Merge with trunk.

master
alainfrisch 2015-12-02 12:00:44 +01:00
commit 90544ab95e
227 changed files with 25562 additions and 509 deletions

117
.depend
View File

@ -111,10 +111,10 @@ typing/cmt_format.cmi : typing/types.cmi typing/typedtree.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/envaux.cmi : typing/subst.cmi typing/path.cmi typing/env.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 \
@ -133,10 +133,10 @@ typing/path.cmi : typing/ident.cmi
typing/predef.cmi : typing/types.cmi typing/path.cmi typing/ident.cmi
typing/primitive.cmi : parsing/parsetree.cmi typing/outcometree.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/printtyped.cmi : typing/typedtree.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
@ -152,11 +152,11 @@ 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/typedtreeIter.cmi : typing/typedtree.cmi parsing/asttypes.cmi
typing/typedtreeMap.cmi : typing/typedtree.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 \
@ -199,6 +199,12 @@ typing/datarepr.cmo : typing/types.cmi typing/path.cmi parsing/location.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 \
@ -211,12 +217,6 @@ typing/env.cmx : utils/warnings.cmx typing/types.cmx utils/tbl.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/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/ident.cmo : typing/ident.cmi
typing/ident.cmx : typing/ident.cmi
typing/includeclass.cmo : typing/types.cmi typing/printtyp.cmi \
@ -281,6 +281,12 @@ typing/primitive.cmo : utils/warnings.cmi parsing/parsetree.cmi \
typing/primitive.cmx : utils/warnings.cmx parsing/parsetree.cmi \
typing/outcometree.cmi utils/misc.cmx parsing/location.cmx \
parsing/attr_helper.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 \
@ -293,12 +299,6 @@ typing/printtyp.cmx : typing/types.cmx typing/primitive.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/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/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 \
@ -365,14 +365,6 @@ typing/typedecl.cmx : utils/warnings.cmx typing/typetexp.cmx \
typing/ident.cmx typing/env.cmx typing/ctype.cmx utils/config.cmx \
utils/clflags.cmx typing/btype.cmx parsing/attr_helper.cmx \
parsing/asttypes.cmi parsing/ast_helper.cmx typing/typedecl.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/typedtreeIter.cmo : typing/typedtree.cmi utils/misc.cmi \
parsing/asttypes.cmi typing/typedtreeIter.cmi
typing/typedtreeIter.cmx : typing/typedtree.cmx utils/misc.cmx \
@ -381,6 +373,14 @@ 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 \
@ -477,13 +477,13 @@ bytecomp/bytelibrarian.cmx : utils/misc.cmx parsing/location.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 \
bytecomp/lambda.cmi bytecomp/instruct.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 \
bytecomp/lambda.cmx bytecomp/instruct.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
@ -633,7 +633,6 @@ bytecomp/typeopt.cmo : typing/types.cmi typing/typedtree.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/CSEgen.cmi : asmcomp/mach.cmi
asmcomp/asmgen.cmi : bytecomp/lambda.cmi asmcomp/cmm.cmi
asmcomp/asmlibrarian.cmi :
asmcomp/asmlink.cmi : asmcomp/cmx_format.cmi
@ -643,19 +642,19 @@ asmcomp/branch_relaxation.cmi : asmcomp/linearize.cmi \
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/cmm.cmi : bytecomp/lambda.cmi typing/ident.cmi asmcomp/debuginfo.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/emit.cmi : asmcomp/linearize.cmi asmcomp/cmm.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
@ -668,8 +667,8 @@ 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/reload.cmi : asmcomp/mach.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 \
@ -683,12 +682,6 @@ 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/CSE.cmo : asmcomp/mach.cmi asmcomp/CSEgen.cmi asmcomp/arch.cmo
asmcomp/CSE.cmx : asmcomp/mach.cmx asmcomp/CSEgen.cmx asmcomp/arch.cmx
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/arch.cmo : utils/clflags.cmi
asmcomp/arch.cmx : utils/clflags.cmx
asmcomp/asmgen.cmo : bytecomp/translmod.cmi asmcomp/split.cmi \
@ -739,14 +732,14 @@ asmcomp/asmpackager.cmx : typing/typemod.cmx bytecomp/translmod.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/branch_relaxation_intf.cmo : asmcomp/linearize.cmi asmcomp/arch.cmo
asmcomp/branch_relaxation_intf.cmx : asmcomp/linearize.cmx asmcomp/arch.cmx
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 \
@ -761,10 +754,6 @@ asmcomp/closure.cmx : utils/warnings.cmx utils/tbl.cmx bytecomp/switch.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/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/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 \
@ -777,16 +766,10 @@ asmcomp/cmmgen.cmx : typing/types.cmx bytecomp/switch.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/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/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/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 \
@ -799,6 +782,12 @@ asmcomp/compilenv.cmo : utils/misc.cmi parsing/location.cmi typing/ident.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 \
@ -807,6 +796,10 @@ 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 \
@ -821,10 +814,6 @@ asmcomp/emit.cmx : asmcomp/x86_proc.cmx asmcomp/x86_masm.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/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/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 \
@ -877,14 +866,14 @@ asmcomp/proc.cmx : asmcomp/x86_proc.cmx asmcomp/reg.cmx utils/misc.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/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/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
@ -939,8 +928,8 @@ driver/compenv.cmi :
driver/compile.cmi :
driver/compmisc.cmi : typing/env.cmi
driver/errors.cmi :
driver/main.cmi :
driver/main_args.cmi :
driver/main.cmi :
driver/optcompile.cmi :
driver/opterrors.cmi :
driver/optmain.cmi :
@ -975,6 +964,8 @@ driver/compmisc.cmx : typing/typemod.cmx utils/misc.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 \
@ -985,8 +976,6 @@ driver/main.cmx : utils/warnings.cmx utils/misc.cmx driver/main_args.cmx \
driver/compile.cmx driver/compenv.cmx utils/clflags.cmx \
bytecomp/bytepackager.cmx bytecomp/bytelink.cmx \
bytecomp/bytelibrarian.cmx driver/main.cmi
driver/main_args.cmo : utils/warnings.cmi driver/main_args.cmi
driver/main_args.cmx : utils/warnings.cmx driver/main_args.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 \

View File

@ -10,26 +10,100 @@
# #
#########################################################################
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
;;
PREFIX=~/local
BuildAndTest () {
case $XARCH in
i386)
echo<<EOF
------------------------------------------------------------------------
This test builds the OCaml compiler distribution with your pull request,
runs its testsuite, and then tries to install some important OCaml softare
(currently camlp4, opam and oasis) on top of it.
Failing to build the compiler distribution, or testsuite failures are
critical errors that must be understood and fixed before your pull
request can be merged. The later installation attempts try to run
bleeding-edge software, and failures can sometimes be out of your
control.
------------------------------------------------------------------------
EOF
mkdir -p $PREFIX
./configure --prefix $PREFIX
export PATH=$PREFIX/bin:$PATH
make world.opt
make install
(cd testsuite && make all)
mkdir external-packages
cd external-packages
git clone git://github.com/ocaml/camlp4
(cd camlp4 &&
./configure --bindir=$PREFIX/bin --libdir=$PREFIX/lib/ocaml \
--pkgdir=$PREFIX/lib/ocaml && \
make && make install)
git clone git://github.com/ocaml/opam
(cd opam && ./configure --prefix $PREFIX &&\
make lib-ext && make && 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
}
CheckChangesModified () {
echo<<EOF
------------------------------------------------------------------------
This test checks that the Changes file has been modified by the pull
request. Most contributions should come with a message in the Changes
file, as described in our contributor documentation:
https://github.com/ocaml/ocaml/blob/trunk/CONTRIBUTING.md#changelog
Some very minor changes (typo fixes for example) may not need
a Changes entry, in which case it is acceptable for this test to fail.
------------------------------------------------------------------------
EOF
# check that Changes has been modified
git diff $TRAVIS_COMMIT_RANGE --name-only --exit-code Changes > /dev/null \
&& exit 1 || echo pass
}
CheckTestsuiteModified () {
echo<<EOF
------------------------------------------------------------------------
This test checks that the OCaml testsuite has been modified by the
pull request. Any new feature should come with tests, bugs should come
with regression tests, and generally any change in behavior that can
be exercized by a test should come with a test or modify and existing
test. See our contributor documentation:
https://github.com/ocaml/ocaml/blob/trunk/CONTRIBUTING.md#test-you-must
Modifications that result in no change in observable behavior
(documentation contributions for example) can hardly be tested, in
which case it is acceptable for this test to fail.
Note: the heuristic used by this test is extremely fragile; passing it
does *not* imply that your change is appropriately tested.
------------------------------------------------------------------------
EOF
# check that at least a file in testsuite/ has been modified
git diff $TRAVIS_COMMIT_RANGE --name-only --exit-code testsuite > /dev/null \
&& exit 1 || echo pass
}
case $CI_KIND in
build) BuildAndTest;;
changes) CheckChangesModified;;
tests) CheckTestsuiteModified;;
*) echo unknown CI kind
exit 1
;;
esac

View File

@ -10,7 +10,14 @@
# #
#########################################################################
sudo: false
language: c
script: bash -ex .travis-ci.sh
env:
- XARCH=i386
matrix:
include:
- env: CI_KIND=build XARCH=i386
- env: CI_KIND=changes
- env: CI_KIND=tests
allow_failures:
- env: CI_KIND=changes
- env: CI_KIND=tests

33
Changes
View File

@ -60,6 +60,9 @@ Language features:
- GPR#282: change short-paths penalty heuristic to assign the same cost to
idents containing double underscores as to idents starting with an underscore
(Thomas Refis, Leo White)
- GPR#273: allow to get the extension slot of an extension constructor
by writing [%extension_constructor <path>]
(Jérémie Dimino)
Compilers:
- PR#4800: better compilation of tuple assignment (Gabriel Scherer and
@ -109,6 +112,8 @@ Compilers:
- GPR#282: relax short-paths safety check in presence of module aliases, take
penalty into account while building the printing map.
(Thomas Refis, Leo White)
- PR#6920: fix debug informations around uses of %apply or %revapply
(Jérémie Dimino)
Runtime system:
- PR#3612: allow allocating custom block with finalizers in the minor heap
@ -119,7 +124,8 @@ Runtime system:
- PR#6760: closures evaluated in the toplevel can now be marshalled
(whitequark, 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)
which is still open (Alain Frisch, review by Damien Doligez);
this is controlled by OCAMLRUNPARAM=W=1 or with Sys.enable_runtime_warnings.
- Signal handling: for read-and-clear, use GCC/Clang atomic builtins
if available. (Xavier Leroy)
- PR#6910, GPR#224: marshaling (output_value, input_value, et al)
@ -170,8 +176,8 @@ Standard library:
(report and fix by Jeremy Yallop)
- GPR#265: new implementation of Queue avoiding Obj.magic
(Jérémie Dimino)
- GPR#268: '%h' and '%H' modifiers for printf and scanf to support
floating-point numbers in hexadecimal notation
- GPR#268, GPR#303: '%h' and '%H' modifiers for printf and scanf to
support floating-point numbers in hexadecimal notation
(Xavier Leroy, Benoît Vaugon)
- GPR#272: Switch classify_float to [@@unboxed] (Alain Frisch)
- Improve speed of classify_float by not going through fpclassify()
@ -225,6 +231,18 @@ OCamlbuild:
- Changed OCamlbuild's license to LGPLv2 with static linking exception.
- GPR#219: speedup target-already-built builds
(ygrek)
- PR#6605, GPR#117: use ocamlfind, if available, to discover camlp4 path
(Vincent Laporte)
OCamldep:
- GRP#286: add support for module aliases
(jacques Garrigue)
Manual:
- GPR#302: The OCaml reference manual is now included in the manual/
subdirectory of the main OCaml source repository. Contributions to
the manual are warmly welcome.
(François Bobot, review by Florian Angeletti)
Bug fixes:
- PR#3612: memory leak in bigarray read from file
@ -281,9 +299,12 @@ Bug fixes:
- PR#6945 and GPR#227: protect Sys and Unix functions against string
arguments containing the null character '\000'
(c-cube and Xavier Leroy, report by Daniel Bünzli)
- PR#6946: Uncaught exception with wrong type for "%ignore"
- PR#6954: Infinite loop in type checker with module aliases
- PR#6972, GPR#276: 4.02.3 regression on documentation comments in .cmt files
(Leo White, report by Olivier Andrieu)
- PR#6980: Assert failure from polymorphic variants and existentials
- PR#6981: Ctype.Unify(_) with associated functor arg refering to previous one
- 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
@ -303,10 +324,14 @@ Bug fixes:
(report and fix by Patrick Star)
- PR#7036: Module alias is not taken into account when checking module
type compatibility (in a class type) (Jacques Garrigue)
- PR#7038: out of memory condition in caml_io_mutex_lock
(Xavier Leroy, report by Marc Lasson)
- PR#7039: Unix.getsockname returns garbage for unnamed PF_UNIX sockets
(Xavier Leroy)
- PR#7042 and GPR#295: CSE optimization confuses the FP literals +0.0 and -0.0
(Xavier Leroy)
- PR#6762: improve warning 45 in presence of re-exported type definitions
(Alain Frisch, report by Olivier Andrieu)
- 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
@ -323,6 +348,8 @@ Bug fixes:
Mark Shinwell)
- GPR#283: Fix memory leaks in intern.c when OOM is raised
(Marc Lasson, review by Alain Frisch)
- GPR#313: Prevent quadratic cases in CSE
(Pierre Chambart, review by Xavier Leroy)
Features wishes:
- PR#4518, GPR#29: change location format for reporting errors in ocamldoc

View File

@ -17,8 +17,8 @@ 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
CAMLC=$(CAMLRUN) boot/ocamlc -g -nostdlib -I boot
CAMLOPT=$(CAMLRUN) ./ocamlopt -g -nostdlib -I stdlib -I otherlibs/dynlink
COMPFLAGS=-strict-sequence -w +33..39+48+50 -warn-error A -bin-annot \
-safe-string $(INCLUDES)
LINKFLAGS=

View File

@ -17,14 +17,51 @@ open Mach
type valnum = int
(* 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 *)
(* 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)
module Equations = struct
module Rhs_map =
Map.Make(struct type t = rhs let compare = Pervasives.compare end)
type 'a t =
{ load_equations : 'a Rhs_map.t;
other_equations : 'a Rhs_map.t }
let empty =
{ load_equations = Rhs_map.empty;
other_equations = Rhs_map.empty }
let add op_class op v m =
match op_class with
| Op_load ->
{ m with load_equations = Rhs_map.add op v m.load_equations }
| _ ->
{ m with other_equations = Rhs_map.add op v m.other_equations }
let find op_class op m =
match op_class with
| Op_load ->
Rhs_map.find op m.load_equations
| _ ->
Rhs_map.find op m.other_equations
let remove_loads m =
{ load_equations = Rhs_map.empty;
other_equations = m.other_equations }
end
type numbering =
{ num_next: int; (* next fresh value number *)
@ -76,9 +113,9 @@ let valnum_regs 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 =
let find_equation op_class n rhs =
try
Some(Equations.find rhs n.num_eqs)
Some(Equations.find op_class rhs n.num_eqs)
with Not_found ->
None
@ -138,9 +175,9 @@ let set_move n src dst =
(* Record the equation [fresh valnums = rhs] and associate the given
result registers [rs] to [fresh valnums]. *)
let set_fresh_regs n rs rhs =
let set_fresh_regs n rs rhs op_class =
let (n1, vs) = fresh_valnum_regs n rs in
{ n1 with num_eqs = Equations.add rhs vs n.num_eqs }
{ n1 with num_eqs = Equations.add op_class rhs vs n.num_eqs }
(* Forget everything we know about the given result registers,
which are receiving unpredictable values at run-time. *)
@ -150,8 +187,8 @@ let set_unknown_regs n rs =
(* 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 }
let remove_load_numbering n =
{ n with num_eqs = Equations.remove_loads n.num_eqs }
(* Forget everything we know about registers of type [Addr]. *)
@ -173,15 +210,6 @@ let insert_move srcs dsts i =
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
@ -217,7 +245,7 @@ method is_cheap_operation op =
non-initializing store *)
method private kill_loads n =
filter_equations (fun o -> self#class_of_operation o <> Op_load) n
remove_load_numbering n
(* Perform CSE on the given instruction [i] and its successors.
[n] is the value numbering current at the beginning of [i]. *)
@ -262,10 +290,10 @@ method private cse n i =
{i with next = self#cse n2 i.next}
| Iop op ->
begin match self#class_of_operation op with
| Op_pure | Op_checkbound | Op_load ->
| (Op_pure | Op_checkbound | Op_load) as op_class ->
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
begin match find_equation op_class n1 (op, varg) with
| Some vres ->
(* This operation was computed earlier. *)
(* Are there registers that hold the results computed earlier? *)
@ -289,7 +317,7 @@ method private cse n i =
end
| None ->
(* This operation produces a result we haven't seen earlier. *)
let n3 = set_fresh_regs n2 i.res (op, varg) in
let n3 = set_fresh_regs n2 i.res (op, varg) op_class in
{i with next = self#cse n3 i.next}
end
| Op_store false | Op_other ->

View File

@ -1,95 +0,0 @@
(***********************************************************************)
(* *)
(* OCaml *)
(* *)
(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
(* *)
(* Copyright 1996 Institut National de 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

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -640,7 +640,8 @@ 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
Pbigarrayref _ | Pbigarrayset _ | Pduprecord _ | Pdirapply _ |
Prevapply _ -> true
| _ -> false
(* Assertions *)
@ -825,6 +826,8 @@ and transl_exp0 e =
Lprim(Pmakeblock(0, Immutable),
transl_path e.exp_env path :: ll)
end
| Texp_extension_constructor (_, path) ->
transl_path e.exp_env path
| Texp_variant(l, arg) ->
let tag = Btype.hash_variant l in
begin match arg with

View File

@ -439,9 +439,28 @@ CAMLexport void caml_finalize_channel(value vchan)
chan->name
);
unlink_channel(chan);
caml_stat_free(chan->name);
caml_stat_free(chan);
if (chan->max == NULL && chan->curr != chan->buff){
/*
This is an unclosed out channel (chan->max == NULL) with a
non-empty buffer: keep it around so the OCaml [at_exit] function
gets a chance to flush it. We would want to simply flush the
channel now, but (i) flushing can raise exceptions, and (ii) it
is potentially a blocking operation. Both are forbidden in a
finalization function.
Refs:
http://caml.inria.fr/mantis/view.php?id=6902
https://github.com/ocaml/ocaml/pull/210
*/
if (chan->name && caml_runtime_warnings_active())
fprintf(stderr,
"[ocaml] (moreover, it has unflushed data)\n"
);
} else {
unlink_channel(chan);
caml_stat_free(chan->name);
caml_stat_free(chan);
}
}
static int compare_channel(value vchan1, value vchan2)

View File

@ -182,7 +182,7 @@ CAMLexport char * caml_strconcat(int n, ...)
/* Runtime warnings */
uintnat caml_runtime_warnings = 1;
uintnat caml_runtime_warnings = 0;
static int caml_runtime_warnings_first = 1;
int caml_runtime_warnings_active(void)

View File

@ -57,6 +57,26 @@ The following command-line options are recognized by
.B \-absname
Show absolute filenames in error messages.
.TP
.B \-all
Generate dependencies on all required files, rather than assuming
implicit dependencies.
.TP
.B \-allow\-approx
Allow falling back on a lexer-based approximation when parsing fails.
.TP
.B \-as\-map
For the following files, do not include delayed dependencies for
module aliases.
This option assumes that they are compiled using options
"\-no\-alias\-deps \-w \-49", and that those files or their interface are
passed with the "\-map" option when computing dependencies for other
files. Note also that for dependencies to be correct in the
implementation of a map file, its interface should not coerce any of
the aliases it contains.
.TP
.B \-debug\-map
Dump the delayed dependency map for each map file.
.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
@ -72,6 +92,22 @@ the same
.B \-I
options that are passed to the compiler.
.TP
.BI \-impl \ file
Process
.IR file
as a .ml file.
.TP
.BI \-intf \ file
Process
.IR file
as a .mli file.
.TP
.BI \-map \ file
Read an propagate the delayed dependencies for module aliases in
.IR file ,
so that the following files will depend on the
exported aliased modules if they use them.
.TP
.BI \-ml\-synonym \ .ext
Consider the given extension (with leading dot) to be a synonym for .ml.
.TP
@ -121,6 +157,9 @@ Pipe abstract syntax tree through preprocessor
.B \-slash
Under Unix, this option does nothing.
.TP
.B \-sort
Sort files according to their dependencies.
.TP
.B \-version
Print version string and exit.
.TP

9
manual/LICENSE Normal file
View File

@ -0,0 +1,9 @@
The present documentation is copyright Institut National de Recherche en Informatique et en Automatique (INRIA).
The OCaml documentation and user's manual may be reproduced and distributed in whole or in part, subject to the following conditions:
- The copyright notice above and this permission notice must be preserved complete on all complete or partial copies.
- Any translation or derivative work of the OCaml documentation and user's manual must be approved by the authors in writing before distribution.
- If you distribute the OCaml documentation and user's manual in part, instructions for obtaining the complete version of this manual must be included, and a means for obtaining a complete version provided.
- Small portions may be reproduced as illustrations for reviews or quotes in other works without this permission notice if proper citation is given.

16
manual/Makefile Normal file
View File

@ -0,0 +1,16 @@
all: tools
cd manual; ${MAKE} all
# cd fpcl; ${MAKE} all
clean:
cd manual; ${MAKE} clean
cd tools; ${MAKE} clean
# cd fpcl; ${MAKE} clean
release:
cd manual; ${MAKE} release
# cd fpcl; ${MAKE} release
.PHONY: tools
tools:
cd tools; ${MAKE} clean; ${MAKE} all

45
manual/README.md Normal file
View File

@ -0,0 +1,45 @@
OCAML DOCUMENTATION
===================
Prerequisites
-------------
- Any prerequisites required to build OCaml from sources.
- The Unix editor 'ed', no longer installed by default on some systems.
- A LaTeX installation.
- The HeVeA LaTeX-to-HTML convertor (available in OPAM):
<http://hevea.inria.fr/>
Note that you must make sure `hevea.sty` is installed into TeX properly. Your
package manager may not do this for you. Run `kpsewhich hevea.sty` to check.
Building
--------
0. Install the OCaml distribution.
1. Run `make` in the manual.
NB: If you already set `LD_LIBRARY_PATH` (OS X: `DYLD_LIBRARY_PATH`)
in you environnement don't forget to add
`otherlibs/unix:otherlibs/str` to it in an absolute way.
Outputs
-------
In the manual:
- The HTML Manual is in directory `htmlman`. The main file is `index.html`.
- The plain text manual is in direcory `textman` as file `manual.txt`.
- The Info manual is in directory `infoman`.
- The DVI manual is in directory `texstuff` as file `manual.dvi`.
- The PDF manual is in directory `texstuff` as file `pdfmanual.pdf`.

7
manual/manual/.cvsignore Normal file
View File

@ -0,0 +1,7 @@
allfiles.tex
biblio.tex
foreword.tex
version.tex
warnings-help.etex
foreword.htex
manual.html

8
manual/manual/.gitignore vendored Normal file
View File

@ -0,0 +1,8 @@
allfiles.tex
biblio.tex
foreword.tex
version.tex
warnings.etex
warnings.tex
foreword.htex
manual.html

143
manual/manual/Makefile Normal file
View File

@ -0,0 +1,143 @@
# $Id$
FILES=allfiles.tex biblio.tex foreword.tex version.tex warnings-help.etex
TEXINPUTS=.:..:../refman:../library:../cmds:../tutorials:../../styles:
TEXFONTS=../../styles:
RELEASE=$$HOME/release/$${RELEASENAME}
HEVEA=hevea
HACHA=hacha
INFO=-fix -exec xxdate.exe -info -w 79
HTML=-fix -exec xxdate.exe -O
TEXT=-fix -exec xxdate.exe -text -w 79
SRC = $(abspath ../../)
export LD_LIBRARY_PATH ?= $(SRC)/otherlibs/unix/:$(SRC)/otherlibs/str/
export DYLD_LIBRARY_PATH ?= $(SRC)/otherlibs/unix/:$(SRC)/otherlibs/str/
OCAMLDOC=$(SRC)/byterun/ocamlrun $(SRC)/ocamldoc/ocamldoc -hide Pervasives
MLIS=$(SRC)/stdlib/*.mli \
$(SRC)/utils/*.mli \
$(SRC)/parsing/*.mli \
$(SRC)/otherlibs/bigarray/bigarray.mli \
$(SRC)/otherlibs/dynlink/dynlink.mli \
$(SRC)/otherlibs/graph/graphics.mli \
$(SRC)/otherlibs/graph/graphicsX11.mli \
$(SRC)/otherlibs/num/num.mli \
$(SRC)/otherlibs/num/arith_status.mli \
$(SRC)/otherlibs/num/big_int.mli \
$(SRC)/otherlibs/num/ratio.mli \
$(SRC)/otherlibs/str/*.mli \
$(SRC)/otherlibs/systhreads/*.mli \
$(SRC)/otherlibs/unix/*.mli
manual: files
cd texstuff; \
TEXINPUTS=$(TEXINPUTS) latex manual.tex
labltk: cmds/browser.tex library/liblabltk.tex library/tk.mli
cd library; $(MAKE) Tk.tex RELEASEDIR=$(SRC)
cd texstuff; \
TEXINPUTS=$(TEXINPUTS) latex labltk.tex
index::
cd texstuff && \
../../tools/fix_index.sh manual.idx && \
makeindex manual.idx
cd texstuff; makeindex manual.kwd.idx
pdfmanual: files
cd texstuff; \
TEXINPUTS=$(TEXINPUTS) pdflatex pdfmanual.tex
index::
cd texstuff && \
../../tools/fix_index.sh pdfmanual.idx && \
makeindex pdfmanual.idx
cd texstuff; makeindex pdfmanual.kwd.idx
html: files
cd htmlman; \
mkdir -p libref ; \
$(OCAMLDOC) -colorize-code -sort -html \
-d libref \
-I $(SRC)/stdlib \
-I $(SRC)/utils \
-I $(SRC)/parsing \
-I $(SRC)/otherlibs/bigarray \
-I $(SRC)/otherlibs/dynlink \
-I $(SRC)/otherlibs/graph \
-I $(SRC)/otherlibs/num \
-I $(SRC)/otherlibs/str \
-I $(SRC)/otherlibs/systhreads \
-I $(SRC)/otherlibs/unix \
$(MLIS) ; \
cp -f ../style.css libref ; \
${HEVEA} ${HTML} -I .. -I ../refman -I ../library -I ../cmds \
-I ../tutorials -I ../../styles -I ../texstuff manual.hva \
-e macros.tex ../manual.tex ; \
${HACHA} -tocter manual.html ; \
info: files
cd infoman; rm -f ocaml.info*; \
${HEVEA} ${INFO} -o ocaml.info.body -I .. -I ../refman -I ../library \
-I ../cmds -I ../tutorials -I ../../styles -I ../texstuff \
../manual.inf -e macros.tex ../manual.tex
cat manual.info.header infoman/ocaml.info.body > infoman/ocaml.info
cd infoman; rm -f ocaml.info.tmp; gzip -9 ocaml.info*
text: files
cd textman; \
${HEVEA} ${TEXT} -I .. -I ../refman -I ../library -I ../cmds \
-I ../tutorials -I ../../styles -I ../texstuff \
../manual.inf -e macros.tex ../manual.tex
files: $(FILES)
cd refman; $(MAKE) all RELEASEDIR=$(SRC)
cd library; $(MAKE) all RELEASEDIR=$(SRC)
cd cmds; $(MAKE) all RELEASEDIR=$(SRC)
cd tutorials; $(MAKE) all RELEASEDIR=$(SRC)
all:
$(MAKE) manual pdfmanual RELEASEDIR=$(SRC)
$(MAKE) manual pdfmanual RELEASEDIR=$(SRC)
$(MAKE) index RELEASEDIR=$(SRC)
$(MAKE) manual pdfmanual RELEASEDIR=$(SRC)
$(MAKE) html text info RELEASEDIR=$(SRC)
clean:
rm -f $(FILES)
cd refman; $(MAKE) clean
cd library; $(MAKE) clean
cd cmds; $(MAKE) clean
cd tutorials; $(MAKE) clean
-rm -f texstuff/*
cd htmlman; rm -rf libref index.html manual*.html *.haux *.hind
cd textman; rm -f manual.txt *.haux *.hind
cd infoman; rm -f ocaml.info ocaml.info-* *.haux *.hind
rm -f warnings-help.etex
release:
gzip < texstuff/manual.dvi > $(RELEASE)refman.dvi.gz
dvips -o '!gzip > $(RELEASE)refman.ps.gz' texstuff/manual.dvi
cp htmlman/manual.html $(RELEASE)refman.html
rm -f htmlman/manual.{html,haux,hmanual*,htoc}
tar zcf $(RELEASE)refman-html.tar.gz htmlman/*.* htmlman/libref
zip -8 $(RELEASE)refman-html.zip htmlman/*.* htmlman/libref/*.*
cp texstuff/pdfmanual.pdf $(RELEASE)refman.pdf
cp textman/manual.txt $(RELEASE)refman.txt
tar cf - infoman/ocaml.info* | gzip > $(RELEASE)refman.info.tar.gz
.SUFFIXES:
.SUFFIXES: .tex .etex .htex
.etex.tex:
../tools/texquote2 < $*.etex > $*.tex
version.tex: $(SRC)/VERSION
sed -n -e '1s/^\([0-9]*\.[0-9]*\).*$$/\\def\\ocamlversion{\1}/p' \
$(SRC)/VERSION > version.tex
warnings-help.etex: $(SRC)/utils/warnings.ml $(SRC)/ocamlc
$(SRC)/boot/ocamlrun $(SRC)/ocamlc -warn-help \
| sed -e 's/^ *\([0-9A-Z][0-9]*\)\(.*\)/\\item[\1] \2/' >$@

105
manual/manual/allfiles.etex Normal file
View File

@ -0,0 +1,105 @@
\makeindex{\jobname}
\makeindex{\jobname.kwd}
\setlength{\emergencystretch}{50pt} % pour que TeX resolve les overfull hbox lui-meme
\begin{document}
\thispagestyle{empty}
\begin{center}
~\vfill
\Huge The OCaml system \\
release \ocamlversion \\[1cm]
\Large Documentation and user's manual \\[1cm]
\large Xavier Leroy, \\
Damien Doligez, Alain Frisch, Jacques Garrigue, Didier Rémy and Jérôme Vouillon \\[1cm]
\today \\
~
\vfill
\normalsize Copyright \copyright\ \number\year\ Institut National de
Recherche en Informatique et en Automatique
\end{center}
\cleardoublepage
\setcounter{page}{1}
\begin{htmlonly}
\begin{quote}
\rule{}{}
This manual is also available in
\ahref{http://caml.inria.fr/distrib/ocaml-\ocamlversion/ocaml-\ocamlversion-refman.pdf}{PDF}.
\ahref{http://caml.inria.fr/distrib/ocaml-\ocamlversion/ocaml-\ocamlversion-refman.ps.gz}{Postscript},
\ahref{http://caml.inria.fr/distrib/ocaml-\ocamlversion/ocaml-\ocamlversion-refman.dvi.gz}{DVI},
\ahref{http://caml.inria.fr/distrib/ocaml-\ocamlversion/ocaml-\ocamlversion-refman.txt}{plain text},
as a
\ahref{http://caml.inria.fr/distrib/ocaml-\ocamlversion/ocaml-\ocamlversion-refman-html.tar.gz}{bundle of HTML files},
and as a
\ahref{http://caml.inria.fr/distrib/ocaml-\ocamlversion/ocaml-\ocamlversion-refman.info.tar.gz}{bundle of Emacs Info files}.
\rule{}{}
\end{quote}
\end{htmlonly}
\tableofcontents
\input{foreword.tex}
\part{An introduction to OCaml}
\label{p:tutorials}
\input{coreexamples.tex}
\input{moduleexamples.tex}
\input{objectexamples.tex}
\input{lablexamples.tex}
\input{advexamples.tex}
\part{The OCaml language}
\label{p:refman}
\input{refman.tex}
\input{exten.tex}
\part{The OCaml tools}
\label{p:commands}
\input{comp.tex}
\input{top.tex}
\input{runtime.tex}
\input{native.tex}
\input{lexyacc.tex}
\input{depend.tex}
\input{browser.tex}
\input{ocamldoc.tex}
\input{debugger.tex}
\input{profil.tex}
\input{ocamlbuild.tex}
% \input emacs.tex
\input{intf-c.tex}
\part{The OCaml library}
\label{p:library}
\input{core.tex}
\input{stdlib.tex}
\input{compilerlibs.tex}
\input{libunix.tex}
\input{libnum.tex}
\input{libstr.tex}
\input{libthreads.tex}
\input{libgraph.tex}
\input{libdynlink.tex}
\input{libbigarray.tex}
\part{Appendix}
\label{p:appendix}
\ifouthtml
\begin{links}
\item \ahref{libref/index_modules.html}{Index of modules}
\item \ahref{libref/index_module_types.html}{Index of module types}
\item \ahref{libref/index_types.html}{Index of types}
\item \ahref{libref/index_exceptions.html}{Index of exceptions}
\item \ahref{libref/index_values.html}{Index of values}
\end{links}
\else
\printindex{\jobname}{Index to the library}
\fi
\printindex{\jobname.kwd}{Index of keywords}
\end{document}

240
manual/manual/biblio.etex Normal file
View File

@ -0,0 +1,240 @@
\chapter{Further reading}
For the interested reader, we list below some references to books and
reports related (sometimes loosely) to Caml Light.
\section{Programming in ML}
The books below are programming courses taught in ML. Their main goal
is to teach programming, not to describe ML in full details --- though
most contain fairly good introductions to the ML language. Some of
those books use the Standard ML dialect instead of the Caml dialect,
so you will have to keep in mind the differences in syntax and in
semantics.
\begin{itemize}
\item Pierre Weis and Xavier Leroy. {\it Le langage Caml.}
InterÉditions, 1993.
The natural companion to this manual, provided you read French. This
book is a step-by-step introduction to programming in Caml, and
presents many realistic examples of Caml programs.
\item Guy Cousineau and Michel Mauny. {\it Approche fonctionnelle de
la programmation}. Ediscience, 1995.
Another Caml programming course written in French, with many original
examples.
\item Lawrence C.\ Paulson. {\it ML for the working programmer.}
Cambridge University Press, 1991.
A good introduction to programming in Standard ML. Develops a
theorem prover as a complete example. Contains a presentation of
the module system of Standard ML.
\item Jeffrey D.\ Ullman. {\it Elements of ML programming.}
Prentice Hall, 1993.
Another good introduction to programming in Standard ML. No realistic
examples, but a very detailed presentation of the language constructs.
\item Ryan Stansifer. {\em ML primer.} Prentice-Hall, 1992.
A short, but nice introduction to programming in Standard ML.
\item Thérèse Accart Hardin and Véronique Donzeau-Gouge Viguié. {\em
Concepts et outils de la programmation. Du fonctionnel à
l'impératif avec Caml et Ada.} InterÉditions, 1992.
A first course in programming, that first introduces the main programming
notions in Caml, then shows them underlying Ada. Intended for
beginners; slow-paced for the others.
\item Rachel Harrison. {\em Abstract Data Types in Standard ML}.
John Wiley \& Sons, 1993.
A presentation of Standard ML from the standpoint of abstract data
types. Uses intensively the Standard ML module system.
\item Harold Abelson and Gerald Jay Sussman.
{\em Structure and Interpretation of Computer Programs.} The MIT
press, 1985. (French translation: {\em Structure et interprétation
des programmes informatiques}, InterÉditions, 1989.)
An outstanding course on programming, taught in Scheme, the modern
dialect of Lisp. Well worth reading, even if you are more interested
in ML than in Lisp.
\end{itemize}
\section{Descriptions of ML dialects}
The books and reports below are descriptions of various programming
languages from the ML family. They assume some familiarity with ML.
\begin{itemize}
\item Xavier Leroy and Pierre Weis. {\em Manuel de référence du
langage Caml.} InterÉditions, 1993.
The French edition of the present reference manual and user's manual.
\item Robert Harper. {\em Introduction to Standard ML.} Technical
report ECS-LFCS-86-14, University of Edinburgh, 1986.
An overview of Standard ML, including the module system. Terse, but
still readable.
\item Robin Milner, Mads Tofte and Robert Harper. {\em The definition
of Standard ML.} The MIT press, 1990.
A complete formal definition of Standard ML, in the framework of
structured operational semantics. This book is probably the most
mathematically precise definition of a programming language ever
written. It is heavy on formalism and extremely terse, so
even readers who are thoroughly familiar with ML will have
major difficulties with it.
\item Robin Milner and Mads Tofte. {\em Commentary on Standard ML.}
The MIT Press, 1991.
A commentary on the book above, that attempts to explain the most
delicate parts and motivate the design choices. Easier to read than the
Definition, but still rather involving.
\item Guy Cousineau and Gérard Huet. {\em The CAML primer.} Technical
report~122, INRIA, 1990.
A short description of the original Caml system, from which Caml Light
has evolved. Some familiarity with Lisp is assumed.
\item Pierre Weis et al. {\em The CAML reference manual, version
2.6.1.} Technical report~121, INRIA, 1990.
The manual for the original Caml system, from which Caml Light
has evolved.
\item Michael J.\ Gordon, Arthur J.\ Milner and Christopher P.\ Wadsworth.
{\em Edinburgh LCF.} Lecture Notes in Computer Science
volume~78, Springer-Verlag, 1979.
This is the first published description of the ML language, at the
time when it was nothing more than the control language for the LCF
system, a theorem prover. This book is now obsolete, since the ML
language has much evolved since then; but it is still of historical
interest.
\item Paul Hudak, Simon Peyton-Jones and Philip Wadler. {\em
Report on the programming language Haskell, version 1.1.} Technical
report, Yale University, 1991.
Haskell is a purely functional language with lazy semantics that
shares many important points with ML (full functionality, polymorphic
typing), but has interesting features of its own (dynamic overloading,
also called type classes).
\end{itemize}
\section{Implementing functional programming languages}
The references below are intended for those who are curious to learn
how a language like Caml Light is compiled and implemented.
\begin{itemize}
\item Xavier Leroy. {\em The ZINC experiment: an economical
implementation of the ML language.} Technical report~117, INRIA, 1990.
(Available by anonymous FTP on "ftp.inria.fr".)
A description of the ZINC implementation, the prototype ML
implementation that has evolved into Caml Light. Large parts of this
report still apply to the current Caml Light system, in particular the
description of the execution model and abstract machine. Other parts
are now obsolete. Yet this report still gives a complete overview of the
implementation techniques used in Caml Light.
\item Simon Peyton-Jones. {\em The implementation of functional
programming languages.} Prentice-Hall, 1987. (French translation:
{\em Mise en \oe uvre des langages fonctionnels de programmation},
Masson, 1990.)
An excellent description of the implementation of purely functional
languages with lazy semantics, using the technique known as graph
reduction. The part of the book that deals with the transformation
from ML to enriched lambda-calculus directly applies to Caml Light.
You will find a good description of how pattern-matching is compiled
and how types are inferred. The remainder of the book does not apply
directly to Caml Light, since Caml Light is not purely functional (it
has side-effects), has strict semantics, and does not use graph
reduction at all.
\item Andrew W.\ Appel. {\em Compiling with continuations.} Cambridge
University Press, 1992.
A complete description of an optimizing compiler for Standard ML,
based on an intermediate representation called continuation-passing
style. Shows how many advanced program optimizations can be applied to
ML. Not directly relevant to the Caml Light system, since Caml Light
does not use continuation-passing style at all, and makes little
attempts at optimizing programs.
\end{itemize}
\section{Applications of ML}
The following reports show ML at work in various, sometimes
unexpected, areas.
\begin{itemize}
\item Emmanuel Chailloux and Guy Cousineau. {\em The MLgraph primer.}
Technical report 92-15, École Normale Supérieure, 1992. (Available by
anonymous FTP on "ftp.ens.fr".)
%, répertoire "biblio", fichier
% "liens-92-15.A4.300dpi.ps.Z".)
Describes a Caml Light library that produces Postscript pictures
through high-level drawing functions.
\item Xavier Leroy. {\em Programmation du système Unix en Caml Light.}
Technical report~147, INRIA, 1992. (Available by anonymous FTP on
"ftp.inria.fr".)
%, répertoire "INRIA/publication", fichier "RT-0147.ps.Z".)
A Unix systems programming course, demonstrating the use of the Caml
Light library that gives access to Unix system calls.
\item John H.\ Reppy. {\em Concurrent programming with events --- The
concurrent ML manual.} Cornell University, 1990.
(Available by anonymous FTP on "research.att.com".)
%, répertoire "dist/ml", fichier "CML-0.9.8.tar.Z".)
Concurrent ML extends Standard ML of New Jersey with concurrent
processes that communicate through channels and events.
\item Jeannette M. Wing, Manuel Faehndrich, J.\ Gregory Morrisett and
Scottt Nettles. {\em Extensions to Standard ML to support
transactions.} Technical report CMU-CS-92-132, Carnegie-Mellon
University, 1992. (Available by anonymous FTP on
"reports.adm.cs.cmu.edu".)
% , répertoire "1992", fichier "CMU-CS-92-132.ps".)
How to integrate the basic database operations to Standard ML.
\item Emden R.\ Gansner and John H.\ Reppy. {\em eXene.} Bell Labs,
1991. (Available by anonymous FTP on "research.att.com".)
%, répertoire "dist/ml", fichier "eXene-0.4.tar.Z".)
An interface between Standard ML of New Jersey and the X Windows
windowing system.
%% \item Daniel de Rauglaudre. {\em X toolkit in Caml Light.} INRIA,
%% 1992. (Included in the Caml Light distribution.)
%% % Disponible par FTP anonyme sur
%% % "ftp.inria.fr", répertoire "lang/caml-light", fichier "rt5.tar.Z".)
%%
%% An interface between Caml Light and the X Windows windowing system.
\end{itemize}

View File

@ -0,0 +1,2 @@
*.tex
*.htex

3
manual/manual/cmds/.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
*.tex
*.htex
warnings.etex

View File

@ -0,0 +1,40 @@
FILES=comp.tex top.tex runtime.tex native.tex lexyacc.tex intf-c.tex \
depend.tex profil.tex debugger.tex browser.tex ocamldoc.tex \
warnings-help.tex ocamlbuild.tex
TRANSF=../../tools/transf
TEXQUOTE=../../tools/texquote2
FORMAT=../../tools/format-intf
all: $(FILES)
clean::
rm -f $(FILES)
rm -f *~ #*#
.SUFFIXES:
.SUFFIXES: .tex .etex
.etex.tex:
$(TEXQUOTE) < $*.etex > $*.tex
ocamldoc.tex: ocamldoc.etex $(TRANSF)
$(TRANSF) < ocamldoc.etex | $(TEXQUOTE) > ocamldoc.tex
top.tex: top.etex $(TRANSF)
$(TRANSF) < top.etex | $(TEXQUOTE) > top.tex
intf-c.tex: intf-c.etex $(TRANSF)
$(TRANSF) < intf-c.etex | $(TEXQUOTE) > intf-c.tex
lexyacc.tex: lexyacc.etex $(TRANSF)
$(TRANSF) < lexyacc.etex | $(TEXQUOTE) > lexyacc.tex
debugger.tex: debugger.etex $(TRANSF)
$(TRANSF) < debugger.etex | $(TEXQUOTE) > debugger.tex
warnings-help.etex: ../warnings-help.etex
cp ../warnings-help.etex .
clean::
rm -f warnings-help.etex

View File

@ -0,0 +1,183 @@
\chapter{The browser/editor (ocamlbrowser)} \label{c:browser}
\pdfchapter{The browser/editor (ocamlbrowser)}
%HEVEA\cutname{browser.html}
This chapter describes OCamlBrowser, a source and compiled interface
browser, written using LablTk. This is a useful companion to the
programmer.
Its functions are:
\begin{itemize}
\item navigation through OCaml's modules (using compiled interfaces).
\item source editing, type-checking, and browsing.
\item integrated OCaml shell, running as a subprocess.
\end{itemize}
\section{Invocation} \label{s:browser-options}
The browser is started by the command "ocamlbrowser", as follows:
\begin{alltt}
ocamlbrowser \var{options}
\end{alltt}
The following command-line options are recognized by "ocamlbrowser".
\begin{options}
\item["-I" \var{directory}]
Add the given directory to the list of directories searched for
source and compiled files. By default, only the standard library
directory is searched. The standard library can also be changed by
setting the "OCAMLLIB" environment variable.
\item["-nolabels"]
Ignore non-optional labels in types. Labels cannot be used in
applications, and parameter order becomes strict.
\item["-oldui"]
Old multi-window interface. The default is now more like Smalltalk's
class browser.
\item["-rectypes"]
Allow arbitrary recursive types during type-checking. By default,
only recursive types where the recursion goes through an object type
are supported.
\item["-version"]
Print version string and exit.
\item["-vnum"]
Print short version number and exit.
\item["-w" \var{warning-list}]
Enable or disable warnings according to the argument \var{warning-list}.
\end{options}
Most options can also be modified inside the application by the {\bf
Modules - Path editor} and {\bf Compiler - Preferences} commands.
They are inherited when you start a toplevel shell.
\section{Viewer}
This is the first window you get when you start OCamlBrowser.
It displays a search window, and the list of modules in the load path.
At the top a row of menus.
\begin{itemize}
\item {\bf File - Open} and {\bf File - Editor} give access to the
editor.
\item {\bf File - Shell} creates an OCaml subprocess in a shell.
\item {\bf View - Show all defs} displays the signature of the currently
selected module.
\item {\bf View - Search entry} shows/hides the search entry just
below the menu bar.
\item {\bf Modules - Path editor} changes the load path. {\bf Modules
- Reset cache} rescans the load path and resets the module cache.
Do it if you recompile some interface, or get confused about what is
in the cache.
\item {\bf Modules - Search symbol} allows searching a symbol either
by its name, like the bottom line of the viewer, or more
interestingly, by its type. {\bf Exact type} searches for a type
with exactly the same information as the pattern (variables match
only variables). {\bf Included type} allows giving only partial
information: the actual type may take more arguments and return more
results, and variables in the pattern match anything. In both cases,
argument and tuple order is irrelevant\footnote{To avoid
combinatorial explosion of the search space, optional arguments in
the actual type are ignored in the actual if (1) there are too many
of them, and (2) they do not appear explicitly in the pattern.},
and unlabeled arguments in the pattern match any label.
\item The {\bf Search entry} just below the menu bar allows one to
search for an identifier in all modules (wildcards ``?'' and ``*''
allowed). If you choose the "type" option, the search is done by type
inclusion ({\em cf.} Search Symbol - Included type).
\item The {\bf Close all} button is there to dismiss the windows
created by the Detach button.
By double-clicking on it you will quit the browser.
\end{itemize}
\section{Module browsing}
You select a module in the leftmost box by either clicking on it or
pressing return when it is selected. Fast access is available in all
boxes pressing the first few letter of the desired name.
Double-clicking / double-return displays the whole signature for the
module.
Defined identifiers inside the module are displayed in a box to the
right of the previous one. If you click on one, this will either
display its contents in another box (if this is a sub-module) or
display the signature for this identifier below.
Signatures are clickable. Double clicking with the left mouse
button on an identifier in a signature brings you to its signature.
A single click on the right button pops up a menu displaying the
type declaration for the selected identifier. Its title, when
selectable, also brings you to its signature.
At the bottom, a series of buttons, depending on the context.
\begin{itemize}
\item {\bf Detach} copies the currently displayed signature in a new window,
to keep it.
\item {\bf Impl} and {\bf Intf} bring you to the implementation or
interface of the currently displayed signature, if it is available.
\end{itemize}
Control-S lets you search a string in the signature.
\section{File editor}
You can edit files with it, if you're not yet used to emacs. Otherwise
you can use it as a browser, making occasional corrections.
The {\bf Edit} menu contains commands for jump (C-g), search (C-s),
and sending the current phrase (or selection if some text is selected)
to a sub-shell (M-x). For this last option, you may choose the shell
via a dialog.
Essential functions are in the {\bf Compiler} menu.
\begin{itemize}
\item {\bf Preferences} opens a dialog to set internals of the editor
and type-checker.
\item {\bf Lex} adds colors according to lexical categories.
\item {\bf Typecheck} verifies typing, and memorizes to let one see an
expression's type by double-clicking on it. This is also valid for
interfaces. If an error occurs, the part of the interface preceding
the error is computed.
After typechecking, pressing the right button pops up a menu that gives
the type of the pointed expression and, where applicable, provides
some links that can be followed.
\item {\bf Clear errors} dismisses type-checker error messages and warnings.
\item {\bf Signature} shows the signature of the current file
(after type checking).
\end{itemize}
\section{Shell}
When you create a shell, a dialog is presented to you, letting you
choose which command you want to run, and the title of the shell (to
choose it in the Editor).
%You may change the default command by setting the "OCAML"
%environment variable.
The executed subshell is given the current load path.
\begin{itemize}
\item {\bf File} use a source file or load a bytecode file. You may
also import the browser's path into the subprocess.
\item {\bf History} M-p and M-n browse up and down.
\item {\bf Signal} C-c interrupts, and you can also kill the subprocess.
\end{itemize}

View File

@ -0,0 +1,720 @@
\chapter{Batch compilation (ocamlc)} \label{c:camlc}
\pdfchapter{Batch compilation (ocamlc)}
%HEVEA\cutname{comp.html}
This chapter describes the OCaml batch compiler "ocamlc",
which 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
"ocamlrun".
\section{Overview of the compiler}
The "ocamlc" command has a command-line interface similar to the one of
most C compilers. It accepts several types of arguments and processes them
sequentially:
\begin{itemize}
\item
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 \var{x}".mli", the "ocamlc" compiler produces a compiled interface
in the file \var{x}".cmi".
\item
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 \var{x}".ml", the "ocamlc"
compiler produces compiled object bytecode in the file \var{x}".cmo".
If the interface file \var{x}".mli" exists, the implementation
\var{x}".ml" is checked against the corresponding compiled interface
\var{x}".cmi", which is assumed to exist. If no interface
\var{x}".mli" is provided, the compilation of \var{x}".ml" produces a
compiled interface file \var{x}".cmi" in addition to the compiled
object code file \var{x}".cmo". The file \var{x}".cmi" produced
corresponds to an interface that exports everything that is defined in
the implementation \var{x}".ml".
\item
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 \var{x}".cmo" file must come
before all ".cmo" files that refer to the unit \var{x}.
\item
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 "ocamlc -a"
(see the description of the "-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.
\item
Arguments ending in ".c" are passed to the C compiler, which generates
a ".o" object file (".obj" under Windows). This object file is linked
with the program if the "-custom" flag is set (see the description of
"-custom" below).
\item
Arguments ending in ".o" or ".a" (".obj" or ".lib" under Windows)
are assumed to be C object files and libraries. They are passed to the
C linker when linking in "-custom" mode (see the description of
"-custom" below).
\item
Arguments ending in ".so" (".dll" under Windows)
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 "ocamlrun" then loads them dynamically at program
start-up time.
\end{itemize}
The output of the linking phase is a file containing compiled bytecode
that can be executed by the OCaml bytecode interpreter:
the command named "ocamlrun". If "a.out" is the name of the file
produced by the linking phase, the command
\begin{alltt}
ocamlrun a.out \nth{arg}{1} \nth{arg}{2} \ldots \nth{arg}{n}
\end{alltt}
executes the compiled code contained in "a.out", passing it as
arguments the character strings \nth{arg}{1} to \nth{arg}{n}.
(See chapter~\ref{c:runtime} for more details.)
On most systems, the file produced by the linking
phase can be run directly, as in:
\begin{alltt}
./a.out \nth{arg}{1} \nth{arg}{2} \ldots \nth{arg}{n}
\end{alltt}
The produced file has the executable bit set, and it manages to launch
the bytecode interpreter by itself.
\section{Options}\label{s:comp-options}
The following command-line options are recognized by "ocamlc".
The options "-pack", "-a", "-c" and "-output-obj" are mutually exclusive.
\begin{options}
\item["-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 "-o" option.
If "-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 "-custom",
"-cclib" and "-ccopt" options as if they had been provided on the
command line, unless the "-noautolink" option is given.
\item["-absname"]
Force error messages to show absolute paths for file names.
\item["-annot"]
Dump detailed information about the compilation (types, bindings,
tail-calls, etc). The information for file \var{src}".ml"
is put into file \var{src}".annot". In case of a type error, dump
all the information inferred by the type-checker before the error.
The \var{src}".annot" file can be used with the emacs commands given in
"emacs/caml-types.el" to display types and other annotations
interactively.
\item["-bin-annot"]
Dump detailed information about the compilation (types, bindings,
tail-calls, etc) in binary format. The information for file \var{src}".ml"
is put into file \var{src}".cmt". In case of a type error, dump
all the information inferred by the type-checker before the error.
The "*.cmt" files produced by "-bin-annot" contain more information
and are much more compact than the files produced by "-annot".
\item["-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.
\item["-cc" \var{ccomp}]
Use \var{ccomp} as the C linker when linking in ``custom runtime''
mode (see the "-custom" option)
and as the C compiler for compiling ".c" source files.
\item["-cclib" "-l"\var{libname}]
Pass the "-l"\var{libname} option to the C linker when linking in
``custom runtime'' mode (see the "-custom" option). This causes the
given C library to be linked with the program.
\item["-ccopt" \var{option}]
Pass the given option to the C compiler and linker. When linking in
``custom runtime'' mode, for instance,
"-ccopt -L"\var{dir} causes the C linker to search for C libraries in
directory \var{dir}. (See the "-custom" option.)
\item["-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.
\item["-config"]
Print the version number of "ocamlc" and a detailed summary of its
configuration, then exit.
\item["-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, "ocamlrun". 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 "ocamlrun" command is not
installed. Moreover, the ``custom runtime'' mode enables static
linking of OCaml code with user-defined C functions, as described in
chapter~\ref{c:intf-c}.
\begin{unix}
Never use the "strip" command on executables produced by "ocamlc -custom",
this would remove the bytecode part of the executable.
\end{unix}
\item["-dllib" "-l"\var{libname}]
Arrange for the C shared library "dll"\var{libname}".so"
("dll"\var{libname}".dll" under Windows) to be loaded dynamically
by the run-time system "ocamlrun" at program start-up time.
\item["-dllpath" \var{dir}]
Adds the directory \var{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 "-I" option).
The "-dllpath" option simply stores \var{dir} in the produced
executable file, where "ocamlrun" can find it and use it as
described in section~\ref{s-ocamlrun-dllpath}.
\item["-for-pack" \var{ident}]
This option is accepted for compatibility with "ocamlopt"; it does
nothing.
\item["-g"]
Add debugging information while compiling and linking. This option is
required in order to be able to debug the program with "ocamldebug"
(see chapter~\ref{c:debugger}), and to produce stack backtraces when
the program terminates on an uncaught exception (see
section~\ref{ocamlrun-options}).
\item["-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.
\item["-I" \var{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
"-cclib -lxxx". 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 "-nostdlib".
If the given directory starts with "+", it is taken relative to the
standard library directory. For instance, "-I +labltk" adds the
subdirectory "labltk" of the standard library to the search path.
\item["-impl" \var{filename}]
Compile the file \var{filename} as an implementation file, even if its
extension is not ".ml".
\item["-intf" \var{filename}]
Compile the file \var{filename} as an interface file, even if its
extension is not ".mli".
\item["-intf-suffix" \var{string}]
Recognize file names ending with \var{string} as interface files
(instead of the default ".mli").
\item["-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.
\item["-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 "-a"), setting the "-linkall" option forces all
subsequent links of programs involving that library to link all the
modules contained in the library.
\item["-make-runtime"]
Build a custom runtime system (in the file specified by option "-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
"ocamlc -use-runtime" \var{runtime-name} option.
See section~\ref{s:custom-runtime} for more information.
\item["-no-alias-deps"]
Do not record dependencies for module aliases. See
section~\ref{s:module-alias} for more information.
\item["-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.
\item["-noassert"]
Do not compile assertion checks. Note that the special form
"assert false" is always compiled because it is typed specially.
This flag has no effect when linking already-compiled files.
\item["-noautolink"]
When linking ".cma" libraries, ignore "-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 "-noautolink" and pass the correct C
libraries and options on the command line.
\item["-nolabels"]
Ignore non-optional labels in types. Labels cannot be used in
applications, and parameter order becomes strict.
\item["-nostdlib"]
Do not include the standard library directory in the list of
directories searched for
compiled interface files (".cmi"), compiled object code files
(".cmo"), libraries (".cma"), and C libraries specified with
"-cclib -lxxx". See also option "-I".
\item["-o" \var{exec-file}]
Specify the name of the output file produced by the compiler. The
default output name is "a.out" under Unix and "camlprog.exe" under
Windows. If the "-a" option is given, specify the name of the library
produced. If the "-pack" option is given, specify the name of the
packed object file produced. If the "-output-obj" option is given,
specify the name of the output file produced. If the "-c" option is
given, specify the name of the object file produced for the {\em next}
source file that appears on the command line.
\item["-open" \var{Module}]
Opens the given module before processing the interface or
implementation files. If several "-open" options are given,
they are processed in order, just as if
the statements "open!" \var{Module1}";;" "..." "open!" \var{ModuleN}";;"
were added at the top of each file.
\item["-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. See chapter~\ref{c:intf-c},
section~\ref{s:embedded-code}. The name of the output object file
must be set with the "-o" option. This
option can also be used to produce a C source file (".c" extension) or
a compiled shared/dynamic library (".so" extension, ".dll" under Windows).
\item["-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 "-o" option. For instance,
\begin{verbatim}
ocamlc -pack -o p.cmo a.cmo b.cmo c.cmo
\end{verbatim}
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.
\item["-pp" \var{command}]
Cause the compiler to call the given \var{command} as a preprocessor
for each source file. The output of \var{command} is redirected to
an intermediate file, which is compiled. If there are no compilation
errors, the intermediate file is deleted afterwards.
\item["-ppx" \var{command}]
After parsing, pipe the abstract syntax tree through the preprocessor
\var{command}. The module "Ast_mapper", described in
chapter~\ref{Ast-underscoremapper}, implements the external interface
of a preprocessor.
\item["-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 "-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.
\item["-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.
\item["-runtime-variant" \var{suffix}]
Add the \var{suffix} string to the name of the runtime library used by
the program. Currently, only one such suffix is supported: "d", and
only if the OCaml compiler was configured with option
"-with-debug-runtime". This suffix gives the debug version of the
runtime, which is useful for debugging pointer problems in low-level
code such as C stubs.
\item["-safe-string"]
Enforce the separation between types "string" and "bytes",
thereby making strings read-only. This will become the default in
a future version of OCaml.
\item["-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.
\item["-strict-sequence"]
Force the left-hand part of each sequence to have type unit.
\item["-strict-formats"]
Reject invalid formats that were accepted in legacy format
implementations. You should use this flag to detect and fix such
invalid formats, as they will be rejected by future OCaml versions.
\item["-thread"]
Compile or link multithreaded programs, in combination with the
system "threads" library described in chapter~\ref{c:threads}.
\item["-unsafe"]
Turn bound checking off for array and string accesses (the "v.(i)" and
"s.[i]" constructs). Programs compiled with "-unsafe" are therefore
slightly faster, but unsafe: anything can happen if the program
accesses an array or string outside of its bounds.
\item["-unsafe-string"]
Identify the types "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.
\item["-use-runtime" \var{runtime-name}]
Generate a bytecode executable file that can be executed on the custom
runtime system \var{runtime-name}, built earlier with
"ocamlc -make-runtime" \var{runtime-name}.
See section~\ref{s:custom-runtime} for more information.
\item["-v"]
Print the version number of the compiler and the location of the
standard library directory, then exit.
\item["-verbose"]
Print all external commands before they are executed, in particular
invocations of the C compiler and linker in "-custom" mode. Useful to
debug C library problems.
\item["-vmthread"]
Compile or link multithreaded programs, in combination with the
VM-level "threads" library described in chapter~\ref{c:threads}.
\item["-version" or "-vnum"]
Print the version number of the compiler in short form (e.g. "3.11.0"),
then exit.
\item["-w" \var{warning-list}]
Enable, disable, or mark as fatal the warnings specified by the argument
\var{warning-list}.
Each warning can be {\em enabled} or {\em disabled}, and each warning
can be {\em fatal} or {\em 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 \var{warning-list} argument is a sequence of warning specifiers,
with no separators between them. A warning specifier is one of the
following:
\begin{options}
\item["+"\var{num}] Enable warning number \var{num}.
\item["-"\var{num}] Disable warning number \var{num}.
\item["@"\var{num}] Enable and mark as fatal warning number \var{num}.
\item["+"\var{num1}..\var{num2}] Enable warnings in the given range.
\item["-"\var{num1}..\var{num2}] Disable warnings in the given range.
\item["@"\var{num1}..\var{num2}] Enable and mark as fatal warnings in
the given range.
\item["+"\var{letter}] Enable the set of warnings corresponding to
\var{letter}. The letter may be uppercase or lowercase.
\item["-"\var{letter}] Disable the set of warnings corresponding to
\var{letter}. The letter may be uppercase or lowercase.
\item["@"\var{letter}] Enable and mark as fatal the set of warnings
corresponding to \var{letter}. The letter may be uppercase or
lowercase.
\item[\var{uppercase-letter}] Enable the set of warnings corresponding
to \var{uppercase-letter}.
\item[\var{lowercase-letter}] Disable the set of warnings corresponding
to \var{lowercase-letter}.
\end{options}
Warning numbers and letters which are out of the range of warnings
that are currently defined are ignored. The warnings are as follows.
\begin{options}
\input{warnings-help.tex}
\end{options}
The default setting is "-w +a-4-6-7-9-27-29-32..39-41..42-44-45".
It is displayed by "ocamlc -help".
Note that warnings 5 and 10 are not always triggered, depending on
the internals of the type checker.
\item["-warn-error" \var{warning-list}]
Mark as fatal the warnings specified in the argument \var{warning-list}.
The compiler will stop with an error when one of these warnings is
emitted. The \var{warning-list} has the same meaning as for
the "-w" option: a "+" sign (or an uppercase letter) marks the
corresponding warnings as fatal, a "-"
sign (or a lowercase letter) turns them back into non-fatal warnings, and a
"@" sign both enables and marks as fatal the corresponding warnings.
Note: it is not recommended to use warning sets (i.e. letters) as
arguments to "-warn-error"
in production code, because this can break your build when future versions
of OCaml add some new warnings.
The default setting is "-warn-error -a" (all warnings are non-fatal).
\item["-warn-help"]
Show the description of all available warning numbers.
\item["-where"]
Print the location of the standard library, then exit.
\item["-" \var{file}]
Process \var{file} as a file name, even if it starts with a dash ("-")
character.
\item["-help" or "--help"]
Display a short usage summary and exit.
%
\end{options}
\section{Modules and the file system}
This short section is intended to clarify the relationship between the
names of the modules corresponding to compilation units and the names
of the files that contain their compiled interface and compiled
implementation.
The compiler always derives the module name by taking the capitalized
base name of the source file (".ml" or ".mli" file). That is, it
strips the leading directory name, if any, as well as the ".ml" or
".mli" suffix; then, it set the first letter to uppercase, in order to
comply with the requirement that module names must be capitalized.
For instance, compiling the file "mylib/misc.ml" provides an
implementation for the module named "Misc". Other compilation units
may refer to components defined in "mylib/misc.ml" under the names
"Misc."\var{name}; they can also do "open Misc", then use unqualified
names \var{name}.
The ".cmi" and ".cmo" files produced by the compiler have the same
base name as the source file. Hence, the compiled files always have
their base name equal (modulo capitalization of the first letter) to
the name of the module they describe (for ".cmi" files) or implement
(for ".cmo" files).
When the compiler encounters a reference to a free module identifier
"Mod", it looks in the search path for a file named "Mod.cmi" or "mod.cmi"
and loads the compiled interface
contained in that file. As a consequence, renaming ".cmi" files is not
advised: the name of a ".cmi" file must always correspond to the name
of the compilation unit it implements. It is admissible to move them
to another directory, if their base name is preserved, and the correct
"-I" options are given to the compiler. The compiler will flag an
error if it loads a ".cmi" file that has been renamed.
Compiled bytecode files (".cmo" files), on the other hand, can be
freely renamed once created. That's because the linker never attempts
to find by itself the ".cmo" file that implements a module with a
given name: it relies instead on the user providing the list of ".cmo"
files by hand.
\section{Common errors} \label{s:comp-errors}
This section describes and explains the most frequently encountered
error messages.
\begin{options}
\item[Cannot find file \var{filename}]
The named file could not be found in the current directory, nor in the
directories of the search path. The \var{filename} is either a
compiled interface file (".cmi" file), or a compiled bytecode file
(".cmo" file). If \var{filename} has the format \var{mod}".cmi", this
means you are trying to compile a file that references identifiers
from module \var{mod}, but you have not yet compiled an interface for
module \var{mod}. Fix: compile \var{mod}".mli" or \var{mod}".ml"
first, to create the compiled interface \var{mod}".cmi".
If \var{filename} has the format \var{mod}".cmo", this
means you are trying to link a bytecode object file that does not
exist yet. Fix: compile \var{mod}".ml" first.
If your program spans several directories, this error can also appear
because you haven't specified the directories to look into. Fix: add
the correct "-I" options to the command line.
\item[Corrupted compiled interface \var{filename}]
The compiler produces this error when it tries to read a compiled
interface file (".cmi" file) that has the wrong structure. This means
something went wrong when this ".cmi" file was written: the disk was
full, the compiler was interrupted in the middle of the file creation,
and so on. This error can also appear if a ".cmi" file is modified after
its creation by the compiler. Fix: remove the corrupted ".cmi" file,
and rebuild it.
\item[This expression has type \nth{t}{1}, but is used with type \nth{t}{2}]
This is by far the most common type error in programs. Type \nth{t}{1} is
the type inferred for the expression (the part of the program that is
displayed in the error message), by looking at the expression itself.
Type \nth{t}{2} is the type expected by the context of the expression; it
is deduced by looking at how the value of this expression is used in
the rest of the program. If the two types \nth{t}{1} and \nth{t}{2} are not
compatible, then the error above is produced.
In some cases, it is hard to understand why the two types \nth{t}{1} and
\nth{t}{2} are incompatible. For instance, the compiler can report that
``expression of type "foo" cannot be used with type "foo"'', and it
really seems that the two types "foo" are compatible. This is not
always true. Two type constructors can have the same name, but
actually represent different types. This can happen if a type
constructor is redefined. Example:
\begin{verbatim}
type foo = A | B
let f = function A -> 0 | B -> 1
type foo = C | D
f C
\end{verbatim}
This result in the error message ``expression "C" of type "foo" cannot
be used with type "foo"''.
\item[The type of this expression, \var{t}, contains type variables
that cannot be generalized]
Type variables ("'a", "'b", \ldots) in a type \var{t} can be in either
of two states: generalized (which means that the type \var{t} is valid
for all possible instantiations of the variables) and not generalized
(which means that the type \var{t} is valid only for one instantiation
of the variables). In a "let" binding "let "\var{name}" = "\var{expr},
the type-checker normally generalizes as many type variables as
possible in the type of \var{expr}. However, this leads to unsoundness
(a well-typed program can crash) in conjunction with polymorphic
mutable data structures. To avoid this, generalization is performed at
"let" bindings only if the bound expression \var{expr} belongs to the
class of ``syntactic values'', which includes constants, identifiers,
functions, tuples of syntactic values, etc. In all other cases (for
instance, \var{expr} is a function application), a polymorphic mutable
could have been created and generalization is therefore turned off for
all variables occurring in contravariant or non-variant branches of the
type. For instance, if the type of a non-value is "'a list" the
variable is generalizable ("list" is a covariant type constructor),
but not in "'a list -> 'a list" (the left branch of "->" is
contravariant) or "'a ref" ("ref" is non-variant).
Non-generalized type variables in a type cause no difficulties inside
a given structure or compilation unit (the contents of a ".ml" file,
or an interactive session), but they cannot be allowed inside
signatures nor in compiled interfaces (".cmi" file), because they
could be used inconsistently later. Therefore, the compiler
flags an error when a structure or compilation unit defines a value
\var{name} whose type contains non-generalized type variables. There
are two ways to fix this error:
\begin{itemize}
\item Add a type constraint or a ".mli" file to give a monomorphic
type (without type variables) to \var{name}. For instance, instead of
writing
\begin{verbatim}
let sort_int_list = Sort.list (<)
(* inferred type 'a list -> 'a list, with 'a not generalized *)
\end{verbatim}
write
\begin{verbatim}
let sort_int_list = (Sort.list (<) : int list -> int list);;
\end{verbatim}
\item If you really need \var{name} to have a polymorphic type, turn
its defining expression into a function by adding an extra parameter.
For instance, instead of writing
\begin{verbatim}
let map_length = List.map Array.length
(* inferred type 'a array list -> int list, with 'a not generalized *)
\end{verbatim}
write
\begin{verbatim}
let map_length lv = List.map Array.length lv
\end{verbatim}
\end{itemize}
\item[Reference to undefined global \var{mod}]
This error appears when trying to link an incomplete or incorrectly
ordered set of files. Either you have forgotten to provide an
implementation for the compilation unit named \var{mod} on the command line
(typically, the file named \var{mod}".cmo", or a library containing
that file). Fix: add the missing ".ml" or ".cmo" file to the command
line. Or, you have provided an implementation for the module named
\var{mod}, but it comes too late on the command line: the
implementation of \var{mod} must come before all bytecode object files
that reference \var{mod}. Fix: change the order of ".ml" and ".cmo"
files on the command line.
Of course, you will always encounter this error if you have mutually
recursive functions across modules. That is, function "Mod1.f" calls
function "Mod2.g", and function "Mod2.g" calls function "Mod1.f".
In this case, no matter what permutations you perform on the command
line, the program will be rejected at link-time. Fixes:
\begin{itemize}
\item Put "f" and "g" in the same module.
\item Parameterize one function by the other.
That is, instead of having
\begin{verbatim}
mod1.ml: let f x = ... Mod2.g ...
mod2.ml: let g y = ... Mod1.f ...
\end{verbatim}
define
\begin{verbatim}
mod1.ml: let f g x = ... g ...
mod2.ml: let rec g y = ... Mod1.f g ...
\end{verbatim}
and link "mod1.cmo" before "mod2.cmo".
\item Use a reference to hold one of the two functions, as in :
\begin{verbatim}
mod1.ml: let forward_g =
ref((fun x -> failwith "forward_g") : <type>)
let f x = ... !forward_g ...
mod2.ml: let g y = ... Mod1.f ...
let _ = Mod1.forward_g := g
\end{verbatim}
\end{itemize}
\item[The external function \var{f} is not available]
This error appears when trying to link code that calls external
functions written in C. As explained in
chapter~\ref{c:intf-c}, such code must be linked with C libraries that
implement the required \var{f} C function. If the C libraries in
question are not shared libraries (DLLs), the code must be linked in
``custom runtime'' mode. Fix: add the required C libraries to the
command line, and possibly the "-custom" option.
\end{options}

View File

@ -0,0 +1,667 @@
\chapter{The debugger (ocamldebug)} \label{c:debugger}
\pdfchapter{The debugger (ocamldebug)}
%HEVEA\cutname{debugger.html}
This chapter describes the OCaml source-level replay debugger
"ocamldebug".
\begin{unix} The debugger is available on Unix systems that provide
BSD sockets.
\end{unix}
\begin{windows} The debugger is available under the Cygwin port of
OCaml, but not under the native Win32 ports.
\end{windows}
\section{Compiling for debugging}
Before the debugger can be used, the program must be compiled and
linked with the "-g" option: all ".cmo" and ".cma" files that are part
of the program should have been created with "ocamlc -g", and they
must be linked together with "ocamlc -g".
Compiling with "-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 "-g".
\section{Invocation}
\subsection{Starting the debugger}
The OCaml debugger is invoked by running the program
"ocamldebug" with the name of the bytecode executable file as first
argument:
\begin{alltt}
ocamldebug \optvar{options} \var{program} \optvar{arguments}
\end{alltt}
The arguments following \var{program} are optional, and are passed as
command-line arguments to the program being debugged. (See also the
"set arguments" command.)
The following command-line options are recognized:
\begin{options}
\item["-c " \var{count}]
Set the maximum number of simultaneously live checkpoints to \var{count}.
\item["-cd " \var{dir}]
Run the debugger program from the working directory \var{dir},
instead of the current directory. (See also the "cd" command.)
\item["-emacs"]
Tell the debugger it is executed under Emacs. (See
section~\ref{s:inf-debugger} for information on how to run the
debugger under Emacs.)
\item["-I "\var{directory}]
Add \var{directory} to the list of directories searched for source
files and compiled files. (See also the "directory" command.)
\item["-s "\var{socket}]
Use \var{socket} for communicating with the debugged program. See the
description of the command "set socket" (section~\ref{s:communication})
for the format of \var{socket}.
\item["-version"]
Print version string and exit.
\item["-vnum"]
Print short version number and exit.
\item["-help" or "--help"]
Display a short usage summary and exit.
%
\end{options}
\subsection{Exiting the debugger}
The command "quit" exits the debugger. You can also exit the debugger
by typing an end-of-file character (usually "ctrl-D").
Typing an interrupt character (usually "ctrl-C") will not exit the
debugger, but will terminate the action of any debugger command that is in
progress and return to the debugger command level.
\section{Commands} \label{s:debugger-commands}
A debugger command is a single line of input. It starts with a command
name, which is followed by arguments depending on this name. Examples:
\begin{verbatim}
run
goto 1000
set arguments arg1 arg2
\end{verbatim}
A command name can be truncated as long as there is no ambiguity. For
instance, "go 1000" is understood as "goto 1000", since there are no
other commands whose name starts with "go". For the most frequently
used commands, ambiguous abbreviations are allowed. For instance, "r"
stands for "run" even though there are others commands starting with
"r". You can test the validity of an abbreviation using the "help" command.
If the previous command has been successful, a blank line (typing just
"RET") will repeat it.
\subsection{Getting help}
The OCaml debugger has a simple on-line help system, which gives
a brief description of each command and variable.
\begin{options}
\item["help"]
Print the list of commands.
\item["help "\var{command}]
Give help about the command \var{command}.
\item["help set "\var{variable}, "help show "\var{variable}]
Give help about the variable \var{variable}. The list of all debugger
variables can be obtained with "help set".
\item["help info "\var{topic}]
Give help about \var{topic}. Use "help info" to get a list of known topics.
\end{options}
\subsection{Accessing the debugger state}
\begin{options}
\item["set "\var{variable} \var{value}]
Set the debugger variable \var{variable} to the value \var{value}.
\item["show "\var{variable}]
Print the value of the debugger variable \var{variable}.
\item["info "\var{subject}]
Give information about the given subject.
For instance, "info breakpoints" will print the list of all breakpoints.
\end{options}
\section{Executing a program}
\subsection{Events}
Events are ``interesting'' locations in the source code, corresponding
to the beginning or end of evaluation of ``interesting''
sub-expressions. Events are the unit of single-stepping (stepping goes
to the next or previous event encountered in the program execution).
Also, breakpoints can only be set at events. Thus, events play the
role of line numbers in debuggers for conventional languages.
During program execution, a counter is incremented at each event
encountered. The value of this counter is referred as the {\em current
time}. Thanks to reverse execution, it is possible to jump back and
forth to any time of the execution.
Here is where the debugger events (written \event) are located in
the source code:
\begin{itemize}
\item Following a function application:
\begin{alltt}
(f arg)\event
\end{alltt}
\item On entrance to a function:
\begin{alltt}
fun x y z -> \event ...
\end{alltt}
\item On each case of a pattern-matching definition (function,
"match"\ldots"with" construct, "try"\ldots"with" construct):
\begin{alltt}
function pat1 -> \event expr1
| ...
| patN -> \event exprN
\end{alltt}
\item Between subexpressions of a sequence:
\begin{alltt}
expr1; \event expr2; \event ...; \event exprN
\end{alltt}
\item In the two branches of a conditional expression:
\begin{alltt}
if cond then \event expr1 else \event expr2
\end{alltt}
\item At the beginning of each iteration of a loop:
\begin{alltt}
while cond do \event body done
for i = a to b do \event body done
\end{alltt}
\end{itemize}
Exceptions: A function application followed by a function return is replaced
by the compiler by a jump (tail-call optimization). In this case, no
event is put after the function application.
% Also, no event is put after a function application when the function
% is external (written in C).
\subsection{Starting the debugged program}
The debugger starts executing the debugged program only when needed.
This allows setting breakpoints or assigning debugger variables before
execution starts. There are several ways to start execution:
\begin{options}
\item["run"] Run the program until a breakpoint is hit, or the program
terminates.
\item["goto 0"] Load the program and stop on the first event.
\item["goto "\var{time}] Load the program and execute it until the
given time. Useful when you already know approximately at what time
the problem appears. Also useful to set breakpoints on function values
that have not been computed at time 0 (see section~\ref{s:breakpoints}).
\end{options}
The execution of a program is affected by certain information it
receives when the debugger starts it, such as the command-line
arguments to the program and its working directory. The debugger
provides commands to specify this information ("set arguments" and "cd").
These commands must be used before program execution starts. If you try
to change the arguments or the working directory after starting your
program, the debugger will kill the program (after asking for confirmation).
\subsection{Running the program}
The following commands execute the program forward or backward,
starting at the current time. The execution will stop either when
specified by the command or when a breakpoint is encountered.
\begin{options}
\item["run"] Execute the program forward from current time. Stops at
next breakpoint or when the program terminates.
\item["reverse"] Execute the program backward from current time.
Mostly useful to go to the last breakpoint encountered before the
current time.
\item["step "\optvar{count}] Run the program and stop at the next
event. With an argument, do it \var{count} times. If \var{count} is 0,
run until the program terminates or a breakpoint is hit.
\item["backstep "\optvar{count}] Run the program backward and stop at
the previous event. With an argument, do it \var{count} times.
\item["next "\optvar{count}] Run the program and stop at the next
event, skipping over function calls. With an argument, do it
\var{count} times.
\item["previous "\optvar{count}] Run the program backward and stop at
the previous event, skipping over function calls. With an argument, do
it \var{count} times.
\item["finish"] Run the program until the current function returns.
\item["start"] Run the program backward and stop at the first event
before the current function invocation.
\end{options}
\subsection{Time travel}
You can jump directly to a given time, without stopping on
breakpoints, using the "goto" command.
As you move through the program, the debugger maintains an history of
the successive times you stop at. The "last" command can be used to
revisit these times: each "last" command moves one step back through
the history. That is useful mainly to undo commands such as "step"
and "next".
\begin{options}
\item["goto "\var{time}]
Jump to the given time.
\item["last "\optvar{count}]
Go back to the latest time recorded in the execution history. With an
argument, do it \var{count} times.
\item["set history "\var{size}]
Set the size of the execution history.
\end{options}
\subsection{Killing the program}
\begin{options}
\item["kill"] Kill the program being executed. This command is mainly
useful if you wish to recompile the program without leaving the debugger.
\end{options}
\section{Breakpoints} \label{s:breakpoints}
A breakpoint causes the program to stop whenever a certain point in
the program is reached. It can be set in several ways using the
"break" command. Breakpoints are assigned numbers when set, for
further reference. The most comfortable way to set breakpoints is
through the Emacs interface (see section~\ref{s:inf-debugger}).
\begin{options}
\item["break"]
Set a breakpoint at the current position in the program execution. The
current position must be on an event (i.e., neither at the beginning,
nor at the end of the program).
\item["break "\var{function}]
Set a breakpoint at the beginning of \var{function}. This works only
when the functional value of the identifier \var{function} has been
computed and assigned to the identifier. Hence this command cannot be
used at the very beginning of the program execution, when all
identifiers are still undefined; use "goto" \var{time} to advance
execution until the functional value is available.
\item["break \@" \optvar{module} \var{line}]
Set a breakpoint in module \var{module} (or in the current module if
\var{module} is not given), at the first event of line \var{line}.
\item["break \@" \optvar{module} \var{line} \var{column}]
Set a breakpoint in module \var{module} (or in the current module if
\var{module} is not given), at the event closest to line \var{line},
column \var{column}.
\item["break \@" \optvar{module} "#" \var{character}]
Set a breakpoint in module \var{module} at the event closest to
character number \var{character}.
\item["break "\var{address}]
Set a breakpoint at the code address \var{address}.
\item["delete "\optvar{breakpoint-numbers}]
Delete the specified breakpoints. Without argument, all breakpoints
are deleted (after asking for confirmation).
\item["info breakpoints"] Print the list of all breakpoints.
\end{options}
\section{The call stack}
Each time the program performs a function application, it saves the
location of the application (the return address) in a block of data
called a stack frame. The frame also contains the local variables of
the caller function. All the frames are allocated in a region of
memory called the call stack. The command "backtrace" (or "bt")
displays parts of the call stack.
At any time, one of the stack frames is ``selected'' by the debugger; several
debugger commands refer implicitly to the selected frame. In particular,
whenever you ask the debugger for the value of a local variable, the
value is found in the selected frame. The commands "frame", "up" and "down"
select whichever frame you are interested in.
When the program stops, the debugger automatically selects the
currently executing frame and describes it briefly as the "frame"
command does.
\begin{options}
\item["frame"]
Describe the currently selected stack frame.
\item["frame" \var{frame-number}]
Select a stack frame by number and describe it. The frame currently
executing when the program stopped has number 0; its caller has number
1; and so on up the call stack.
\item["backtrace "\optvar{count}, "bt "\optvar{count}]
Print the call stack. This is useful to see which sequence of function
calls led to the currently executing frame. With a positive argument,
print only the innermost \var{count} frames.
With a negative argument, print only the outermost -\var{count} frames.
\item["up" \optvar{count}]
Select and display the stack frame just ``above'' the selected frame,
that is, the frame that called the selected frame. An argument says how
many frames to go up.
\item["down "\optvar{count}]
Select and display the stack frame just ``below'' the selected frame,
that is, the frame that was called by the selected frame. An argument
says how many frames to go down.
\end{options}
\section{Examining variable values}
The debugger can print the current value of simple expressions. The
expressions can involve program variables: all the identifiers that
are in scope at the selected program point can be accessed.
Expressions that can be printed are a subset of OCaml
expressions, as described by the following grammar:
\begin{syntax}
simple-expr:
lowercase-ident
| { capitalized-ident '.' } lowercase-ident
| '*'
| '$' integer
| simple-expr '.' lowercase-ident
| simple-expr '.(' integer ')'
| simple-expr '.[' integer ']'
| '!' simple-expr
| '(' simple-expr ')'
\end{syntax}
The first two cases refer to a value identifier, either unqualified or
qualified by the path to the structure that define it.
"*" refers to the result just computed (typically, the value of a
function application), and is valid only if the selected event is an
``after'' event (typically, a function application).
@'$' integer@ refer to a previously printed value. The remaining four
forms select part of an expression: respectively, a record field, an
array element, a string element, and the current contents of a
reference.
\begin{options}
\item["print "\var{variables}]
Print the values of the given variables. "print" can be abbreviated as
"p".
\item["display "\var{variables}]
Same as "print", but limit the depth of printing to 1. Useful to
browse large data structures without printing them in full.
"display" can be abbreviated as "d".
\end{options}
When printing a complex expression, a name of the form "$"\var{integer}
is automatically assigned to its value. Such names are also assigned
to parts of the value that cannot be printed because the maximal
printing depth is exceeded. Named values can be printed later on
with the commands "p $"\var{integer} or "d $"\var{integer}.
Named values are valid only as long as the program is stopped. They
are forgotten as soon as the program resumes execution.
\begin{options}
\item["set print_depth" \var{d}]
Limit the printing of values to a maximal depth of \var{d}.
\item["set print_length" \var{l}]
Limit the printing of values to at most \var{l} nodes printed.
\end{options}
\section{Controlling the debugger}
\subsection{Setting the program name and arguments}
\begin{options}
\item["set program" \var{file}]
Set the program name to \var{file}.
\item["set arguments" \var{arguments}]
Give \var{arguments} as command-line arguments for the program.
\end{options}
A shell is used to pass the arguments to the debugged program. You can
therefore use wildcards, shell variables, and file redirections inside
the arguments. To debug programs that read from standard input, it is
recommended to redirect their input from a file (using
"set arguments < input-file"), otherwise input to the program and
input to the debugger are not properly separated, and inputs are not
properly replayed when running the program backwards.
\subsection{How programs are loaded}
The "loadingmode" variable controls how the program is executed.
\begin{options}
\item["set loadingmode direct"]
The program is run directly by the debugger. This is the default mode.
\item["set loadingmode runtime"]
The debugger execute the OCaml runtime "ocamlrun" on the program.
Rarely useful; moreover it prevents the debugging of programs compiled
in ``custom runtime'' mode.
\item["set loadingmode manual"]
The user starts manually the program, when asked by the debugger.
Allows remote debugging (see section~\ref{s:communication}).
\end{options}
\subsection{Search path for files}
The debugger searches for source files and compiled interface files in
a list of directories, the search path. The search path initially
contains the current directory "." and the standard library directory.
The "directory" command adds directories to the path.
Whenever the search path is modified, the debugger will clear any
information it may have cached about the files.
\begin{options}
\item["directory" \var{directorynames}]
Add the given directories to the search path. These directories are
added at the front, and will therefore be searched first.
\item["directory" \var{directorynames} "for" \var{modulename}]
Same as "directory" \var{directorynames}, but the given directories will be
searched only when looking for the source file of a module that has
been packed into \var{modulename}.
\item["directory"]
Reset the search path. This requires confirmation.
\end{options}
\subsection{Working directory}
Each time a program is started in the debugger, it inherits its working
directory from the current working directory of the debugger. This
working directory is initially whatever it inherited from its parent
process (typically the shell), but you can specify a new working
directory in the debugger with the "cd" command or the "-cd"
command-line option.
\begin{options}
\item["cd" \var{directory}]
Set the working directory for "ocamldebug" to \var{directory}.
\item["pwd"]
Print the working directory for "ocamldebug".
\end{options}
\subsection{Turning reverse execution on and off}
In some cases, you may want to turn reverse execution off. This speeds
up the program execution, and is also sometimes useful for interactive
programs.
Normally, the debugger takes checkpoints of the program state from
time to time. That is, it makes a copy of the current state of the
program (using the Unix system call "fork"). If the variable
\var{checkpoints} is set to "off", the debugger will not take any
checkpoints.
\begin{options}
\item["set checkpoints" \var{on/off}]
Select whether the debugger makes checkpoints or not.
\end{options}
\subsection{Communication between the debugger and the program}
\label{s:communication}
The debugger communicate with the program being debugged through a
Unix socket. You may need to change the socket name, for example if
you need to run the debugger on a machine and your program on another.
\begin{options}
\item["set socket" \var{socket}]
Use \var{socket} for communication with the program. \var{socket} can be
either a file name, or an Internet port specification
\var{host}:\var{port}, where \var{host} is a host name or an Internet
address in dot notation, and \var{port} is a port number on the host.
\end{options}
On the debugged program side, the socket name is passed through the
"CAML_DEBUG_SOCKET" environment variable.
\subsection{Fine-tuning the debugger} \label{s:fine-tuning}
Several variables enables to fine-tune the debugger. Reasonable
defaults are provided, and you should normally not have to change them.
\begin{options}
\item["set processcount" \var{count}]
Set the maximum number of checkpoints to \var{count}. More checkpoints
facilitate going far back in time, but use more memory and create more
Unix processes.
\end{options}
As checkpointing is quite expensive, it must not be done too often. On
the other hand, backward execution is faster when checkpoints are
taken more often. In particular, backward single-stepping is more
responsive when many checkpoints have been taken just before the
current time. To fine-tune the checkpointing strategy, the debugger
does not take checkpoints at the same frequency for long displacements
(e.g. "run") and small ones (e.g. "step"). The two variables "bigstep"
and "smallstep" contain the number of events between two checkpoints
in each case.
\begin{options}
\item["set bigstep" \var{count}]
Set the number of events between two checkpoints for long displacements.
\item["set smallstep" \var{count}]
Set the number of events between two checkpoints for small
displacements.
\end{options}
The following commands display information on checkpoints and events:
\begin{options}
\item["info checkpoints"]
Print a list of checkpoints.
\item["info events" \optvar{module}]
Print the list of events in the given module (the current module, by default).
\end{options}
\subsection{User-defined printers}
Just as in the toplevel system (section~\ref{s:toplevel-directives}),
the user can register functions for printing values of certain types.
For technical reasons, the debugger cannot call printing functions
that reside in the program being debugged. The code for the printing
functions must therefore be loaded explicitly in the debugger.
\begin{options}
\item["load_printer \""\var{file-name}"\""]
Load in the debugger the indicated ".cmo" or ".cma" object file. The
file is loaded in an environment consisting only of the OCaml
standard library plus the definitions provided by object files
previously loaded using "load_printer". If this file depends on other
object files not yet loaded, the debugger automatically loads them if
it is able to find them in the search path. The loaded file does not
have direct access to the modules of the program being debugged.
\item["install_printer "\var{printer-name}]
Register the function named \var{printer-name} (a
value path) as a printer for objects whose types match the argument
type of the function. That is, the debugger will call
\var{printer-name} when it has such an object to print.
The printing function \var{printer-name} must use the "Format" library
module to produce its output, otherwise its output will not be
correctly located in the values printed by the toplevel loop.
The value path \var{printer-name} must refer to one of the functions
defined by the object files loaded using "load_printer". It cannot
reference the functions of the program being debugged.
\item["remove_printer "\var{printer-name}]
Remove the named function from the table of value printers.
\end{options}
\section{Miscellaneous commands}
\begin{options}
\item["list" \optvar{module} \optvar{beginning} \optvar{end}]
List the source of module \var{module}, from line number
\var{beginning} to line number \var{end}. By default, 20 lines of the
current module are displayed, starting 10 lines before the current
position.
\item["source" \var{filename}]
Read debugger commands from the script \var{filename}.
\end{options}
\section{Running the debugger under Emacs} \label{s:inf-debugger}
The most user-friendly way to use the debugger is to run it under Emacs.
See the file "emacs/README" in the distribution for information on how
to load the Emacs Lisp files for OCaml support.
The OCaml debugger is started under Emacs by the command "M-x
camldebug", with argument the name of the executable file
\var{progname} to debug. Communication with the debugger takes place
in an Emacs buffer named "*camldebug-"\var{progname}"*". The editing
and history facilities of Shell mode are available for interacting
with the debugger.
In addition, Emacs displays the source files containing the current
event (the current position in the program execution) and highlights
the location of the event. This display is updated synchronously with
the debugger action.
The following bindings for the most common debugger commands are
available in the "*camldebug-"\var{progname}"*" buffer:
\begin{options}
\item["C-c C-s"] (command "step"): execute the program one step forward.
\item["C-c C-k"] (command "backstep"): execute the program one step backward.
\item["C-c C-n"] (command "next"): execute the program one step
forward, skipping over function calls.
\item[Middle mouse button] (command "display"): display named value.
"$"\var{n} under mouse cursor (support incremental browsing of large
data structures).
\item["C-c C-p"] (command "print"): print value of identifier at point.
\item["C-c C-d"] (command "display"): display value of identifier at point.
\item["C-c C-r"] (command "run"): execute the program forward to next
breakpoint.
\item["C-c C-v"] (command "reverse"): execute the program backward to
latest breakpoint.
\item["C-c C-l"] (command "last"): go back one step in the command history.
\item["C-c C-t"] (command "backtrace"): display backtrace of function calls.
\item["C-c C-f"] (command "finish"): run forward till the current
function returns.
\item["C-c <"] (command "up"): select the stack frame below the
current frame.
\item["C-c >"] (command "down"): select the stack frame above the
current frame.
\end{options}
In all buffers in OCaml editing mode, the following debugger commands
are also available:
\begin{options}
\item["C-x C-a C-b"] (command "break"): set a breakpoint at event closest
to point
\item["C-x C-a C-p"] (command "print"): print value of identifier at point
\item["C-x C-a C-d"] (command "display"): display value of identifier at point
\end{options}

View File

@ -0,0 +1,208 @@
\chapter{Dependency generator (ocamldep)} \label{c:camldep}
\pdfchapter{Dependency generator (ocamldep)}
%HEVEA\cutname{depend.html}
The "ocamldep" 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 "make"
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:
\begin{alltt}
ocamldep \var{options} *.mli *.ml > .depend
\end{alltt}
where "*.mli *.ml" expands to all source files in the current
directory and ".depend" is the file that should contain the
dependencies. (See below for a typical "Makefile".)
Dependencies are generated both for compiling with the bytecode
compiler "ocamlc" and with the native-code compiler "ocamlopt".
The "ocamlbuild" compilation manager (see chapter~\ref{c:ocamlbuild})
provide a higher-level, more automated alternative to the combination
of "make" and "ocamldep".
\section{Options}
The following command-line options are recognized by "ocamldep".
\begin{options}
\item["-absname"]
Show absolute filenames in error messages.
\item["-all"]
Generate dependencies on all required files, rather than assuming
implicit dependencies.
\item["-allow-approx"]
Allow falling back on a lexer-based approximation when parsing fails.
\item["-as-map"]
For the following files, do not include delayed dependencies for
module aliases.
This option assumes that they are compiled using options
"-no-alias-deps -w -49", and that those files or their interface are
passed with the "-map" option when computing dependencies for other
files. Note also that for dependencies to be correct in the
implementation of a map file, its interface should not coerce any of
the aliases it contains.
\item["-debug-map"]
Dump the delayed dependency map for each map file.
\item["-I" \var{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 "-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 "ocamldep" the same "-I" options
that are passed to the compiler.
\item["-impl" \var{file}]
Process \var{file} as a ".ml" file.
\item["-intf" \var{file}]
Process \var{file} as a ".mli" file.
\item["-map" \var{file}]
Read an propagate the delayed dependencies for module aliases in
\var{file}, so that the following files will depend on the
exported aliased modules if they use them. See the example below.
\item["-ml-synonym" \var{.ext}]
Consider the given extension (with leading dot) to be a synonym for .ml.
\item["-mli-synonym" \var{.ext}]
Consider the given extension (with leading dot) to be a synonym for .mli.
\item["-modules"]
Output raw dependencies of the form
\begin{verbatim}
filename: Module1 Module2 ... ModuleN
\end{verbatim}
where "Module1", \ldots, "ModuleN" are the names of the compilation
units referenced within the file "filename", but these names are not
resolved to source file names. Such raw dependencies cannot be used
by "make", but can be post-processed by other tools such as "Omake".
\item["-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), "ocamldep" 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 "-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.)
\item["-one-line"]
Output one line per file, regardless of the length.
\item["-open" \var{module}]
Assume that module \var{module} is opened before parsing each of the
following files.
\item["-pp" \var{command}]
Cause "ocamldep" to call the given \var{command} as a preprocessor
for each source file.
\item["-ppx" \var{command}]
Pipe abstract syntax trees through preprocessor \var{command}.
\item["-slash"]
Under Windows, use a forward slash (/) as the path separator instead
of the usual backward slash ($\backslash$). Under Unix, this option does
nothing.
\item["-sort"]
Sort files according to their dependencies.
\item["-version"]
Print version string and exit.
\item["-vnum"]
Print short version number and exit.
\item["-help" or "--help"]
Display a short usage summary and exit.
%
\end{options}
\section{A typical Makefile}
Here is a template "Makefile" for a OCaml program.
\begin{verbatim}
OCAMLC=ocamlc
OCAMLOPT=ocamlopt
OCAMLDEP=ocamldep
INCLUDES= # all relevant -I options here
OCAMLFLAGS=$(INCLUDES) # add other options for ocamlc here
OCAMLOPTFLAGS=$(INCLUDES) # add other options for ocamlopt here
# prog1 should be compiled to bytecode, and is composed of three
# units: mod1, mod2 and mod3.
# The list of object files for prog1
PROG1_OBJS=mod1.cmo mod2.cmo mod3.cmo
prog1: $(PROG1_OBJS)
$(OCAMLC) -o prog1 $(OCAMLFLAGS) $(PROG1_OBJS)
# prog2 should be compiled to native-code, and is composed of two
# units: mod4 and mod5.
# The list of object files for prog2
PROG2_OBJS=mod4.cmx mod5.cmx
prog2: $(PROG2_OBJS)
$(OCAMLOPT) -o prog2 $(OCAMLFLAGS) $(PROG2_OBJS)
# Common rules
.SUFFIXES: .ml .mli .cmo .cmi .cmx
.ml.cmo:
$(OCAMLC) $(OCAMLFLAGS) -c $<
.mli.cmi:
$(OCAMLC) $(OCAMLFLAGS) -c $<
.ml.cmx:
$(OCAMLOPT) $(OCAMLOPTFLAGS) -c $<
# Clean up
clean:
rm -f prog1 prog2
rm -f *.cm[iox]
# Dependencies
depend:
$(OCAMLDEP) $(INCLUDES) *.mli *.ml > .depend
include .depend
\end{verbatim}
If you use module aliases to give shorter names to modules, you need
to change the above definitions. Assuming that your map file is called
"mylib.mli", here are minimal modifications.
\begin{verbatim}
OCAMLFLAGS=$(INCLUDES) -open Mylib
mylib.cmi: mylib.mli
$(OCAMLC) $(INCLUDES) -no-alias-deps -w -49 -c $<
depend:
$(OCAMLDEP) $(INCLUDES) -map mylib.mli $(PROG1_OBJS:.cmo=.ml) > .depend
\end{verbatim}
Note that in this case you should not compute dependencies for
"mylib.mli" together with the other files, hence the need to pass
explicitly the list of files to process.
If "mylib.mli" itself has dependencies, you should compute them using
"-as-map".

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,729 @@
\chapter{Lexer and parser generators (ocamllex, ocamlyacc)}
\label{c:ocamlyacc}
\pdfchapter{Lexer and parser generators (ocamllex, ocamlyacc)}
%HEVEA\cutname{lexyacc.html}
This chapter describes two program generators: "ocamllex", that
produces a lexical analyzer from a set of regular expressions with
associated semantic actions, and "ocamlyacc", that produces a parser
from a grammar with associated semantic actions.
These program generators are very close to the well-known "lex" and
"yacc" commands that can be found in most C programming environments.
This chapter assumes a working knowledge of "lex" and "yacc": while
it describes the input syntax for "ocamllex" and "ocamlyacc" and the
main differences with "lex" and "yacc", it does not explain the basics
of writing a lexer or parser description in "lex" and "yacc". Readers
unfamiliar with "lex" and "yacc" are referred to ``Compilers:
principles, techniques, and tools'' by Aho, Sethi and Ullman
(Addison-Wesley, 1986), or ``Lex $\&$ Yacc'', by Levine, Mason and
Brown (O'Reilly, 1992).
\section{Overview of \texttt{ocamllex}}
The "ocamllex" command produces a lexical analyzer from a set of regular
expressions with attached semantic actions, in the style of
"lex". Assuming the input file is \var{lexer}".mll", executing
\begin{alltt}
ocamllex \var{lexer}.mll
\end{alltt}
produces OCaml code for a lexical analyzer in file \var{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. (See the description of module
"Lexing" in chapter~\ref{c:stdlib}.)
When used in conjunction with a parser generated by "ocamlyacc", the
semantic actions compute a value belonging to the type "token" defined
by the generated parsing module. (See the description of "ocamlyacc"
below.)
\subsection{Options}
The following command-line options are recognized by "ocamllex".
\begin{options}
\item["-ml"]
Output code that does not use OCaml's built-in automata
interpreter. Instead, the automaton is encoded by OCaml functions.
This option mainly is useful for debugging "ocamllex", using it for
production lexers is not recommended.
\item["-o" \var{output-file}]
Specify the name of the output file produced by "ocamllex".
The default is the input file name with its extension replaced by ".ml".
\item["-q"]
Quiet mode. "ocamllex" normally outputs informational messages
to standard output. They are suppressed if option "-q" is used.
\item["-v" or "-version"]
Print version string and exit.
\item["-vnum"]
Print short version number and exit.
\item["-help" or "--help"]
Display a short usage summary and exit.
%
\end{options}
\section{Syntax of lexer definitions}
The format of lexer definitions is as follows:
\begin{alltt}
\{ \var{header} \}
let \var{ident} = \var{regexp} \ldots
[refill \{ \var{refill-handler} \}]
rule \var{entrypoint} [\nth{arg}{1}\ldots{} \nth{arg}{n}] =
parse \var{regexp} \{ \var{action} \}
| \ldots
| \var{regexp} \{ \var{action} \}
and \var{entrypoint} [\nth{arg}{1}\ldots{} \nth{arg}{n}] =
parse \ldots
and \ldots
\{ \var{trailer} \}
\end{alltt}
Comments are delimited by "(*" and "*)", as in OCaml.
The "parse" keyword, can be replaced by the "shortest" keyword, with
the semantic consequences explained below.
Refill handlers are a recent (optional) feature introduced in 4.02,
documented below in subsection~\ref{ss:refill-handlers}.
\subsection{Header and trailer}
The {\it header} and {\it trailer} sections are arbitrary OCaml
text enclosed in curly braces. Either or both can be omitted. If
present, the header text is copied as is at the beginning of the
output file and the trailer text at the end. Typically, the
header section contains the "open" directives required
by the actions, and possibly some auxiliary functions used in the
actions.
\subsection{Naming regular expressions}
Between the header and the entry points, one can give names to
frequently-occurring regular expressions. This is written
@"let" ident "=" regexp@.
In regular expressions that follow this declaration, the identifier
\var{ident} can be used as shorthand for \var{regexp}.
\subsection{Entry points}
The names of the entry points must be valid identifiers for OCaml
values (starting with a lowercase letter).
Similarily, the arguments \texttt{\var{arg$_1$}\ldots{}
\var{arg$_n$}} must be valid identifiers for OCaml.
Each entry point becomes an
OCaml function that takes $n+1$ arguments,
the extra implicit last argument being of type "Lexing.lexbuf".
Characters are read from the "Lexing.lexbuf" argument and matched
against the regular expressions provided in the rule, until a prefix
of the input matches one of the rule. The corresponding action is
then evaluated and returned as the result of the function.
If several regular expressions match a prefix of the input, the
``longest match'' rule applies: the regular expression that matches
the longest prefix of the input is selected. In case of tie, the
regular expression that occurs earlier in the rule is selected.
However, if lexer rules are introduced with the "shortest" keyword in
place of the "parse" keyword, then the ``shortest match'' rule applies:
the shortest prefix of the input is selected. In case of tie, the
regular expression that occurs earlier in the rule is still selected.
This feature is not intended for use in ordinary lexical analyzers, it
may facilitate the use of "ocamllex" as a simple text processing tool.
\subsection{Regular expressions}
The regular expressions are in the style of "lex", with a more
OCaml-like syntax.
\begin{syntax}
regexp:
\ldots
\end{syntax}
\begin{options}
\item[@"'" regular-char || escape-sequence "'"@]
A character constant, with the same syntax as OCaml character
constants. Match the denoted character.
\item["_"]
(underscore) Match any character.
\item[@"eof"@]
Match the end of the lexer input.\\
{\bf Note:} On some systems, with interactive input, an end-of-file
may be followed by more characters. However, "ocamllex" will not
correctly handle regular expressions that contain "eof" followed by
something else.
\item[@'"' { string-character } '"'@]
A string constant, with the same syntax as OCaml string
constants. Match the corresponding sequence of characters.
\item[@'[' character-set ']'@]
Match any single character belonging to the given
character set. Valid character sets are: single
character constants @"'" @c@ "'"@; ranges of characters
@"'" @c@_1 "'" "-" "'" @c@_2 "'"@ (all characters between $c_1$ and $c_2$,
inclusive); and the union of two or more character sets, denoted by
concatenation.
\item[@'[' '^' character-set ']'@]
Match any single character not belonging to the given character set.
\item[@regexp_1 '#' regexp_2@]
(difference of character sets)
Regular expressions @regexp_1@ and @regexp_2@ must be character sets
defined with @'['\ldots ']'@ (or a a single character expression or
underscore "_").
Match the difference of the two specified character sets.
\item[@regexp '*'@]
(repetition) Match the concatenation of zero or more
strings that match @regexp@.
\item[@regexp '+'@]
(strict repetition) Match the concatenation of one or more
strings that match @regexp@.
\item[@regexp '?'@]
(option) Match the empty string, or a string matching @regexp@.
\item[@regexp_1 '|' regexp_2@]
(alternative) Match any string that matches @regexp_1@ or @regexp_2@
\item[@regexp_1 regexp_2@]
(concatenation) Match the concatenation of two strings, the first
matching @regexp_1@, the second matching @regexp_2@.
\item[@'(' regexp ')'@]
Match the same strings as @regexp@.
\item[@ident@]
Reference the regular expression bound to @ident@ by an earlier
@"let" ident "=" regexp@ definition.
\item[@regexp 'as' ident@]
Bind the substring matched by @regexp@ to identifier @ident@.
\end{options}
Concerning the precedences of operators, "#" has the highest precedence,
followed by "*", "+" and "?",
then concatenation, then "|" (alternation), then "as".
\subsection{Actions}
The actions are arbitrary OCaml expressions. They are evaluated in
a context where the identifiers defined by using the "as" construct
are bound to subparts of the matched string.
Additionally, "lexbuf" is bound to the current lexer
buffer. Some typical uses for "lexbuf", in conjunction with the
operations on lexer buffers provided by the "Lexing" standard library
module, are listed below.
\begin{options}
\item["Lexing.lexeme lexbuf"]
Return the matched string.
\item["Lexing.lexeme_char lexbuf "$n$]
Return the $n\th$
character in the matched string. The first character corresponds to $n = 0$.
\item["Lexing.lexeme_start lexbuf"]
Return the absolute position in the input text of the beginning of the
matched string (i.e. the offset of the first character of the matched
string). The first character read from the input text has offset 0.
\item["Lexing.lexeme_end lexbuf"]
Return the absolute position in the input text of the end of the
matched string (i.e. the offset of the first character after the
matched string). The first character read from the input text has
offset 0.
\newcommand{\sub}[1]{$_{#1}$}%
\item[\var{entrypoint} {[\var{exp\sub{1}}\ldots{} \var{exp\sub{n}}]} "lexbuf"]
(Where \var{entrypoint} is the name of another entry point in the same
lexer definition.) Recursively call the lexer on the given entry point.
Notice that "lexbuf" is the last argument.
Useful for lexing nested comments, for example.
\end{options}
\subsection{Variables in regular expressions}
The "as" construct is similar to ``\emph{groups}'' as provided by
numerous regular expression packages.
The type of these variables can be "string", "char", "string option"
or "char option".
We first consider the case of linear patterns, that is the case when
all "as" bound variables are distinct.
In @regexp 'as' ident@, the type of @ident@ normally is "string" (or
"string option") except
when @regexp@ is a character constant, an underscore, a string
constant of length one, a character set specification, or an
alternation of those. Then, the type of @ident@ is "char" (or "char
option").
Option types are introduced when overall rule matching does not
imply matching of the bound sub-pattern. This is in particular the
case of @'(' regexp 'as' ident ')' '?'@ and of
@regexp_1 '|' '(' regexp_2 'as' ident ')'@.
There is no linearity restriction over "as" bound variables.
When a variable is bound more than once, the previous rules are to be
extended as follows:
\begin{itemize}
\item A variable is a "char" variable when all its occurrences bind
"char" occurrences in the previous sense.
\item A variable is an "option" variable when the overall expression
can be matched without binding this variable.
\end{itemize}
For instance, in
"('a' as x) | ( 'a' (_ as x) )" the variable "x" is of type
"char", whereas in
"(\"ab\" as x) | ( 'a' (_ as x) ? )" the variable "x" is of type
"string option".
In some cases, a successful match may not yield a unique set of bindings.
For instance the matching of \verb+aba+ by the regular expression
"(('a'|\"ab\") as x) ((\"ba\"|'a') as y)" may result in binding
either
\verb+x+ to \verb+"ab"+ and \verb+y+ to \verb+"a"+, or
\verb+x+ to \verb+"a"+ and \verb+y+ to \verb+"ba"+.
The automata produced "ocamllex" on such ambiguous regular
expressions will select one of the possible resulting sets of
bindings.
The selected set of bindings is purposely left unspecified.
\subsection{Refill handlers}
\label{ss:refill-handlers}
By default, when ocamllex reaches the end of its lexing buffer, it
will silently call the "refill_buff" function of "lexbuf" structure
and continue lexing. It is sometimes useful to be able to take control
of refilling action; typically, if you use a library for asynchronous
computation, you may want to wrap the refilling action in a delaying
function to avoid blocking synchronous operations.
Since OCaml 4.02, it is possible to specify a \var{refill-handler},
a function that will be called when refill happens. It is passed the
continuation of the lexing, on which it has total control. The OCaml
expression used as refill action should have a type that is an
instance of
\begin{verbatim}
(Lexing.lexbuf -> 'a) -> Lexing.lexbuf -> 'a
\end{verbatim}
where the first argument is the continuation which captures the
processing ocamllex would usually perform (refilling the buffer, then
calling the lexing function again), and the result type that
instantiates ['a] should unify with the result type of all lexing
rules.
As an example, consider the following lexer that is parametrized over
an arbitrary monad:
\begin{verbatim}
{
type token = EOL | INT of int | PLUS
module Make (M : sig
type 'a t
val return: 'a -> 'a t
val bind: 'a t -> ('a -> 'b t) -> 'b t
val fail : string -> 'a t
(* Set up lexbuf *)
val on_refill : Lexing.lexbuf -> unit t
end)
= struct
let refill_handler k lexbuf =
M.bind (M.on_refill lexbuf) (fun () -> k lexbuf)
}
refill {refill_handler}
rule token = parse
| [' ' '\t']
{ token lexbuf }
| '\n'
{ M.return EOL }
| ['0'-'9']+ as i
{ M.return (INT (int_of_string i)) }
| '+'
{ M.return PLUS }
| _
{ M.fail "unexpected character" }
{
end
}
\end{verbatim}
\subsection{Reserved identifiers}
All identifiers starting with "__ocaml_lex" are reserved for use by
"ocamllex"; do not use any such identifier in your programs.
\section{Overview of \texttt{ocamlyacc}}
The "ocamlyacc" command produces a parser from a context-free grammar
specification with attached semantic actions, in the style of "yacc".
Assuming the input file is \var{grammar}".mly", executing
\begin{alltt}
ocamlyacc \var{options} \var{grammar}.mly
\end{alltt}
produces OCaml code for a parser in the file \var{grammar}".ml",
and its interface in file \var{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
"ocamllex" 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
\var{grammar}".mli" produced by "ocamlyacc".
\section{Syntax of grammar definitions}
Grammar definitions have the following format:
\begin{alltt}
\%\{
\var{header}
\%\}
\var{declarations}
\%\%
\var{rules}
\%\%
\var{trailer}
\end{alltt}
Comments are enclosed between \verb|/*| and \verb|*/| (as in C) in the
``declarations'' and ``rules'' sections, and between \verb|(*| and
\verb|*)| (as in OCaml) in the ``header'' and ``trailer'' sections.
\subsection{Header and trailer}
The header and the trailer sections are OCaml code that is copied
as is into file \var{grammar}".ml". Both sections are optional. The header
goes at the beginning of the output file; it usually contains
"open" directives and auxiliary functions required by the semantic
actions of the rules. The trailer goes at the end of the output file.
\subsection{Declarations}
Declarations are given one per line. They all start with a \verb"%" sign.
\begin{options}
\item[@"%token" constr \ldots constr@]
Declare the given symbols @constr \ldots constr@
as tokens (terminal symbols). These symbols
are added as constant constructors for the "token" concrete type.
\item[@"%token" "<" typexpr ">" constr \ldots constr@]
Declare the given symbols @constr \ldots constr@ as tokens with an
attached attribute of the
given type. These symbols are added as constructors with arguments of
the given type for the "token" concrete type. The @typexpr@ part is
an arbitrary OCaml type expression, except that all type
constructor names must be fully qualified (e.g. "Modname.typename")
for all types except standard built-in types, even if the proper
\verb|open| directives (e.g. \verb|open Modname|) were given in the
header section. That's because the header is copied only to the ".ml"
output file, but not to the ".mli" output file, while the @typexpr@ part
of a \verb"%token" declaration is copied to both.
\item[@"%start" symbol \ldots symbol@]
Declare the given symbols as entry points for the grammar. For each
entry point, a parsing function with the same name is defined in the
output module. Non-terminals that are not declared as entry points
have no such parsing function. Start symbols must be given a type with
the \verb|%type| directive below.
\item[@"%type" "<" typexpr ">" symbol \ldots symbol@]
Specify the type of the semantic attributes for the given symbols.
This is mandatory for start symbols only. Other nonterminal symbols
need not be given types by hand: these types will be inferred when
running the output files through the OCaml compiler (unless the
\verb"-s" option is in effect). The @typexpr@ part is an arbitrary OCaml
type expression, except that all type constructor names must be
fully qualified, as explained above for "%token".
\item[@"%left" symbol \ldots symbol@]
\item[@"%right" symbol \ldots symbol@]
\item[@"%nonassoc" symbol \ldots symbol@]
Associate precedences and associativities to the given symbols. All
symbols on the same line are given the same precedence. They have
higher precedence than symbols declared before in a \verb"%left",
\verb"%right" or \verb"%nonassoc" line. They have lower precedence
than symbols declared after in a \verb"%left", \verb"%right" or
\verb"%nonassoc" line. The symbols are declared to associate to the
left (\verb"%left"), to the right (\verb"%right"), or to be
non-associative (\verb"%nonassoc"). The symbols are usually tokens.
They can also be dummy nonterminals, for use with the \verb"%prec"
directive inside the rules.
The precedence declarations are used in the following way to
resolve reduce/reduce and shift/reduce conflicts:
\begin{itemize}
\item Tokens and rules have precedences. By default, the precedence
of a rule is the precedence of its rightmost terminal. You
can override this default by using the @"%prec"@ directive in the rule.
\item A reduce/reduce conflict
is resolved in favor of the first rule (in the order given by the
source file), and "ocamlyacc" outputs a warning.
\item A shift/reduce conflict
is resolved by comparing the precedence of the rule to be
reduced with the precedence of the token to be shifted. If the
precedence of the rule is higher, then the rule will be reduced;
if the precedence of the token is higher, then the token will
be shifted.
\item A shift/reduce conflict between a rule and a token with the
same precedence will be resolved using the associativity: if the
token is left-associative, then the parser will reduce; if the
token is right-associative, then the parser will shift. If the
token is non-associative, then the parser will declare a syntax
error.
\item When a shift/reduce conflict cannot be resolved using the above
method, then "ocamlyacc" will output a warning and the parser will
always shift.
\end{itemize}
\end{options}
\subsection{Rules}
The syntax for rules is as usual:
\begin{alltt}
\var{nonterminal} :
\var{symbol} \ldots \var{symbol} \{ \var{semantic-action} \}
| \ldots
| \var{symbol} \ldots \var{symbol} \{ \var{semantic-action} \}
;
\end{alltt}
%
Rules can also contain the \verb"%prec "{\it symbol} directive in the
right-hand side part, to override the default precedence and
associativity of the rule with the precedence and associativity of the
given symbol.
Semantic actions are arbitrary OCaml expressions, that
are evaluated to produce the semantic attribute attached to
the defined nonterminal. The semantic actions can access the
semantic attributes of the symbols in the right-hand side of
the rule with the \verb"$" notation: \verb"$1" is the attribute for the
first (leftmost) symbol, \verb"$2" is the attribute for the second
symbol, etc.
The rules may contain the special symbol "error" to indicate
resynchronization points, as in "yacc".
Actions occurring in the middle of rules are not supported.
Nonterminal symbols are like regular OCaml symbols, except that they
cannot end with "'" (single quote).
\subsection{Error handling}
Error recovery is supported as follows: when the parser reaches an
error state (no grammar rules can apply), it calls a function named
"parse_error" with the string "\"syntax error\"" as argument. The default
"parse_error" function does nothing and returns, thus initiating error
recovery (see below). The user can define a customized "parse_error"
function in the header section of the grammar file.
The parser also enters error recovery mode if one of the grammar
actions raises the "Parsing.Parse_error" exception.
In error recovery mode, the parser discards states from the
stack until it reaches a place where the error token can be shifted.
It then discards tokens from the input until it finds three successive
tokens that can be accepted, and starts processing with the first of
these. If no state can be uncovered where the error token can be
shifted, then the parser aborts by raising the "Parsing.Parse_error"
exception.
Refer to documentation on "yacc" for more details and guidance in how
to use error recovery.
\section{Options}
The "ocamlyacc" command recognizes the following options:
\begin{options}
\item["-b"{\it prefix}]
Name the output files {\it prefix}".ml", {\it prefix}".mli",
{\it prefix}".output", instead of the default naming convention.
\item["-q"]
This option has no effect.
\item["-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 \var{grammar}".output".
\item["-version"]
Print version string and exit.
\item["-vnum"]
Print short version number and exit.
\item["-"]
Read the grammar specification from standard input. The default
output file names are "stdin.ml" and "stdin.mli".
\item["--" \var{file}]
Process \var{file} as the grammar specification, even if its name
starts with a dash (-) character. This option must be the last on the
command line.
\end{options}
At run-time, the "ocamlyacc"-generated parser can be debugged by
setting the "p" option in the "OCAMLRUNPARAM" environment variable
(see section~\ref{ocamlrun-options}). This causes the pushdown
automaton executing the parser to print a trace of its action (tokens
shifted, rules reduced, etc). The trace mentions rule numbers and
state numbers that can be interpreted by looking at the file
\var{grammar}".output" generated by "ocamlyacc -v".
\section{A complete example}
The all-time favorite: a desk calculator. This program reads
arithmetic expressions on standard input, one per line, and prints
their values. Here is the grammar definition:
\begin{verbatim}
/* File parser.mly */
%token <int> INT
%token PLUS MINUS TIMES DIV
%token LPAREN RPAREN
%token EOL
%left PLUS MINUS /* lowest precedence */
%left TIMES DIV /* medium precedence */
%nonassoc UMINUS /* highest precedence */
%start main /* the entry point */
%type <int> main
%%
main:
expr EOL { $1 }
;
expr:
INT { $1 }
| LPAREN expr RPAREN { $2 }
| expr PLUS expr { $1 + $3 }
| expr MINUS expr { $1 - $3 }
| expr TIMES expr { $1 * $3 }
| expr DIV expr { $1 / $3 }
| MINUS expr %prec UMINUS { - $2 }
;
\end{verbatim}
Here is the definition for the corresponding lexer:
\begin{verbatim}
(* File lexer.mll *)
{
open Parser (* The type token is defined in parser.mli *)
exception Eof
}
rule token = parse
[' ' '\t'] { token lexbuf } (* skip blanks *)
| ['\n' ] { EOL }
| ['0'-'9']+ as lxm { INT(int_of_string lxm) }
| '+' { PLUS }
| '-' { MINUS }
| '*' { TIMES }
| '/' { DIV }
| '(' { LPAREN }
| ')' { RPAREN }
| eof { raise Eof }
\end{verbatim}
Here is the main program, that combines the parser with the lexer:
\begin{verbatim}
(* File calc.ml *)
let _ =
try
let lexbuf = Lexing.from_channel stdin in
while true do
let result = Parser.main Lexer.token lexbuf in
print_int result; print_newline(); flush stdout
done
with Lexer.Eof ->
exit 0
\end{verbatim}
To compile everything, execute:
\begin{verbatim}
ocamllex lexer.mll # generates lexer.ml
ocamlyacc parser.mly # generates parser.ml and parser.mli
ocamlc -c parser.mli
ocamlc -c lexer.ml
ocamlc -c parser.ml
ocamlc -c calc.ml
ocamlc -o calc lexer.cmo parser.cmo calc.cmo
\end{verbatim}
\section{Common errors}
\begin{options}
\item[ocamllex: transition table overflow, automaton is too big]
The deterministic automata generated by "ocamllex" are limited to at
most 32767 transitions. The message above indicates that your lexer
definition is too complex and overflows this limit. This is commonly
caused by lexer definitions that have separate rules for each of the
alphabetic keywords of the language, as in the following example.
\begin{verbatim}
rule token = parse
"keyword1" { KWD1 }
| "keyword2" { KWD2 }
| ...
| "keyword100" { KWD100 }
| ['A'-'Z' 'a'-'z'] ['A'-'Z' 'a'-'z' '0'-'9' '_'] * as id
{ IDENT id}
\end{verbatim}
To keep the generated automata small, rewrite those definitions with
only one general ``identifier'' rule, followed by a hashtable lookup
to separate keywords from identifiers:
\begin{verbatim}
{ let keyword_table = Hashtbl.create 53
let _ =
List.iter (fun (kwd, tok) -> Hashtbl.add keyword_table kwd tok)
[ "keyword1", KWD1;
"keyword2", KWD2; ...
"keyword100", KWD100 ]
}
rule token = parse
['A'-'Z' 'a'-'z'] ['A'-'Z' 'a'-'z' '0'-'9' '_'] * as id
{ try
Hashtbl.find keyword_table id
with Not_found ->
IDENT id }
\end{verbatim}
\item[ocamllex: Position memory overflow, too many bindings]
The deterministic automata generated by "ocamllex" maintain a table of
positions inside the scanned lexer buffer. The size of this table is
limited to at most 255 cells. This error should not show up in normal
situations.
\end{options}

View File

@ -0,0 +1,600 @@
\chapter{Native-code compilation (ocamlopt)} \label{c:nativecomp}
\pdfchapter{Native-code compilation (ocamlopt)}
%HEVEA\cutname{native.html}
This chapter describes the OCaml high-performance
native-code compiler "ocamlopt", which compiles OCaml source files to
native code object files and link these object files to produce
standalone executables.
The native-code compiler is only available on certain platforms.
It produces code that runs faster than the bytecode produced by
"ocamlc", at the cost of increased compilation time and executable code
size. Compatibility with the bytecode compiler is extremely high: the
same source code should run identically when compiled with "ocamlc" and
"ocamlopt".
It is not possible to mix native-code object files produced by "ocamlopt"
with bytecode object files produced by "ocamlc": a program must be
compiled entirely with "ocamlopt" or entirely with "ocamlc". Native-code
object files produced by "ocamlopt" cannot be loaded in the toplevel
system "ocaml".
\section{Overview of the compiler}
The "ocamlopt" command has a command-line interface very close to that
of "ocamlc". It accepts the same types of arguments, and processes them
sequentially:
\begin{itemize}
\item
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 \var{x}".mli", the "ocamlopt" compiler produces a compiled interface
in the file \var{x}".cmi". The interface produced is identical to that
produced by the bytecode compiler "ocamlc".
\item
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 \var{x}".ml", the "ocamlopt"
compiler produces two files: \var{x}".o", containing native object code,
and \var{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 \var{x}".cmx" (when given
a ".o" or ".obj" file, "ocamlopt" assumes that it contains code compiled from C,
not from OCaml).
The implementation is checked against the interface file \var{x}".mli"
(if it exists) as described in the manual for "ocamlc"
(chapter~\ref{c:camlc}).
\item
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 \var{x}".cmx" file must come
before all ".cmx" files that refer to the unit \var{x}.
\item
Arguments ending in ".cmxa" are taken to be libraries of object code.
Such a library packs in two files (\var{lib}".cmxa" and \var{lib}".a"/".lib")
a set of object files (".cmx" and ".o"/".obj" files). Libraries are build with
"ocamlopt -a" (see the description of the "-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.
\item
Arguments ending in ".c" are passed to the C compiler, which generates
a ".o"/".obj" object file. This object file is linked with the program.
\item
Arguments ending in ".o", ".a" or ".so" (".obj", ".lib" and ".dll"
under Windows) are assumed to be C object files and
libraries. They are linked with the program.
\end{itemize}
The output of the linking phase is a regular Unix or Windows
executable file. It does not need "ocamlrun" to run.
\section{Options}
The following command-line options are recognized by "ocamlopt".
The options "-pack", "-a", "-shared", "-c" and "-output-obj" are mutually
exclusive.
\begin{options}
\item["-a"]
Build a library (".cmxa" and ".a"/".lib" files) with the object files
(".cmx" and ".o"/".obj" files) given on the command line, instead of
linking them into an executable file. The name of the library must be
set with the "-o" option.
If "-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
"-cclib" and "-ccopt" options as if they had been provided on the
command line, unless the "-noautolink" option is given.
\item["-absname"]
Force error messages to show absolute paths for file names.
\item["-annot"]
Dump detailed information about the compilation (types, bindings,
tail-calls, etc). The information for file \var{src}".ml"
is put into file \var{src}".annot". In case of a type error, dump
all the information inferred by the type-checker before the error.
The \var{src}".annot" file can be used with the emacs commands given in
"emacs/caml-types.el" to display types and other annotations
interactively.
\item["-bin-annot"]
Dump detailed information about the compilation (types, bindings,
tail-calls, etc) in binary format. The information for file \var{src}".ml"
is put into file \var{src}".cmt". In case of a type error, dump
all the information inferred by the type-checker before the error.
The "*.cmt" files produced by "-bin-annot" contain more information
and are much more compact than the files produced by "-annot".
\item["-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.
\item["-cc" \var{ccomp}]
Use \var{ccomp} as the C linker called to build the final executable
and as the C compiler for compiling ".c" source files.
\item["-cclib" "-l"\var{libname}]
Pass the "-l"\var{libname} option to the linker. This causes the given
C library to be linked with the program.
\item["-ccopt" \var{option}]
Pass the given option to the C compiler and linker. For instance,
"-ccopt -L"\var{dir} causes the C linker to search for C libraries in
directory \var{dir}.
\item["-compact"]
Optimize the produced code for space rather than for time. This
results in slightly smaller but slightly slower programs. The default is to
optimize for speed.
\item["-config"]
Print the version number of "ocamlopt" and a detailed summary of its
configuration, then exit.
\item["-for-pack" \var{module-path}]
Generate an object file (".cmx" and ".o"/".obj" files) that can later be
included
as a sub-module (with the given access path) of a compilation unit
constructed with "-pack". For instance, "ocamlopt -for-pack P -c A.ml"
will generate "a.cmx" and "a.o" files that can later be used with
"ocamlopt -pack -o P.cmx a.cmx".
\item["-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
section~\ref{ocamlrun-options}).
\item["-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.
\item["-I" \var{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 "-nostdlib".
If the given directory starts with "+", it is taken relative to the
standard library directory. For instance, "-I +labltk" adds the
subdirectory "labltk" of the standard library to the search path.
\item["-impl" \var{filename}]
Compile the file \var{filename} as an implementation file, even if its
extension is not ".ml".
\item["-inline" \var{n}]
Set aggressiveness of inlining to \var{n}, where \var{n} is a positive
integer. Specifying "-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,
"-inline 1", allows slightly larger functions to be inlined, resulting
in a slight expansion in code size. Higher values for the "-inline"
option cause larger and larger functions to become candidate for
inlining, but can result in a serious increase in code size.
\item["-intf" \var{filename}]
Compile the file \var{filename} as an interface file, even if its
extension is not ".mli".
\item["-intf-suffix" \var{string}]
Recognize file names ending with \var{string} as interface files
(instead of the default ".mli").
\item["-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.
\item["-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 ("-a" flag), setting the "-linkall" flag forces all
subsequent links of programs involving that library to link all the
modules contained in the library.
\item["-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.
\item["-noassert"]
Do not compile assertion checks. Note that the special form
"assert false" is always compiled because it is typed specially.
This flag has no effect when linking already-compiled files.
\item["-noautolink"]
When linking ".cmxa" libraries, ignore "-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 "-noautolink" and pass the correct C
libraries and options on the command line.
\item["-nodynlink"]
Allow the compiler to use some optimizations that are valid only for code
that is never dynlinked.
\item["-nolabels"]
Ignore non-optional labels in types. Labels cannot be used in
applications, and parameter order becomes strict.
\item["-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
"-I".
\item["-o" \var{exec-file}]
Specify the name of the output file produced by the linker. The
default output name is "a.out" under Unix and "camlprog.exe" under
Windows. If the "-a" option is given, specify the name of the library
produced. If the "-pack" option is given, specify the name of the
packed object file produced. If the "-output-obj" option is given,
specify the name of the output file produced. If the "-shared" option
is given, specify the name of plugin file produced.
\item["-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. See chapter~\ref{c:intf-c},
section~\ref{s:embedded-code}. The name of the output object file
must be set with the "-o" option.
This option can also be used to produce a compiled shared/dynamic
library (".so" extension, ".dll" under Windows).
\item["-p"]
Generate extra code to write profile information when the program is
executed. The profile information can then be examined with the
analysis program "gprof". (See chapter~\ref{c:profiler} for more
information on profiling.) The "-p" option must be given both at
compile-time and at link-time. Linking object files not compiled with
"-p" is possible, but results in less precise profiling.
\begin{unix} See the Unix manual page for "gprof(1)" for more
information about the profiles.
Full support for "gprof" is only available for certain platforms
(currently: Intel x86 32 and 64 bits under Linux, BSD and MacOS X).
On other platforms, the "-p" option will result in a less precise
profile (no call graph information, only a time profile).
\end{unix}
\begin{windows}
The "-p" option does not work under Windows.
\end{windows}
\item["-pack"]
Build an object file (".cmx" and ".o"/".obj" 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 "-o" option. For instance,
\begin{verbatim}
ocamlopt -pack -o P.cmx A.cmx B.cmx C.cmx
\end{verbatim}
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 "-for-pack" option. In the example above,
"A.cmx", "B.cmx" and "C.cmx" must have been compiled with
"ocamlopt -for-pack P".
Multiple levels of packing can be achieved by combining "-pack" with
"-for-pack". Consider the following example:
\begin{verbatim}
ocamlopt -for-pack P.Q -c A.ml
ocamlopt -pack -o Q.cmx -for-pack P A.cmx
ocamlopt -for-pack P -c B.ml
ocamlopt -pack -o P.cmx Q.cmx B.cmx
\end{verbatim}
The resulting "P.cmx" object file has sub-modules "P.Q", "P.Q.A"
and "P.B".
\item["-pp" \var{command}]
Cause the compiler to call the given \var{command} as a preprocessor
for each source file. The output of \var{command} is redirected to
an intermediate file, which is compiled. If there are no compilation
errors, the intermediate file is deleted afterwards.
\item["-ppx" \var{command}]
After parsing, pipe the abstract syntax tree through the preprocessor
\var{command}. The module "Ast_mapper", described in
chapter~\ref{Ast-underscoremapper}, implements the external interface
of a preprocessor.
\item["-principal"]
Check information path during type-checking, to make sure that all
types are derived in a principal way. All programs accepted in
"-principal" mode are also accepted in default mode with equivalent
types, but different binary signatures.
\item["-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.
\item["-runtime-variant" \var{suffix}]
Add the \var{suffix} string to the name of the runtime library used by
the program. Currently, only one such suffix is supported: "d", and
only if the OCaml compiler was configured with option
"-with-debug-runtime". This suffix gives the debug version of the
runtime, which is useful for debugging pointer problems in low-level
code such as C stubs.
\item["-S"]
Keep the assembly code produced during the compilation. The assembly
code for the source file \var{x}".ml" is saved in the file \var{x}".s".
\item["-shared"]
Build a plugin (usually ".cmxs") that can be dynamically loaded with
the "Dynlink" module. The name of the plugin must be
set with the "-o" option. A plugin can include a number of OCaml
modules and libraries, and extra native objects (".o", ".obj", ".a",
".lib" 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 "-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).
\item["-safe-string"]
Enforce the separation between types "string" and "bytes",
thereby making strings read-only. This will become the default in
a future version of OCaml.
\item["-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.
\item["-strict-sequence"]
Force the left-hand part of each sequence to have type unit.
\item["-strict-formats"]
Reject invalid formats that were accepted in legacy format
implementations. You should use this flag to detect and fix such
invalid formats, as they will be rejected by future OCaml versions.
\item["-thread"]
Compile or link multithreaded programs, in combination with the
system "threads" library described in chapter~\ref{c:threads}.
\item["-unsafe"]
Turn bound checking off for array and string accesses (the "v.(i)" and
"s.[i]" constructs). Programs compiled with "-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 "-unsafe", an integer division (or modulus) by zero can halt the
program or continue with an unspecified result instead of raising a
"Division_by_zero" exception.
\item["-unsafe-string"]
Identify the types "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.
\item["-v"]
Print the version number of the compiler and the location of the
standard library directory, then exit.
\item["-verbose"]
Print all external commands before they are executed, in particular
invocations of the assembler, C compiler, and linker.
\item["-version" or "-vnum"]
Print the version number of the compiler in short form (e.g. "3.11.0"),
then exit.
\item["-w" \var{warning-list}]
Enable, disable, or mark as fatal the warnings specified by the argument
\var{warning-list}.
Each warning can be {\em enabled} or {\em disabled}, and each warning
can be {\em fatal} or {\em 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 \var{warning-list} argument is a sequence of warning specifiers,
with no separators between them. A warning specifier is one of the
following:
\begin{options}
\item["+"\var{num}] Enable warning number \var{num}.
\item["-"\var{num}] Disable warning number \var{num}.
\item["@"\var{num}] Enable and mark as fatal warning number \var{num}.
\item["+"\var{num1}..\var{num2}] Enable warnings in the given range.
\item["-"\var{num1}..\var{num2}] Disable warnings in the given range.
\item["@"\var{num1}..\var{num2}] Enable and mark as fatal warnings in
the given range.
\item["+"\var{letter}] Enable the set of warnings corresponding to
\var{letter}. The letter may be uppercase or lowercase.
\item["-"\var{letter}] Disable the set of warnings corresponding to
\var{letter}. The letter may be uppercase or lowercase.
\item["@"\var{letter}] Enable and mark as fatal the set of warnings
corresponding to \var{letter}. The letter may be uppercase or
lowercase.
\item[\var{uppercase-letter}] Enable the set of warnings corresponding
to \var{uppercase-letter}.
\item[\var{lowercase-letter}] Disable the set of warnings corresponding
to \var{lowercase-letter}.
\end{options}
Warning numbers and letters which are out of the range of warnings
that are currently defined are ignored. The warning are as follows.
\begin{options}
\input{warnings-help.tex}
\end{options}
The default setting is "-w +a-4-6-7-9-27-29-32..39-41..42-44-45".
It is displayed by "ocamlopt -help".
Note that warnings 5 and 10 are not always triggered, depending on
the internals of the type checker.
\item["-warn-error" \var{warning-list}]
Mark as fatal the warnings specified in the argument \var{warning-list}.
The compiler will stop with an error when one of these warnings is
emitted. The \var{warning-list} has the same meaning as for
the "-w" option: a "+" sign (or an uppercase letter) marks the
corresponding warnings as fatal, a "-"
sign (or a lowercase letter) turns them back into non-fatal warnings,
and a "@" sign both enables and marks as fatal the corresponding
warnings.
Note: it is not recommended to use warning sets (i.e. letters) as
arguments to "-warn-error"
in production code, because this can break your build when future versions
of OCaml add some new warnings.
The default setting is "-warn-error -a" (all warnings are non-fatal).
\item["-warn-help"]
Show the description of all available warning numbers.
\item["-where"]
Print the location of the standard library, then exit.
\item["-" \var{file}]
Process \var{file} as a file name, even if it starts with a dash (-)
character.
\item["-help" or "--help"]
Display a short usage summary and exit.
%
\end{options}
\paragraph{Options for the IA32 architecture}
The IA32 code generator (Intel Pentium, AMD Athlon) supports the
following additional option:
\begin{options}
\item["-ffast-math"] Use the IA32 instructions to compute
trigonometric and exponential functions, instead of calling the
corresponding library routines. The functions affected are:
"atan", "atan2", "cos", "log", "log10", "sin", "sqrt" and "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 "cos", "sin", "tan" have their range reduced to
$[-2^{64}, 2^{64}]$.
\end{options}
\paragraph{Options for the AMD64 architecture}
The AMD64 code generator (64-bit versions of Intel Pentium and AMD
Athlon) supports the following additional options:
\begin{options}
\item["-fPIC"] Generate position-independent machine code. This is
the default.
\item["-fno-PIC"] Generate position-dependent machine code.
\end{options}
\paragraph{Options for the Sparc architecture}
The Sparc code generator supports the following additional options:
\begin{options}
\item["-march=v8"] Generate SPARC version 8 code.
\item["-march=v9"] Generate SPARC version 9 code.
\end{options}
The default is to generate code for SPARC version 7, which runs on all
SPARC processors.
\section{Common errors}
The error messages are almost identical to those of "ocamlc".
See section~\ref{s:comp-errors}.
\section{Running executables produced by ocamlopt}
Executables generated by "ocamlopt" are native, stand-alone executable
files that can be invoked directly. They do
not depend on the "ocamlrun" bytecode runtime system nor on
dynamically-loaded C/OCaml stub libraries.
During execution of an "ocamlopt"-generated executable,
the following environment variables are also consulted:
\begin{options}
\item["OCAMLRUNPARAM"] Same usage as in "ocamlrun"
(see section~\ref{ocamlrun-options}), except that option "l"
is ignored (the operating system's stack size limit
is used instead).
\item["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.
\end{options}
\section{Compatibility with the bytecode compiler}
\label{s:compat-native-bytecode}
This section lists the known incompatibilities between the bytecode
compiler and the native-code compiler. Except on those points, the two
compilers should generate code that behave identically.
\begin{itemize}
\item Signals are detected only when the program performs an
allocation in the heap. That is, if a signal is delivered while in a
piece of code that does not allocate, its handler will not be called
until the next heap allocation.
\item Stack overflow, typically caused by excessively deep recursion,
is handled in one of the following ways, depending on the
platform used:
\begin{itemize}
\item By raising a "Stack_overflow" exception, like the bytecode
compiler does. (IA32/Linux, AMD64/Linux, PowerPC/MacOSX, MS Windows
32-bit ports).
\item By aborting the program on a ``segmentation fault'' signal.
(All other Unix systems.)
\item By terminating the program silently.
(MS Windows 64 bits).
\end{itemize}
\item On IA32 processors only (Intel and AMD x86 processors in 32-bit
mode), some intermediate results in floating-point computations are
kept in extended precision rather than being rounded to double
precision like the bytecode compiler always does. Floating-point
results can therefore differ slightly between bytecode and native code.
\end{itemize}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,170 @@
\chapter{Profiling (ocamlprof)} \label{c:profiler}
\pdfchapter{Profiling (ocamlprof)}
%HEVEA\cutname{profil.html}
This chapter describes how the execution of OCaml
programs can be profiled, by recording how many times functions are
called, branches of conditionals are taken, \ldots
\section{Compiling for profiling}
Before profiling an execution, the program must be compiled in
profiling mode, using the "ocamlcp" front-end to the "ocamlc" compiler
(see chapter~\ref{c:camlc}) or the "ocamloptp" front-end to the
"ocamlopt" compiler (see chapter~\ref{c:nativecomp}). When compiling
modules separately, "ocamlcp" or "ocamloptp" must be used when
compiling the modules (production of ".cmo" or ".cmx" files), and can
also be used (though this is not strictly necessary) when linking them
together.
\paragraph{Note} If a module (".ml" file) doesn't have a corresponding
interface (".mli" file), then compiling it with "ocamlcp" will produce
object files (".cmi" and ".cmo") that are not compatible with the ones
produced by "ocamlc", which may lead to problems (if the ".cmi" or
".cmo" is still around) when switching between profiling and
non-profiling compilations. To avoid this problem, you should always
have a ".mli" file for each ".ml" file. The same problem exists with
"ocamloptp".
\paragraph{Note} To make sure your programs can be compiled in
profiling mode, avoid using any identifier that begins with
"__ocaml_prof".
The amount of profiling information can be controlled through the "-P"
option to "ocamlcp" or "ocamloptp", followed by one or several letters
indicating which parts of the program should be profiled:
%% description des options
\begin{options}
\item["a"] all options
\item["f"] function calls : a count point is set at the beginning of
each function body
\item["i"] {\bf if \ldots then \ldots else \ldots} : count points are set in
both {\bf then} branch and {\bf else} branch
\item["l"] {\bf while, for} loops: a count point is set at the beginning of
the loop body
\item["m"] {\bf match} branches: a count point is set at the beginning of the
body of each branch
\item["t"] {\bf try \ldots with \ldots} branches: a count point is set at the
beginning of the body of each branch
\end{options}
For instance, compiling with "ocamlcp -P film" profiles function calls,
if\ldots then\ldots else\ldots, loops and pattern matching.
Calling "ocamlcp" or "ocamloptp" without the "-P" option defaults to
"-P fm", meaning that only function calls and pattern matching are
profiled.
\paragraph{Note} For compatibility with previous releases, "ocamlcp"
also accepts the "-p" option, with the same arguments and behaviour as
"-P".
The "ocamlcp" and "ocamloptp" commands also accept all the options of
the corresponding "ocamlc" or "ocamlopt" compiler, except the "-pp"
(preprocessing) option.
\section{Profiling an execution}
Running an executable that has been compiled with "ocamlcp" or
"ocamloptp" records the execution counts for the specified parts of
the program and saves them in a file called "ocamlprof.dump" in the
current directory.
If the environment variable "OCAMLPROF_DUMP" is set when the program
exits, its value is used as the file name instead of "ocamlprof.dump".
The dump file is written only if the program terminates
normally (by calling "exit" or by falling through). It is not written
if the program terminates with an uncaught exception.
If a compatible dump file already exists in the current directory, then the
profiling information is accumulated in this dump file. This allows, for
instance, the profiling of several executions of a program on
different inputs. Note that dump files produced by byte-code
executables (compiled with "ocamlcp") are compatible with the dump
files produced by native executables (compiled with "ocamloptp").
\section{Printing profiling information}
The "ocamlprof" command produces a source listing of the program modules
where execution counts have been inserted as comments. For instance,
\begin{verbatim}
ocamlprof foo.ml
\end{verbatim}
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
after it was compiled.
The following options are recognized by "ocamlprof":
\begin{options}
\item["-f" \var{dumpfile}]
Specifies an alternate dump file of profiling information to be read.
\item["-F" \var{string}]
Specifies an additional string to be output with profiling information.
By default, "ocamlprof" will annotate programs with comments of the form
{\tt (* \var{n} *)} where \var{n} is the counter value for a profiling
point. With option {\tt -F \var{s}}, the annotation will be
{\tt (* \var{s}\var{n} *)}.
\item["-impl" \var{filename}]
Process the file \var{filename} as an implementation file, even if its
extension is not ".ml".
\item["-intf" \var{filename}]
Process the file \var{filename} as an interface file, even if its
extension is not ".mli".
\item["-version"]
Print version string and exit.
\item["-vnum"]
Print short version number and exit.
\item["-help" or "--help"]
Display a short usage summary and exit.
%
\end{options}
\section{Time profiling}
Profiling with "ocamlprof" only records execution counts, not the actual
time spent within each function. There is currently no way to perform
time profiling on bytecode programs generated by "ocamlc".
Native-code programs generated by "ocamlopt" can be profiled for time
and execution counts using the "-p" option and the standard Unix
profiler "gprof". Just add the "-p" option when compiling and linking
the program:
\begin{alltt}
ocamlopt -o myprog -p \var{other-options} \var{files}
./myprog
gprof myprog
\end{alltt}
OCaml function names in the output of "gprof" have the following format:
\begin{alltt}
\var{Module-name}_\var{function-name}_\var{unique-number}
\end{alltt}
Other functions shown are either parts of the OCaml run-time system or
external C functions linked with the program.
The output of "gprof" is described in the Unix manual page for
"gprof(1)". It generally consists of two parts: a ``flat'' profile
showing the time spent in each function and the number of invocation
of each function, and a ``hierarchical'' profile based on the call
graph. Currently, only the Intel x86 ports of "ocamlopt" under
Linux, BSD and MacOS X support the two profiles. On other platforms,
"gprof" will report only the ``flat'' profile with just time
information. When reading the output of "gprof", keep in mind that
the accumulated times computed by "gprof" are based on heuristics and
may not be exact.
\paragraph{Note} The "ocamloptp" command also accepts the "-p"
option. In that case, both kinds of profiling are performed by the
program, and you can display the results with the "gprof" and "ocamlprof"
commands, respectively.

View File

@ -0,0 +1,270 @@
\chapter{The runtime system (ocamlrun)} \label{c:runtime}
\pdfchapter{The runtime system (ocamlrun)}
%HEVEA\cutname{runtime.html}
The "ocamlrun" command executes bytecode files produced by the
linking phase of the "ocamlc" command.
\section{Overview}
The "ocamlrun" command comprises three main parts: the bytecode
interpreter, that actually executes bytecode files; the memory
allocator and garbage collector; and a set of C functions that
implement primitive operations such as input/output.
The usage for "ocamlrun" is:
\begin{alltt}
ocamlrun \var{options} \var{bytecode-executable} \nth{arg}{1} ... \nth{arg}{n}
\end{alltt}
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
"Sys.argv". Element 0 of this array is the name of the
bytecode executable file; elements 1 to \var{n} are the remaining
arguments \nth{arg}{1} to \nth{arg}{n}.
As mentioned in chapter~\ref{c:camlc}, the bytecode executable files
produced by the "ocamlc" command are self-executable, and manage to
launch the "ocamlrun" command on themselves automatically. That is,
assuming "a.out" is a bytecode executable file,
\begin{alltt}
a.out \nth{arg}{1} ... \nth{arg}{n}
\end{alltt}
works exactly as
\begin{alltt}
ocamlrun a.out \nth{arg}{1} ... \nth{arg}{n}
\end{alltt}
Notice that it is not possible to pass options to "ocamlrun" when
invoking "a.out" directly.
\begin{windows}
Under several versions of Windows, bytecode executable files are
self-executable only if their name ends in ".exe". It is recommended
to always give ".exe" names to bytecode executables, e.g. compile
with "ocamlc -o myprog.exe ..." rather than "ocamlc -o myprog ...".
\end{windows}
\section{Options} \label{ocamlrun-options}
The following command-line options are recognized by "ocamlrun".
\begin{options}
\item["-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 "-g"
option to "ocamlc" set. This is equivalent to setting the "b" flag
in the "OCAMLRUNPARAM" environment variable (see below).
\item["-I" \var{dir}]
Search the directory \var{dir} for dynamically-loaded libraries,
in addition to the standard search path (see
section~\ref{s-ocamlrun-dllpath}).
\item["-p"]
Print the names of the primitives known to this version of
"ocamlrun" and exit.
\item["-v"]
Direct the memory manager to print some progress messages on
standard error. This is equivalent to setting "v=63" in the
"OCAMLRUNPARAM" environment variable (see below).
\item["-version"]
Print version string and exit.
\item["-vnum"]
Print short version number and exit.
\end{options}
\noindent
The following environment variables are also consulted:
\begin{options}
\item["CAML_LD_LIBRARY_PATH"] Additional directories to search for
dynamically-loaded libraries (see section~\ref{s-ocamlrun-dllpath}).
\item["OCAMLLIB"] The directory containing the OCaml standard
library. (If "OCAMLLIB" is not set, "CAMLLIB" will be used instead.)
Used to locate the "ld.conf" configuration file for
dynamic loading (see section~\ref{s-ocamlrun-dllpath}). If not set,
default to the library directory specified when compiling OCaml.
\item["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.
A parameter specification is an option letter followed by an "="
sign, a decimal number (or an hexadecimal number prefixed by "0x"),
and an optional multiplier. The options are documented below;
the last six correspond to the fields of the
"control" record documented in
\ifouthtml
\ahref{libref/Gc.html}{Module \texttt{Gc}}.
\else
section~\ref{Gc}.
\fi
\begin{options}
\item[b] (backtrace) Trigger the printing of a stack backtrace
when an uncaught exception aborts the program.
This option takes no argument.
\item[p] (parser trace) Turn on debugging support for
"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.
\item[R] (randomize) Turn on randomization of all hash tables by default
(see
\ifouthtml
\ahref{libref/Hashtbl.html}{Module \texttt{Hashtbl}}).
\else
section~\ref{Hashtbl}).
\fi
This option takes no argument.
\item[h] The initial size of the major heap (in words).
\item[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.
\item[s] ("minor_heap_size") Size of the minor heap. (in words)
\item[i] ("major_heap_increment") Default size increment for the
major heap. (in words)
\item[o] ("space_overhead") The major GC speed setting.
\item[O] ("max_overhead") The heap compaction trigger setting.
\item[l] ("stack_limit") The limit (in words) of the stack size.
\item[v] ("verbose") What GC messages to print to stderr. This
is a sum of values selected from the following:
\begin{options}
\item[1 (= 0x001)] Start of major GC cycle.
\item[2 (= 0x002)] Minor collection and major GC slice.
\item[4 (= 0x004)] Growing and shrinking of the heap.
\item[8 (= 0x008)] Resizing of stacks and memory manager tables.
\item[16 (= 0x010)] Heap compaction.
\item[32 (= 0x020)] Change of GC parameters.
\item[64 (= 0x040)] Computation of major GC slice size.
\item[128 (= 0x080)] Calling of finalization functions
\item[256 (= 0x100)] Startup messages (loading the bytecode
executable file, resolving shared libraries).
\item[512 (= 0x200)] Computation of compaction-triggering condition.
\end{options}
\end{options}
The multiplier is "k", "M", or "G", for multiplication by $2^{10}$,
$2^{20}$, and $2^{30}$ respectively.
For example, on a 32-bit machine, under "bash" the command
\begin{verbatim}
export OCAMLRUNPARAM='b,s=256k,v=0x015'
\end{verbatim}
tells a subsequent "ocamlrun" to print backtraces for uncaught exceptions,
set its initial minor heap size to 1~megabyte and
print a message at the start of each major GC cycle, when the heap
size changes, and when compaction is triggered.
\item["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.
\item["PATH"] List of directories searched to find the bytecode
executable file.
\end{options}
\section{Dynamic loading of shared libraries} \label{s-ocamlrun-dllpath}
On platforms that support dynamic loading, "ocamlrun" can link
dynamically with C shared libraries (DLLs) providing additional C primitives
beyond those provided by the standard runtime system. The names for
these libraries are provided at link time as described in
section~\ref{dynlink-c-code}), and recorded in the bytecode executable
file; "ocamlrun", then, locates these libraries and resolves references
to their primitives when the bytecode executable program starts.
The "ocamlrun" command searches shared libraries in the following
directories, in the order indicated:
\begin{enumerate}
\item Directories specified on the "ocamlrun" command line with the
"-I" option.
\item Directories specified in the "CAML_LD_LIBRARY_PATH" environment
variable.
\item Directories specified at link-time via the "-dllpath" option to
"ocamlc". (These directories are recorded in the bytecode executable
file.)
\item Directories specified in the file "ld.conf". This file resides
in the OCaml standard library directory, and lists directory
names (one per line) to be searched. Typically, it contains only one
line naming the "stublibs" subdirectory of the OCaml standard
library directory. Users can add there the names of other directories
containing frequently-used shared libraries; however, for consistency
of installation, we recommend that shared libraries are installed
directly in the system "stublibs" directory, rather than adding lines
to the "ld.conf" file.
\item Default directories searched by the system dynamic loader.
Under Unix, these generally include "/lib" and "/usr/lib", plus the
directories listed in the file "/etc/ld.so.conf" and the environment
variable "LD_LIBRARY_PATH". Under Windows, these include the Windows
system directories, plus the directories listed in the "PATH"
environment variable.
\end{enumerate}
\section{Common errors}
This section describes and explains the most frequently encountered
error messages.
\begin{options}
\item[{\it filename}": no such file or directory"]
If {\it filename} is the name of a self-executable bytecode file, this
means that either that file does not exist, or that it failed to run
the "ocamlrun" bytecode interpreter on itself. The second possibility
indicates that OCaml has not been properly installed on your
system.
\item["Cannot exec ocamlrun"]
(When launching a self-executable bytecode file.) The "ocamlrun"
could not be found in the executable path. Check that OCaml
has been properly installed on your system.
\item["Cannot find the bytecode file"]
The file that "ocamlrun" is trying to execute (e.g. the file given as
first non-option argument to "ocamlrun") either does not exist, or is
not a valid executable bytecode file.
\item["Truncated bytecode file"]
The file that "ocamlrun" is trying to execute is not a valid executable
bytecode file. Probably it has been truncated or mangled since
created. Erase and rebuild it.
\item["Uncaught exception"]
The program being executed contains a ``stray'' exception. That is,
it raises an exception at some point, and this exception is never
caught. This causes immediate termination of the program. The name of
the exception is printed, along with its string, byte sequence, and
integer arguments
(arguments of more complex types are not correctly printed).
To locate the context of the uncaught exception, compile the program
with the "-g" option and either run it again under the "ocamldebug"
debugger (see chapter~\ref{c:debugger}), or run it with "ocamlrun -b"
or with the "OCAMLRUNPARAM" environment variable set to "b=1".
\item["Out of memory"]
The program being executed requires more memory than available. Either
the program builds excessively large data structures; or the program
contains too many nested function calls, and the stack overflows. In
some cases, your program is perfectly correct, it just requires more
memory than your machine provides. In other cases, the ``out of
memory'' message reveals an error in your program: non-terminating
recursive function, allocation of an excessively large array,
string or byte sequence, attempts to build an infinite list or other
data structure, \ldots
To help you diagnose this error, run your program with the "-v" option
to "ocamlrun", or with the "OCAMLRUNPARAM" environment variable set to
"v=63". If it displays lots of ``"Growing stack"\ldots''
messages, this is probably a looping recursive function. If it
displays lots of ``"Growing heap"\ldots'' messages, with the heap size
growing slowly, this is probably an attempt to construct a data
structure with too many (infinitely many?) cells. If it displays few
``"Growing heap"\ldots'' messages, but with a huge increment in the
heap size, this is probably an attempt to build an excessively large
array, string or byte sequence.
\end{options}

528
manual/manual/cmds/top.etex Normal file
View File

@ -0,0 +1,528 @@
\chapter{The toplevel system (ocaml)} \label{c:camllight}
\pdfchapter{The toplevel system (ocaml)}
%HEVEA\cutname{toplevel.html}
This chapter describes 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, compile and
evaluate them, then prints the inferred type and result value, if
any. The system prints a "#" (sharp) prompt before reading each
phrase.
Input to the toplevel can span several lines. It is terminated by @";;"@ (a
double-semicolon). The toplevel input consists in one or several
toplevel phrases, with the following syntax:
\begin{syntax}
toplevel-input:
{{ definition }} ';;'
| expr ';;'
| '#' ident [ directive-argument ] ';;'
;
directive-argument:
string-literal
| integer-literal
| value-path
| 'true' || 'false'
\end{syntax}
A phrase can consist of a definition, like those found in
implementations of compilation units or in @'struct' \ldots 'end'@
module expressions. The definition can bind value names, type names,
an exception, a module name, or a module type name. The toplevel
system performs the bindings, then prints the types and values (if
any) for the names thus defined.
A phrase may also consist in a value expression
(section~\ref{s:value-expr}). It is simply evaluated
without performing any bindings, and its value is
printed.
Finally, a phrase can also consist in a toplevel directive,
starting with @"#"@ (the sharp sign). These directives control the
behavior of the toplevel; they are listed below in
section~\ref{s:toplevel-directives}.
\begin{unix}
The toplevel system is started by the command "ocaml", as follows:
\begin{alltt}
ocaml \var{options} \var{objects} # interactive mode
ocaml \var{options} \var{objects} \var{scriptfile} # script mode
\end{alltt}
\var{options} are described below.
\var{objects} are filenames ending in ".cmo" or ".cma"; they are
loaded into the interpreter immediately after \var{options} are set.
\var{scriptfile} is any file name not ending in ".cmo" or ".cma".
If no \var{scriptfile} is given on the command line, the toplevel system
enters interactive mode: phrases are read on standard input, results
are printed on standard output, errors on standard error. End-of-file
on standard input terminates "ocaml" (see also the "#quit" directive
in section~\ref{s:toplevel-directives}).
On start-up (before the first phrase is read), if the file
".ocamlinit" exists in the current directory,
its contents are read as a sequence of OCaml phrases
and executed as per the "#use" directive
described in section~\ref{s:toplevel-directives}.
The evaluation outcode for each phrase are not displayed.
If the current directory does not contain an ".ocamlinit" file, but
the user's home directory (environment variable "HOME") does, the
latter is read and executed as described below.
The toplevel system does not perform line editing, but it can
easily be used in conjunction with an external line editor such as
"ledit", "ocaml2" or "rlwrap"
\begin{latexonly}
(see the Caml Hump "http://caml.inria.fr/humps/index_framed_caml.html").
\end{latexonly}
\begin{htmlonly}
(see the
\ahref{http://caml.inria.fr/humps/index\_framed\_caml.html}{Caml Hump}).
\end{htmlonly}
Another option is to use "ocaml" under Gnu Emacs, which gives the
full editing power of Emacs (command "run-caml" from library "inf-caml").
At any point, the parsing, compilation or evaluation of the current
phrase can be interrupted by pressing "ctrl-C" (or, more precisely,
by sending the "INTR" signal to the "ocaml" process). The toplevel
then immediately returns to the "#" prompt.
If \var{scriptfile} is given on the command-line to "ocaml", the toplevel
system enters script mode: the contents of the file are read as a
sequence of OCaml phrases and executed, as per the "#use"
directive (section~\ref{s:toplevel-directives}). The outcome of the
evaluation is not printed. On reaching the end of file, the "ocaml"
command exits immediately. No commands are read from standard input.
"Sys.argv" is transformed, ignoring all OCaml parameters, and
starting with the script file name in "Sys.argv.(0)".
In script mode, the first line of the script is ignored if it starts
with "#!". Thus, it should be possible to make the script
itself executable and put as first line "#!/usr/local/bin/ocaml",
thus calling the toplevel system automatically when the script is
run. However, "ocaml" itself is a "#!" script on most installations
of OCaml, and Unix kernels usually do not handle nested "#!"
scripts. A better solution is to put the following as the first line
of the script:
\begin{verbatim}
#!/usr/local/bin/ocamlrun /usr/local/bin/ocaml
\end{verbatim}
\end{unix}
\begin{windows}
In addition to the text-only command "ocaml.exe", which works exactly
as under Unix (see above), a graphical user interface for the
toplevel is available under the name "ocamlwin.exe". It should be
launched from the Windows file manager or program manager.
This interface provides a text window in which commands can be entered
and edited, and the toplevel responses are printed.
\end{windows}
\section{Options} \label{s:toplevel-options}
The following command-line options are recognized by the "ocaml" command.
\begin{options}
\item["-absname"]
Force error messages to show absolute paths for file names.
\item["-I" \var{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 "-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.
If the given directory starts with "+", it is taken relative to the
standard library directory. For instance, "-I +labltk" adds the
subdirectory "labltk" of the standard library to the search path.
Directories can also be added to the list once
the toplevel is running with the "#directory" directive
(section~\ref{s:toplevel-directives}).
\item["-init" \var{file}]
Load the given file instead of the default initialization file.
The default file is ".ocamlinit" in the current directory if it
exists, otherwise ".ocamlinit" in the user's home directory.
\item["-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.
\item["-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.
\item["-noassert"]
Do not compile assertion checks. Note that the special form
"assert false" is always compiled because it is typed specially.
\item["-nolabels"]
Ignore non-optional labels in types. Labels cannot be used in
applications, and parameter order becomes strict.
\item["-noprompt"]
Do not display any prompt when waiting for input.
\item["-nopromptcont"]
Do not display the secondary prompt when waiting for continuation
lines in multi-line inputs. This should be used e.g. when running
"ocaml" in an "emacs" window.
\item["-nostdlib"]
Do not include the standard library directory in the list of
directories searched for source and compiled files.
\item["-ppx" \var{command}]
After parsing, pipe the abstract syntax tree through the preprocessor
\var{command}. The module "Ast_mapper", described in
chapter~\ref{Ast-underscoremapper}, implements the external interface
of a preprocessor.
\item["-principal"]
Check information paths 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 "-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.
\item["-rectypes"]
Allow arbitrary recursive types during type-checking. By default,
only recursive types where the recursion goes through an object type
are supported.
\item["-safe-string"]
Enforce the separation between types "string" and "bytes",
thereby making strings read-only. This will become the default in
a future version of OCaml.
\item["-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.
\item["-stdin"]
Read the standard input as a script file rather than starting an
interactive session.
\item["-strict-sequence"]
Force the left-hand part of each sequence to have type unit.
\item["-strict-formats"]
Reject invalid formats that were accepted in legacy format
implementations. You should use this flag to detect and fix such
invalid formats, as they will be rejected by future OCaml versions.
\item["-unsafe"]
See the corresponding option for "ocamlc", chapter~\ref{c:camlc}.
Turn bound checking off on array and string accesses (the "v.(i)" and
"s.[i]" constructs). Programs compiled with "-unsafe" are therefore
slightly faster, but unsafe: anything can happen if the program
accesses an array or string outside of its bounds.
\item["-unsafe-string"]
Identify the types "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.
\item["-version"]
Print version string and exit.
\item["-vnum"]
Print short version number and exit.
\item["-w" \var{warning-list}]
Enable or disable warnings according to the argument \var{warning-list}.
See section~\ref{s:comp-options} for the syntax of the argument.
\item["-warn-error" \var{warning-list}]
Mark as fatal the warnings enabled by the argument \var{warning-list}.
See section~\ref{s:comp-options} for the syntax of the argument.
\item["-warn-help"]
Show the description of all available warning numbers.
\item["-" \var{file}]
Use \var{file} as a script file name, even when it starts with a
hyphen (-).
\item["-help" or "--help"]
Display a short usage summary and exit.
%
\end{options}
\begin{unix}
The following environment variables are also consulted:
\begin{options}
\item["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
("\\"\var{ddd}).
\item["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.
\item["HOME"] Directory where the ".ocamlinit" file is searched.
\end{options}
\end{unix}
\section{Toplevel directives}
\label{s:toplevel-directives}
The following directives control the toplevel behavior, load files in
memory, and trace program execution.
{\bf Note:} all directives start with a "#" (sharp) symbol. This "#"
must be typed before the directive, and must not be confused with the
"#" prompt displayed by the interactive loop. For instance,
typing "#quit;;" will exit the toplevel loop, but typing "quit;;"
will result in an ``unbound value "quit"'' error.
\begin{options}
\item["#quit;;"]
Exit the toplevel loop and terminate the "ocaml" command.
\item["#labels "\var{bool}";;"]
Ignore labels in function types if argument is "false", or switch back
to default behaviour (commuting style) if argument is "true".
\item["#principal "\var{bool}";;"]
If the argument is "true", check information paths during
type-checking, to make sure that all types are derived in a principal
way. If the argument is "false", do not check information paths.
\item["#rectypes;;"]
Allow arbitrary recursive types during type-checking. Note: once
enabled, this option cannot be disabled because that would lead to
unsoundness of the type system.
\item["#warnings \""\var{warning-list}"\";;"]
Enable or disable warnings according to the argument.
\item["#warn_error \""\var{warning-list}"\";;"]
Treat as errors the warnings enabled by the argument and as normal
warnings the warnings disabled by the argument.
\item["#directory \""\var{dir-name}"\";;"]
Add the given directory to the list of directories searched for
source and compiled files.
\item["#remove_directory \""\var{dir-name}"\";;"]
Remove the given directory from the list of directories searched for
source and compiled files. Do nothing if the list does not contain
the given directory.
\item["#cd \""\var{dir-name}"\";;"]
Change the current working directory.
\item["#load \""\var{file-name}"\";;"]
Load in memory a bytecode object file (".cmo" file) or library file
(".cma" file) produced by the batch compiler "ocamlc".
\item["#load_rec \""\var{file-name}"\";;"]
Load in memory a bytecode object file (".cmo" file) or library file
(".cma" file) produced by the batch compiler "ocamlc".
When loading an object file that depends on other modules
which have not been loaded yet, the .cmo files for these modules
are searched and loaded as well, recursively. The loading order
is not specified.
\item["#use \""\var{file-name}"\";;"]
Read, compile and execute source phrases from the given file.
This is textual inclusion: phrases are processed just as if
they were typed on standard input. The reading of the file stops at
the first error encountered.
\item["#mod_use \""\var{file-name}"\";;"]
Similar to "#use" but also wrap the code into a top-level module of the
same name as capitalized file name without extensions, following
semantics of the compiler.
\item["#install_printer "\var{printer-name}";;"]
This directive registers the function named \var{printer-name} (a
value path) as a printer for values whose types match the argument
type of the function. That is, the toplevel loop will call
\var{printer-name} when it has such a value to print.
The printing function \var{printer-name} should have type
@"Format.formatter" "->" @t@ "->" "unit"@, where @@t@@ is the
type for the values to be printed, and should output its textual
representation for the value of type @@t@@ on the given formatter,
using the functions provided by the "Format" library. For backward
compatibility, \var{printer-name} can also have type
@@t@ "->" "unit"@ and should then output on the standard
formatter, but this usage is deprecated.
\item["#remove_printer "\var{printer-name}";;"]
Remove the named function from the table of toplevel printers.
\item["#trace "\var{function-name}";;"]
After executing this directive, all calls to the function named
\var{function-name} will be ``traced''. That is, the argument and the
result are displayed for each call, as well as the exceptions escaping
out of the function, raised either by the function itself or by
another function it calls. If the function is curried, each argument
is printed as it is passed to the function.
\item["#untrace "\var{function-name}";;"]
Stop tracing the given function.
\item["#untrace_all;;"]
Stop tracing all functions traced so far.
\item["#print_depth "\var{n}";;"]
Limit the printing of values to a maximal depth of \var{n}.
The parts of values whose depth exceeds \var{n} are printed as "..."
(ellipsis).
\item["#print_length "\var{n}";;"]
Limit the number of value nodes printed to at most \var{n}.
Remaining parts of values are printed as "..." (ellipsis).
\item["#show_val "\var{value-path}";;"]\vspace{-4.7ex}
\item["#show_type "\var{typeconstr}";;"]\vspace{-4.7ex}
\item["#show_module "\var{module-path}";;"]\vspace{-4.7ex}
\item["#show_module_type "\var{modtype-path}";;"]\vspace{-4.7ex}
\item["#show_class "\var{class-path}";;"]\vspace{-4.7ex}
\item["#show_class_type "\var{class-path}";;"]
Print the signature of the corresponding component.
\item["#show "\var{ident}";;"]
Print the signatures of components with name \var{ident} in all the
above categories.
\end{options}
\section{The toplevel and the module system} \label{s:toplevel-modules}
Toplevel phrases can refer to identifiers defined in compilation units
with the same mechanisms as for separately compiled units: either by
using qualified names ("Modulename.localname"), or by using
the "open" construct and unqualified names (see section~\ref{s:names}).
However, before referencing another compilation unit, an
implementation of that unit must be present in memory.
At start-up, the toplevel system contains implementations for all the
modules in the the standard library. Implementations for user modules
can be entered with the "#load" directive described above. Referencing
a unit for which no implementation has been provided
results in the error "Reference to undefined global `...'".
Note that entering "open "\var{Mod} merely accesses the compiled
interface (".cmi" file) for \var{Mod}, but does not load the
implementation of \var{Mod}, and does not cause any error if no
implementation of \var{Mod} has been loaded. The error
``reference to undefined global \var{Mod}'' will occur only when
executing a value or module definition that refers to \var{Mod}.
\section{Common errors}
This section describes and explains the most frequently encountered
error messages.
\begin{options}
\item[Cannot find file \var{filename}]
The named file could not be found in the current directory, nor in the
directories of the search path.
If \var{filename} has the format \var{mod}".cmi", this
means you have referenced the compilation unit \var{mod}, but its
compiled interface could not be found. Fix: compile \var{mod}".mli" or
\var{mod}".ml" first, to create the compiled interface \var{mod}".cmi".
If \var{filename} has the format \var{mod}".cmo", this
means you are trying to load with "#load" a bytecode object file that
does not exist yet. Fix: compile \var{mod}".ml" first.
If your program spans several directories, this error can also appear
because you haven't specified the directories to look into. Fix: use
the "#directory" directive to add the correct directories to the
search path.
\item[This expression has type \nth{t}{1}, but is used with type \nth{t}{2}]
See section~\ref{s:comp-errors}.
\item[Reference to undefined global \var{mod}]
You have neglected to load in memory an implementation for a module
with "#load". See section~\ref{s:toplevel-modules} above.
\end{options}
\section{Building custom toplevel systems: \texttt{ocamlmktop}}
The "ocamlmktop" command builds OCaml toplevels that
contain user code preloaded at start-up.
The "ocamlmktop" command takes as argument a set of ".cmo" and ".cma"
files, and links them with the object files that implement the OCaml toplevel.
The typical use is:
\begin{verbatim}
ocamlmktop -o mytoplevel foo.cmo bar.cmo gee.cmo
\end{verbatim}
This creates the bytecode file "mytoplevel", containing the OCaml toplevel
system, plus the code from the three ".cmo"
files. This toplevel is directly executable and is started by:
\begin{verbatim}
./mytoplevel
\end{verbatim}
This enters a regular toplevel loop, except that the code from
"foo.cmo", "bar.cmo" and "gee.cmo" is already loaded in memory, just as
if you had typed:
\begin{verbatim}
#load "foo.cmo";;
#load "bar.cmo";;
#load "gee.cmo";;
\end{verbatim}
on entrance to the toplevel. The modules "Foo", "Bar" and "Gee" are
not opened, though; you still have to do
\begin{verbatim}
open Foo;;
\end{verbatim}
yourself, if this is what you wish.
\section{Options}
The following command-line options are recognized by "ocamlmktop".
\begin{options}
\item["-cclib" \var{libname}]
Pass the "-l"\var{libname} option to the C linker when linking in
``custom runtime'' mode. See the corresponding option for
"ocamlc", in chapter~\ref{c:camlc}.
\item["-ccopt" \var{option}]
Pass the given option to the C compiler and linker, when linking in
``custom runtime'' mode. See the corresponding option for
"ocamlc", in chapter~\ref{c:camlc}.
\item["-custom"]
Link in ``custom runtime'' mode. See the corresponding option for
"ocamlc", in chapter~\ref{c:camlc}.
\item["-I" \var{directory}]
Add the given directory to the list of directories searched for
compiled object code files (".cmo" and ".cma").
\item["-o" \var{exec-file}]
Specify the name of the toplevel file produced by the linker.
The default is "a.out".
\end{options}

View File

@ -0,0 +1,81 @@
\chapter*{Foreword}
\markboth{Foreword}{}
%HEVEA\cutname{foreword.html}
This manual documents the release \ocamlversion\ of the OCaml
system. It is organized as follows.
\begin{itemize}
\item Part~\ref{p:tutorials}, ``An introduction to OCaml'',
gives an overview of the language.
\item Part~\ref{p:refman}, ``The OCaml language'', is the
reference description of the language.
\item Part~\ref{p:commands}, ``The OCaml tools'', documents
the compilers, toplevel system, and programming utilities.
\item Part~\ref{p:library}, ``The OCaml library'', describes the
modules provided in the standard library.
\begin{latexonly}
\item Part~\ref{p:appendix}, ``Appendix'', contains an
index of all identifiers defined in the standard library, and an
index of keywords.
\end{latexonly}
\end{itemize}
\section*{Conventions}
OCaml runs on several operating systems. The parts of
this manual that are specific to one operating system are presented as
shown below:
\begin{unix} This is material specific to the Unix family of operating
systems, including Linux and \hbox{MacOS~X}.
\end{unix}
\begin{windows} This is material specific to Microsoft Windows (2000,
XP, Vista, Seven).
\end{windows}
\section*{License}
The OCaml system is copyright \copyright\ 1996--\number\year\
Institut National de Recherche en Informatique et en
Automatique (INRIA).
INRIA holds all ownership rights to the OCaml system.
The OCaml system is open source and can be freely
redistributed. See the file "LICENSE" in the distribution for
licensing information.
The present documentation is copyright \copyright\ \number\year\
Institut National de Recherche en Informatique et en
Automatique (INRIA). The OCaml documentation and user's
manual may be reproduced and distributed in whole or
in part, subject to the following conditions:
\begin{itemize}
\item The copyright notice above and this permission notice must be
preserved complete on all complete or partial copies.
\item Any translation or derivative work of the OCaml
documentation and user's manual must be approved by the authors in
writing before distribution.
\item If you distribute the OCaml
documentation and user's manual in part, instructions for obtaining
the complete version of this manual must be included, and a
means for obtaining a complete version provided.
\item Small portions may be reproduced as illustrations for reviews or
quotes in other works without this permission notice if proper
citation is given.
\end{itemize}
\section*{Availability}
\begin{latexonly}
The complete OCaml distribution can be accessed via the Web
site \url{http://caml.inria.fr/}. This Web site contains a lot of
additional information on OCaml.
\end{latexonly}
\begin{htmlonly}
The complete OCaml distribution can be accessed via the
\href{http://caml.inria.fr/}{Caml Web site}.
The \href{http://caml.inria.fr/}{Caml Web site}
contains a lot of additional information on OCaml.
\end{htmlonly}

View File

@ -0,0 +1,8 @@
*.html
*.haux
*.hind
libref
manual.hmanual
manual.hmanual.kwd
manual.css
*.htoc

8
manual/manual/htmlman/.gitignore vendored Normal file
View File

@ -0,0 +1,8 @@
*.html
*.haux
*.hind
libref
manual.hmanual
manual.hmanual.kwd
manual.css
*.htoc

Binary file not shown.

After

Width:  |  Height:  |  Size: 316 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 317 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 317 B

20
manual/manual/index.tex Normal file
View File

@ -0,0 +1,20 @@
\ifouthtml
\begin{rawhtml}
<ul>
<li><a HREF=libref/index_modules.html>Index of modules</a></li>
<li><a HREF=libref/index_module_types.html>Index of module types</a></li>
<li><a HREF=libref/index_types.html>Index of types</a></li>
<li><a HREF=libref/index_exceptions.html>Index of exceptions</a></li>
<li><a HREF=libref/index_values.html>Index of values</a></li>
</ul>
\end{rawhtml}
\else
\chapter*{Index to the library}
\markright{Index to the library}
\addcontentsline{toc}{chapter}{Index to the library}
\myprintindex{\jobname.ind}
\fi
\chapter*{Index of keywords}
\markright{Index of keywords}
\addcontentsline{toc}{chapter}{Index of keywords}
\myprintindex{\jobname.kwd.ind}

View File

@ -0,0 +1,4 @@
*.haux
*.hind
*.info*.gz
ocaml.hocaml.kwd

5
manual/manual/infoman/.gitignore vendored Normal file
View File

@ -0,0 +1,5 @@
*.haux
*.hind
*.info*.gz
*.info.body*
ocaml.hocaml.kwd

42
manual/manual/labltk.tex Normal file
View File

@ -0,0 +1,42 @@
\documentclass[11pt]{book}
\usepackage[latin1]{inputenc}
%HEVEA\@def@charset{US-ASCII}%
\usepackage{alltt}
\usepackage{fullpage}
\usepackage{syntaxdef}
\usepackage{multind}
\usepackage{html}
\usepackage{textcomp}
\usepackage{caml-sl}
\usepackage{ocamldoc}
\usepackage{xspace}
\newif\ifplaintext
\plaintextfalse
%\newif\ifpdf
%\pdffalse
\input{macros.tex}
\usepackage{hyperref}
%\makeatletter \def\@wrindex#1#2{\xdef \@indexfile{\csname #1@idxfile\endcsname}\@@wrindex#2||\\}\makeatother
\def\th{^{\hbox{\scriptsize th}}}
\raggedbottom
\input{version.tex}
\begin{document}
\thispagestyle{empty}
\begin{center}
~\vfill
\Huge The LablTk library
release 8.06.0 \\
and \\
The OCamlBrowser library explorer \\[1cm]
\large Jacques Garrigue, Jun Furuse \\
\today \\
\vfill
\end{center}
\setcounter{page}{1}
\input{library/liblabltk.tex}
\input{cmds/browser.tex}
\end{document}

View File

@ -0,0 +1,5 @@
*.tex
*.htex
arithstatus.mli
ocamldoc.out
ocamldoc.sty

5
manual/manual/library/.gitignore vendored Normal file
View File

@ -0,0 +1,5 @@
*.tex
*.htex
arithstatus.mli
ocamldoc.out
ocamldoc.sty

View File

@ -0,0 +1,103 @@
CORE_INTF=Pervasives.tex
STDLIB_INTF=Arg.tex Array.tex ArrayLabels.tex Char.tex Complex.tex \
Digest.tex Filename.tex Format.tex \
Gc.tex Genlex.tex Hashtbl.tex Int32.tex Int64.tex \
Lazy.tex Lexing.tex List.tex ListLabels.tex Map.tex Marshal.tex \
MoreLabels.tex Nativeint.tex Obj.tex Oo.tex \
Parsing.tex Printexc.tex Printf.tex Queue.tex Random.tex Scanf.tex \
Set.tex Sort.tex Stack.tex Stream.tex String.tex StringLabels.tex Sys.tex \
Weak.tex Callback.tex Buffer.tex StdLabels.tex \
Bytes.tex BytesLabels.tex
COMPILER_LIBS_INTF=Asthelper.tex Astmapper.tex Asttypes.tex \
Lexer.tex Location.tex Longident.tex Parse.tex Pprintast.tex Printast.tex
OTHERLIB_INTF=Unix.tex UnixLabels.tex Str.tex \
Num.tex Arithstatus.tex Bigint.tex \
Graphics.tex GraphicsX11.tex \
Thread.tex Mutex.tex Condition.tex Event.tex ThreadUnix.tex \
Dynlink.tex Bigarray.tex
INTF=$(CORE_INTF) $(STDLIB_INTF) $(COMPILER_LIBS_INTF) $(OTHERLIB_INTF)
MLIS=$(CSLDIR)/stdlib/*.mli \
$(CSLDIR)/utils/*.mli \
$(CSLDIR)/parsing/*.mli \
$(CSLDIR)/otherlibs/bigarray/bigarray.mli \
$(CSLDIR)/otherlibs/dynlink/dynlink.mli \
$(CSLDIR)/otherlibs/graph/graphics.mli \
$(CSLDIR)/otherlibs/graph/graphicsX11.mli \
$(CSLDIR)/otherlibs/num/num.mli \
$(CSLDIR)/otherlibs/num/arith_status.mli \
$(CSLDIR)/otherlibs/num/big_int.mli \
$(CSLDIR)/otherlibs/str/*.mli \
$(CSLDIR)/otherlibs/systhreads/*.mli \
$(CSLDIR)/otherlibs/unix/*.mli
BLURB=core.tex builtin.tex stdlib.tex compilerlibs.tex \
libunix.tex libstr.tex libnum.tex libgraph.tex \
libthreads.tex libdynlink.tex libbigarray.tex
FILES=$(BLURB) $(INTF)
FORMAT=../../tools/format-intf
TEXQUOTE=../../tools/texquote2
CSLDIR=$(RELEASEDIR)
VPATH=.:$(CSLDIR)/stdlib:$(CSLDIR)/parsing:$(CSLDIR)/otherlibs/unix:$(CSLDIR)/otherlibs/str:$(CSLDIR)/otherlibs/num:$(CSLDIR)/otherlibs/graph:$(CSLDIR)/otherlibs/threads:$(CSLDIR)/otherlibs/dynlink:$(CSLDIR)/otherlibs/bigarray
all: libs
libs: $(FILES)
$(INTF): $(MLIS)
$(CSLDIR)/byterun/ocamlrun $(CSLDIR)/ocamldoc/ocamldoc -latex \
-I $(CSLDIR)/utils \
-I $(CSLDIR)/stdlib \
-I $(CSLDIR)/parsing \
-I $(CSLDIR)/otherlibs/bigarray \
-I $(CSLDIR)/otherlibs/dynlink \
-I $(CSLDIR)/otherlibs/graph \
-I $(CSLDIR)/otherlibs/num \
-I $(CSLDIR)/otherlibs/str \
-I $(CSLDIR)/otherlibs/systhreads \
-I $(CSLDIR)/otherlibs/unix \
$(MLIS) \
-sepfiles \
-latextitle "6,subsection*" \
-latextitle "7,subsubsection*" \
-latex-type-prefix "TYP" \
-latex-module-prefix "" \
-latex-module-type-prefix "" \
-latex-value-prefix ""
mv -f Arith_status.tex Arithstatus.tex
mv -f Big_int.tex Bigint.tex
mv -f Ast_helper.tex Asthelper.tex
mv -f Ast_mapper.tex Astmapper.tex
Tk.tex: tk.mli
$(CSLDIR)/byterun/ocamlrun $(CSLDIR)/ocamldoc/ocamldoc -latex \
-I +labltk tk.mli \
-sepfiles \
-latextitle "6,subsection*" \
-latextitle "7,subsubsection*" \
-latex-type-prefix "TYP" \
-latex-module-prefix "" \
-latex-module-type-prefix "" \
-latex-value-prefix ""
clean:
rm -f $(FILES)
.SUFFIXES:
.SUFFIXES: .tex .etex .mli
.etex.tex: $(TEXQUOTE)
$(TEXQUOTE) < $*.etex > $*.tex
.mli.tex: $(FORMAT)
$(FORMAT) $< > $*.tex < $<

View File

@ -0,0 +1,281 @@
\section{Built-in types and predefined exceptions}
The following built-in types and predefined exceptions are always
defined in the
compilation environment, but are not part of any module. As a
consequence, they can only be referred by their short names.
%\vspace{0.1cm}
\subsection*{Built-in types}
%\vspace{0.1cm}
\begin{ocamldoccode}
type int
\end{ocamldoccode}
\index{int@\verb`int`}
\begin{ocamldocdescription}
The type of integer numbers.
\end{ocamldocdescription}
\begin{ocamldoccode}
type char
\end{ocamldoccode}
\index{char@\verb`char`}
\begin{ocamldocdescription}
The type of characters.
\end{ocamldocdescription}
\begin{ocamldoccode}
type bytes
\end{ocamldoccode}
\index{bytes@\verb`bytes`}
\begin{ocamldocdescription}
The type of (writable) byte sequences.
\end{ocamldocdescription}
\begin{ocamldoccode}
type string
\end{ocamldoccode}
\index{string@\verb`string`}
\begin{ocamldocdescription}
The type of (read-only) character strings.
\end{ocamldocdescription}
\begin{ocamldoccode}
type float
\end{ocamldoccode}
\index{float@\verb`float`}
\begin{ocamldocdescription}
The type of floating-point numbers.
\end{ocamldocdescription}
\begin{ocamldoccode}
type bool = false | true
\end{ocamldoccode}
\index{bool@\verb`bool`}
\begin{ocamldocdescription}
The type of booleans (truth values).
\end{ocamldocdescription}
\begin{ocamldoccode}
type unit = ()
\end{ocamldoccode}
\index{unit@\verb`unit`}
\begin{ocamldocdescription}
The type of the unit value.
\end{ocamldocdescription}
\begin{ocamldoccode}
type exn
\end{ocamldoccode}
\index{exn@\verb`exn`}
\begin{ocamldocdescription}
The type of exception values.
\end{ocamldocdescription}
\begin{ocamldoccode}
type 'a array
\end{ocamldoccode}
\index{array@\verb`array`}
\begin{ocamldocdescription}
The type of arrays whose elements have type "'a".
\end{ocamldocdescription}
\begin{ocamldoccode}
type 'a list = [] | :: of 'a * 'a list
\end{ocamldoccode}
\index{list@\verb`list`}
\begin{ocamldocdescription}
The type of lists whose elements have type "'a".
\end{ocamldocdescription}
\begin{ocamldoccode}
type 'a option = None | Some of 'a
\end{ocamldoccode}
\index{option@\verb`option`}
\begin{ocamldocdescription}
The type of optional values of type "'a".
\end{ocamldocdescription}
\begin{ocamldoccode}
type int32
\end{ocamldoccode}
\index{int32@\verb`int32`}
\begin{ocamldocdescription}
The type of signed 32-bit integers.
See the "Int32"[\moduleref{Int32}] module.
\end{ocamldocdescription}
\begin{ocamldoccode}
type int64
\end{ocamldoccode}
\index{int64@\verb`int64`}
\begin{ocamldocdescription}
The type of signed 64-bit integers.
See the "Int64"[\moduleref{Int64}] module.
\end{ocamldocdescription}
\begin{ocamldoccode}
type nativeint
\end{ocamldoccode}
\index{nativeint@\verb`nativeint`}
\begin{ocamldocdescription}
The type of signed, platform-native integers (32 bits on 32-bit
processors, 64 bits on 64-bit processors).
See the "Nativeint"[\moduleref{Nativeint}] module.
\end{ocamldocdescription}
\begin{ocamldoccode}
type ('a, 'b, 'c, 'd, 'e, 'f) format6
\end{ocamldoccode}
\index{format4@\verb`format4`}
\begin{ocamldocdescription}
The type of format strings. "'a" is the type of the parameters of
the format, "'f" is the result type for the "printf"-style
functions, "'b" is the type of the first argument given to "%a" and
"%t" printing functions (see module "Printf"[\moduleref{Printf}]),
"'c" is the result type of these functions, and also the type of the
argument transmitted to the first argument of "kprintf"-style
functions, "'d" is the result type for the "scanf"-style functions
(see module "Scanf"[\moduleref{Scanf}]),
and "'e" is the type of the receiver function for the "scanf"-style
functions.
\end{ocamldocdescription}
\begin{ocamldoccode}
type 'a lazy_t
\end{ocamldoccode}
\index{lazyt@\verb`lazy_t`}
\begin{ocamldocdescription}
This type is used to implement the "Lazy"[\moduleref{Lazy}] module.
It should not be used directly.
\end{ocamldocdescription}
%\vspace{0.1cm}
\subsection*{Predefined exceptions}
%\vspace{0.1cm}
\begin{ocamldoccode}
exception Match_failure of (string * int * int)
\end{ocamldoccode}
\index{Matchfailure@\verb`Match_failure`}
\begin{ocamldocdescription}
Exception raised when none of the cases of a pattern-matching
apply. The arguments are the location of the "match" keyword
in the source code (file name, line number, column number).
\end{ocamldocdescription}
\begin{ocamldoccode}
exception Assert_failure of (string * int * int)
\end{ocamldoccode}
\index{Assertfailure@\verb`Assert_failure`}
\begin{ocamldocdescription}
Exception raised when an assertion fails. The arguments are
the location of the "assert" keyword in the source code
(file name, line number, column number).
\end{ocamldocdescription}
\begin{ocamldoccode}
exception Invalid_argument of string
\end{ocamldoccode}
\index{Invalidargument@\verb`Invalid_argument`}
\begin{ocamldocdescription}
Exception raised by library functions to signal that the given
arguments do not make sense. The string gives some information
to the programmer. As a general rule, this exception should not
be caught, it denotes a programming error and the code should be
modified not to trigger it.
\end{ocamldocdescription}
\begin{ocamldoccode}
exception Failure of string
\end{ocamldoccode}
\index{Failure@\verb`Failure`}
\begin{ocamldocdescription}
Exception raised by library functions to signal that they are
undefined on the given arguments. The string is meant to give some
information to the programmer; you must \emph{not} pattern match on
the string literal because it may change in future versions (use
\verb`Failure _` instead).
\end{ocamldocdescription}
\begin{ocamldoccode}
exception Not_found
\end{ocamldoccode}
\index{Notfound@\verb`Not_found`}
\begin{ocamldocdescription}
Exception raised by search functions when the desired object
could not be found.
\end{ocamldocdescription}
\begin{ocamldoccode}
exception Out_of_memory
\end{ocamldoccode}
\index{Outofmemory@\verb`Out_of_memory`}
\begin{ocamldocdescription}
Exception raised by the garbage collector
when there is insufficient memory to complete the computation.
\end{ocamldocdescription}
\begin{ocamldoccode}
exception Stack_overflow
\end{ocamldoccode}
\index{Stackoverflow@\verb`Stack_overflow`}
\begin{ocamldocdescription}
Exception raised by the bytecode interpreter when the evaluation
stack reaches its maximal size. This often indicates infinite
or excessively deep recursion in the user's program.
(Not fully implemented by the native-code compiler;
see section~\ref{s:compat-native-bytecode}.)
\end{ocamldocdescription}
\begin{ocamldoccode}
exception Sys_error of string
\end{ocamldoccode}
\index{Syserror@\verb`Sys_error`}
\begin{ocamldocdescription}
Exception raised by the input/output functions to report an
operating system error. The string is meant to give some
information to the programmer; you must \emph{not} pattern match on
the string literal because it may change in future versions (use
\verb`Sys_error _` instead).
\end{ocamldocdescription}
\begin{ocamldoccode}
exception End_of_file
\end{ocamldoccode}
\index{Endoffile@\verb`End_of_file`}
\begin{ocamldocdescription}
Exception raised by input functions to signal that the
end of file has been reached.
\end{ocamldocdescription}
\begin{ocamldoccode}
exception Division_by_zero
\end{ocamldoccode}
\index{Divisionbyzero@\verb`Division_by_zero`}
\begin{ocamldocdescription}
Exception raised by integer division and remainder operations
when their second argument is zero.
\end{ocamldocdescription}
\begin{ocamldoccode}
exception Sys_blocked_io
\end{ocamldoccode}
\index{Sysblockedio@\verb`Sys_blocked_io`}
\begin{ocamldocdescription}
A special case of "Sys_error" raised when no I/O is possible
on a non-blocking I/O channel.
\end{ocamldocdescription}
\begin{ocamldoccode}
exception Undefined_recursive_module of (string * int * int)
\end{ocamldoccode}
\index{Undefinedrecursivemodule@\verb`Undefined_recursive_module`}
\begin{ocamldocdescription}
Exception raised when an ill-founded recursive module definition
is evaluated. (See section~\ref{s-recursive-modules}.)
The arguments are the location of the definition in the source code
(file name, line number, column number).
\end{ocamldocdescription}

View File

@ -0,0 +1,58 @@
\chapter{The compiler front-end} \label{c:parsinglib}\cutname{parsing.html}
\pdfchapterfold{-1}{The compiler front-end}
This chapter describes the OCaml front-end, which declares the abstract
syntax tree used by the compiler, provides a way to parse, print
and pretty-print OCaml code, and ultimately allows to write abstract
syntax tree preprocessors invoked via the {\tt -ppx} flag (see chapters~\ref{c:camlc}
and~\ref{c:nativecomp}).
It is important to note that the exported front-end interface follows the evolution of the OCaml language and implementation, and thus does not provide {\bf any} backwards compatibility guarantees.
The front-end is a part of "compiler-libs" library.
Programs that use the "compiler-libs" library should be built as follows:
\begin{alltt}
ocamlfind ocamlc \var{other options} -package compiler-libs.common \var{other files}
ocamlfind ocamlopt \var{other options} -package compiler-libs.common \var{other files}
\end{alltt}
Use of the {\tt ocamlfind} utility is recommended. However, if this is not possible, an alternative method may be used:
\begin{alltt}
ocamlc \var{other options} -I +compiler-libs ocamlcommon.cma \var{other files}
ocamlopt \var{other options} -I +compiler-libs ocamlcommon.cmxa \var{other files}
\end{alltt}
For interactive use of the "compiler-libs" library, start "ocaml" and
type\\*"#load \"compiler-libs/ocamlcommon.cma\";;".
% Some of the files below are commented out as the documentation is too poor
% or they are thought to be nonessential.
\ifouthtml
\begin{links}
\item \ahref{libref/Ast\_helper.html}{Module \texttt{Ast_helper}: helper functions for AST construction}
\item \ahref{libref/Ast\_mapper.html}{Module \texttt{Ast_mapper}: -ppx rewriter interface}
\item \ahref{libref/Asttypes.html}{Module \texttt{Asttypes}: auxiliary types used by Parsetree}
% \item \ahref{libref/Lexer.html}{Module \texttt{Lexer}: OCaml syntax lexing}
\item \ahref{libref/Location.html}{Module \texttt{Location}: source code locations}
\item \ahref{libref/Longident.html}{Module \texttt{Longident}: long identifiers}
\item \ahref{libref/Parse.html}{Module \texttt{Parse}: OCaml syntax parsing}
\item \ahref{libref/Parsetree.html}{Module \texttt{Parsetree}: OCaml syntax tree}
\item \ahref{libref/Pprintast.html}{Module \texttt{Pprintast}: OCaml syntax printing}
% \item \ahref{libref/Printast.html}{Module \texttt{Printast}: AST printing}
\end{links}
\else
% Ast_helper is excluded from the PDF and text manuals.
% It is over 20 pages long and does not have doc-comments. It is expected
% that Ast_helper will be only useful in the HTML manual (to look up signatures).
% \input{Asthelper.tex}
\input{Astmapper.tex}
\input{Asttypes.tex}
% \input{Lexer.tex}
\input{Location.tex}
\input{Longident.tex}
\input{Parse.tex}
\input{Parsetree.tex}
\input{Pprintast.tex}
% \input{Printast.tex}
\fi

View File

@ -0,0 +1,36 @@
\chapter{The core library} \label{c:corelib}\cutname{core.html}
\pdfchapterfold{-1}{The core library}
This chapter describes the OCaml core library, which is
composed of declarations for built-in types and exceptions, plus
the module "Pervasives" that provides basic operations on these
built-in types. The "Pervasives" module is special in two
ways:
\begin{itemize}
\item It is automatically linked with the user's object code files by
the "ocamlc" command (chapter~\ref{c:camlc}).
\item It is automatically ``opened'' when a compilation starts, or
when the toplevel system is launched. Hence, it is possible to use
unqualified identifiers to refer to the functions provided by the
"Pervasives" module, without adding a "open Pervasives" directive.
\end{itemize}
\section*{Conventions}
The declarations of the built-in types and the components of module
"Pervasives" are printed one by one in typewriter font, followed by a
short comment. All library modules and the components they provide are
indexed at the end of this report.
\input{builtin.tex}
\ifouthtml
\section{Module {\tt Pervasives}: the initially opened module}
\begin{links}
\item \ahref{libref/Pervasives.html}{Module \texttt{Pervasives}: the initially opened module}
\end{links}
\else
\input{Pervasives.tex}
\fi

View File

@ -0,0 +1,168 @@
\chapter{The bigarray library}
\pdfchapterfold{-1}{The bigarray library}
%HEVEA\cutname{libbigarray.html}
The "bigarray" library implements large, multi-dimensional, numerical
arrays. These arrays are called ``big arrays'' to distinguish them
from the standard OCaml arrays described in
\ifouthtml
\ahref{libref/Array.html}{Module \texttt{Array}}.
\else
section~\ref{Array}.
\fi
The main differences between ``big arrays'' and standard OCaml arrays
are as follows:
\begin{itemize}
\item Big arrays are not limited in size, unlike OCaml arrays
("float array" are limited to 2097151 elements on a 32-bit platform,
other "array" types to 4194303 elements).
\item Big arrays are multi-dimensional. Any number of dimensions
between 1 and 16 is supported. In contrast, OCaml arrays are
mono-dimensional and require encoding multi-dimensional arrays as
arrays of arrays.
\item Big arrays can only contain integers and floating-point
numbers, while OCaml arrays can contain arbitrary OCaml data types.
However, big arrays provide more space-efficient storage of integer
and floating-point elements, in particular because they support
``small'' types such as single-precision floats and 8 and 16-bit
integers, in addition to the standard OCaml types of double-precision
floats and 32 and 64-bit integers.
\item The memory layout of big arrays is entirely compatible with that
of arrays in C and Fortran, allowing large arrays to be passed back
and forth between OCaml code and C / Fortran code with no data copying
at all.
\item Big arrays support interesting high-level operations that normal
arrays do not provide efficiently, such as extracting sub-arrays and
``slicing'' a multi-dimensional array along certain dimensions, all
without any copying.
\end{itemize}
%
Programs that use the "bigarray" library must be linked as follows:
\begin{alltt}
ocamlc \var{other options} bigarray.cma \var{other files}
ocamlopt \var{other options} bigarray.cmxa \var{other files}
\end{alltt}
For interactive use of the "bigarray" library, do:
\begin{alltt}
ocamlmktop -o mytop bigarray.cma
./mytop
\end{alltt}
or (if dynamic linking of C libraries is supported on your platform),
start "ocaml" and type "#load \"bigarray.cma\";;".
\ifouthtml
\section{Module {\tt Bigarray}: large, multi-dimensional, numerical arrays}
\begin{links}
\item \ahref{libref/Bigarray.html}{Module \texttt{Bigarray}}
\end{links}
\else
\input{Bigarray.tex}
\fi
\section{Big arrays in the OCaml-C interface}
C stub code that interface C or Fortran code with OCaml code, as
described in chapter~\ref{c:intf-c}, can exploit big arrays as
follows.
\subsection{Include file}
The include file "<caml/bigarray.h>" must be included in the C stub
file. It declares the functions, constants and macros discussed
below.
\subsection{Accessing an OCaml bigarray from C or Fortran}
If \var{v} is a OCaml "value" representing a big array, the expression
"Caml_ba_data_val("\var{v}")" returns a pointer to the data part of the array.
This pointer is of type "void *" and can be cast to the appropriate C
type for the array (e.g. "double []", "char [][10]", etc).
Various characteristics of the OCaml big array can be consulted from C
as follows:
\begin{tableau}{|l|l|}{C expression}{Returns}
\entree{"Caml_ba_array_val("\var{v}")->num_dims"}{number of dimensions}
\entree{"Caml_ba_array_val("\var{v}")->dim["\var{i}"]"}{\var{i}-th dimension}
\entree{"Caml_ba_array_val("\var{v}")->flags & BIGARRAY_KIND_MASK"}{kind of array elements}
\end{tableau}
The kind of array elements is one of the following constants:
\begin{tableau}{|l|l|}{Constant}{Element kind}
\entree{"CAML_BA_FLOAT32"}{32-bit single-precision floats}
\entree{"CAML_BA_FLOAT64"}{64-bit double-precision floats}
\entree{"CAML_BA_SINT8"}{8-bit signed integers}
\entree{"CAML_BA_UINT8"}{8-bit unsigned integers}
\entree{"CAML_BA_SINT16"}{16-bit signed integers}
\entree{"CAML_BA_UINT16"}{16-bit unsigned integers}
\entree{"CAML_BA_INT32"}{32-bit signed integers}
\entree{"CAML_BA_INT64"}{64-bit signed integers}
\entree{"CAML_BA_CAML_INT"}{31- or 63-bit signed integers}
\entree{"CAML_BA_NATIVE_INT"}{32- or 64-bit (platform-native) integers}
\end{tableau}
%
The following example shows the passing of a two-dimensional big array
to a C function and a Fortran function.
\begin{verbatim}
extern void my_c_function(double * data, int dimx, int dimy);
extern void my_fortran_function_(double * data, int * dimx, int * dimy);
value caml_stub(value bigarray)
{
int dimx = Caml_ba_array_val(bigarray)->dim[0];
int dimy = Caml_ba_array_val(bigarray)->dim[1];
/* C passes scalar parameters by value */
my_c_function(Caml_ba_data_val(bigarray), dimx, dimy);
/* Fortran passes all parameters by reference */
my_fortran_function_(Caml_ba_data_val(bigarray), &dimx, &dimy);
return Val_unit;
}
\end{verbatim}
\subsection{Wrapping a C or Fortran array as an OCaml big array}
A pointer \var{p} to an already-allocated C or Fortran array can be
wrapped and returned to OCaml as a big array using the "caml_ba_alloc"
or "caml_ba_alloc_dims" functions.
\begin{itemize}
\item
"caml_ba_alloc("\var{kind} "|" \var{layout}, \var{numdims}, \var{p}, \var{dims}")"
Return an OCaml big array wrapping the data pointed to by \var{p}.
\var{kind} is the kind of array elements (one of the "CAML_BA_"
kind constants above). \var{layout} is "CAML_BA_C_LAYOUT" for an
array with C layout and "CAML_BA_FORTRAN_LAYOUT" for an array with
Fortran layout. \var{numdims} is the number of dimensions in the
array. \var{dims} is an array of \var{numdims} long integers, giving
the sizes of the array in each dimension.
\item
"caml_ba_alloc_dims("\var{kind} "|" \var{layout}, \var{numdims},
\var{p}, "(long) "\nth{dim}{1}, "(long) "\nth{dim}{2}, \ldots, "(long) "\nth{dim}{numdims}")"
Same as "caml_ba_alloc", but the sizes of the array in each dimension
are listed as extra arguments in the function call, rather than being
passed as an array.
\end{itemize}
%
The following example illustrates how statically-allocated C and
Fortran arrays can be made available to OCaml.
\begin{verbatim}
extern long my_c_array[100][200];
extern float my_fortran_array_[300][400];
value caml_get_c_array(value unit)
{
long dims[2];
dims[0] = 100; dims[1] = 200;
return caml_ba_alloc(CAML_BA_NATIVE_INT | CAML_BA_C_LAYOUT,
2, my_c_array, dims);
}
value caml_get_fortran_array(value unit)
{
return caml_ba_alloc_dims(CAML_BA_FLOAT32 | CAML_BA_FORTRAN_LAYOUT,
2, my_fortran_array_, 300L, 400L);
}
\end{verbatim}

View File

@ -0,0 +1,29 @@
\chapter{The dynlink library: dynamic loading and linking of object files}
\pdfchapterfold{-1}{The dynlink library: dynamic loading and linking of object files}
%HEVEA\cutname{libdynlink.html}
The "dynlink" library supports type-safe dynamic loading and linking
of bytecode object files (".cmo" and ".cma" files) in a running
bytecode program, or of native plugins (usually ".cmxs" files) in a
running native program. Type safety is ensured by limiting the set of
modules from the running program that the loaded object file can
access, and checking that the running program and the loaded object
file have been compiled against the same interfaces for these modules.
In native code, there are also some compatibility checks on the
implementations (to avoid errors with cross-module optimizations); it
might be useful to hide ".cmx" files when building native plugins so
that they remain independent of the implementation of modules in the
main program.
Programs that use the "dynlink" library simply need to link
"dynlink.cma" or "dynlink.cmxa" with their object files and other libraries.
\ifouthtml
\begin{links}
\item \ahref{libref/Dynlink.html}{Module \texttt{Dynlink}: dynamic loading of bytecode object files}
\end{links}
\else
\input{Dynlink.tex}
\fi

View File

@ -0,0 +1,100 @@
\chapter{The graphics library}
\pdfchapterfold{-1}{The graphics library}
%HEVEA\cutname{libgraph.html}
The "graphics" library provides a set of portable drawing primitives.
Drawing takes place
in a separate window that is created when "Graphics.open_graph" is called.
\begin{unix}
This library is implemented under the X11 windows system.
Programs that use the "graphics" library must be linked as follows:
\begin{alltt}
ocamlc \var{other options} graphics.cma \var{other files}
\end{alltt}
For interactive use of the "graphics" library, do:
\begin{alltt}
ocamlmktop -o mytop graphics.cma
./mytop
\end{alltt}
or (if dynamic linking of C libraries is supported on your platform),
start "ocaml" and type "#load \"graphics.cma\";;".
Here are the graphics mode specifications supported by
"Graphics.open_graph" on
the X11 implementation of this library:
the argument to "Graphics.open_graph" has the format
"\""{\it display-name} {\it geometry\/}"\"",
where {\it display-name} is the name of the X-windows display to
connect to, and {\it geometry} is a standard X-windows geometry
specification. The two components are separated by a space. Either can
be omitted, or both. Examples:
\begin{options}
\item["Graphics.open_graph \"foo:0\""]
connects to the display "foo:0" and creates a window with the default geometry
\item["Graphics.open_graph \"foo:0 300x100+50-0\""]
connects to the display "foo:0" and creates a window 300 pixels wide
by 100 pixels tall, at location $(50,0)$
\item["Graphics.open_graph \" 300x100+50-0\""]
connects to the default display and creates a window 300 pixels wide
by 100 pixels tall, at location $(50,0)$
\item["Graphics.open_graph \"\""]
connects to the default display and creates a window with the default
geometry.
\end{options}
\end{unix}
\begin{windows}
This library is available both for standalone compiled programs and
under the toplevel application "ocamlwin.exe". For the latter, this
library must be loaded in-core by typing
\begin{verbatim}
#load "graphics.cma";;
\end{verbatim}
\end{windows}
The screen coordinates are interpreted as shown in the figure below.
Notice that the coordinate system used is the same as in mathematics:
$y$ increases from the bottom of the screen to the top of the screen,
and angles are measured counterclockwise (in degrees).
Drawing is clipped to the screen.
%
\begin{latexonly}
\begin{center}
\setlength{\unitlength}{0.5mm}
\begin{picture}(130,100)(-10,-10)
\thicklines
\put(-10,0){\vector(1,0){130}}
\put(125,0){\makebox(0,0)[l]{$x$}}
\put(0,-10){\vector(0,1){100}}
\put(0,95){\makebox(0,0){$y$}}
\thinlines
\put(100,80){\line(-1,0){105}}
\put(100,80){\line(0,-1){85}}
\put(95,75){\makebox(0,0)[tr]{Screen}}
\put(100,-10){\makebox(0,0){\tt size\_x()}}
\put(-10,80){\makebox(0,0)[r]{\tt size\_y()}}
\put(30,40){\makebox(4,4){\rule{2mm}{2mm}}}
\put(36,40){pixel at $(x,y)$}
\put(30,40){\line(-1,0){35}}
\put(30,-10){\makebox(0,0){$x$}}
\put(30,40){\line(0,-1){45}}
\put(-10,40){\makebox(0,0)[r]{$y$}}
\end{picture}
\end{center}
\end{latexonly}
\begin{htmlonly}
\begin{center}
\imgsrc{libgraph.gif}
\end{center}
\end{htmlonly}
%
\ifouthtml
\begin{links}
\item \ahref{libref/Graphics.html}{Module \texttt{Graphics}: machine-independent graphics primitives}
\end{links}
\else
\input{Graphics.tex}
\fi

View File

@ -0,0 +1,29 @@
#FIG 3.2
Landscape
Center
Inches
Letter
100.00
Single
-2
1200 2
2 1 0 1 0 7 0 0 -1 0.000 0 0 7 1 0 2
1 1 1.00 60.00 120.00
1050 3375 4575 3375
2 1 0 1 0 7 0 0 -1 0.000 0 0 -1 1 0 2
1 1 1.00 60.00 120.00
1200 3525 1200 825
2 1 0 1 0 7 0 0 -1 0.000 0 0 7 0 0 3
1125 1200 3750 1200 3750 3450
2 1 0 1 0 7 0 0 -1 0.000 0 0 -1 0 0 3
1125 2400 2475 2400 2475 3450
2 2 0 1 0 0 0 0 20 0.000 0 0 7 0 0 5
2475 2400 2550 2400 2550 2325 2475 2325 2475 2400
4 0 0 0 0 0 12 0.0000 4 135 525 2325 1500 Screen\001
4 0 0 0 0 0 12 0.0000 4 180 990 2175 2250 point at (x,y)\001
4 0 0 0 0 0 12 0.0000 4 90 90 2400 3600 x\001
4 0 0 0 0 0 12 0.0000 4 135 90 975 2475 y\001
4 0 0 0 0 0 12 0.0000 4 180 450 1050 750 y axis\001
4 0 0 0 0 14 12 0.0000 4 180 840 225 1200 size_y()\001
4 0 0 0 0 14 12 0.0000 4 165 840 3375 3600 size_x()\001
4 0 0 0 0 0 12 0.0000 4 135 450 4650 3375 x axis\001

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

View File

@ -0,0 +1,96 @@
\chapter{The LablTk library: Tcl/Tk GUI interface}
\pdfchapterfold{-1}{The LablTk library: Tcl/Tk GUI interface}
%HEVEA\cutname{liblabltk.html}
The "labltk" library provides access to the Tcl/Tk GUI from
OCaml programs. This interface is generated in an automated way, and
you should refer to Tcl/Tk books and man pages for detailed
information on the behavior of the numerous functions. We also suggest
to use "ocamlbrowser" to see the types of the various functions, that
are the best documentation for the library itself.
\smallskip\noindent
Programs that use the "labltk" library must be linked as follows:
\begin{alltt}
ocamlc \var{other options} -I +labltk labltk.cma \var{other files}
ocamlopt \var{other options} -I +labltk labltk.cmxa \var{other files}
\end{alltt}
\begin{unix}
The "labltk" library is available for any system with Tcl/Tk installed,
starting from Tcl/Tk 8.0 up to Tcl/Tk 8.6. Beware that some beta
versions may have compatibility problems.
If the library was not compiled correctly, try to run again the
"configure" script with the option "-tkdefs" \var{switches},
where \var{switches} is a list of C-style inclusion paths leading to
the right "tcl.h" and "tk.h", for instance
"\"-I/usr/local/include/tcl8.4 -I/usr/local/include/tk8.4\"".
A script is installed, to make easier the use of the "labltk"
library as toplevel.
\begin{options}
\item["labltk"]
This is a toplevel including the "labltk" library, and the path is
already set as to allow the use of the various modules. It also
includes code for the Unix and Str libraries. You can use it
in place of "ocaml".
\end{options}
\end{unix}
\begin{windows}
The "labltk" library has been precompiled for use with Tcl/Tk 8.5.
You must first have it installed on your system.
It can be downloaded from \\
"http://www.activestate.com/products/ActiveTcl/".
After installing it, you must put the dynamically loaded libraries
"tcl85.dll" and "tk85.dll" (from the "bin" directory of the Tcl
installation) in a directory included in you path.
No toplevel is available, but you can load the library from the
standard toplevel with the following commands.
\begin{quote}
\begin{verbatim}
# #directory "+labltk";;
# #load "labltk.cma";;
\end{verbatim}
\end{quote}
You can also load it directly from the command line.
\begin{quote}
\begin{verbatim}
C:\ocaml\bin> ocaml -I +labltk labltk.cma
\end{verbatim}
\end{quote}
\end{windows}
The "labltk" library is composed of a large number of modules.
\begin{quote}
\begin{verbatim}
Bell Imagebitmap Place
Button Imagephoto Radiobutton
Canvas Label Scale
Checkbutton Listbox Scrollbar
Clipboard Menu Selection
Dialog Menubutton Text
Entry Message Tk
Focus Option Tkwait
Frame Optionmenu Toplevel
Grab Pack Winfo
Grid Palette Wm
\end{verbatim}
\end{quote}
Giving a detailed account of each of these module would be impractical
here. We will just present some of the basic functions in the module
"Tk". Note that for most other modules information can be found in the
Tcl "man" page of their name.
\ifouthtml
\begin{links}
\item \ahref{libref/Tk.html}{The \texttt{Tk} library: Basic functions and types for LablTk}
\end{links}
\else
\input{Tk.tex}
\fi

View File

@ -0,0 +1,39 @@
\chapter{The num library: arbitrary-precision rational arithmetic}
\pdfchapterfold{-3}{The num library: arbitrary-precision integer and rational arithmetic}
%HEVEA\cutname{libnum.html}
The "num" library implements integer arithmetic and rational
arithmetic in arbitrary precision.
More documentation on the functions provided in this library can be found
in {\em The CAML Numbers Reference Manual\/} by
Valérie Ménissier-Morain, technical report 141, INRIA, july 1992
(available electronically,
\url{http://hal.inria.fr/docs/00/07/00/27/PDF/RT-0141.pdf}).
Programs that use the "num" library must be linked as follows:
\begin{alltt}
ocamlc \var{other options} nums.cma \var{other files}
ocamlopt \var{other options} nums.cmxa \var{other files}
\end{alltt}
For interactive use of the "nums" library, do:
\begin{alltt}
ocamlmktop -o mytop nums.cma
./mytop
\end{alltt}
or (if dynamic linking of C libraries is supported on your platform),
start "ocaml" and type "#load \"nums.cma\";;".
\ifouthtml
\begin{links}
\item \ahref{libref/Num.html}{Module \texttt{Num}: operation on arbitrary-precision numbers}
\item \ahref{libref/Big\_int.html}{Module \texttt{Big\_int}: operations on arbitrary-precision integers}
\item \ahref{libref/Arith\_status.html}{Module \texttt{Arith\_status}: flags that control rational arithmetic}
\end{links}
\else
\input{Num.tex}
\input{Bigint.tex}
\input{Arithstatus.tex}
\fi

View File

@ -0,0 +1,32 @@
\chapter{The str library: regular expressions and string processing}
\pdfchapterfold{-1}{The str library: regular expressions and string processing}
%HEVEA\cutname{libstr.html}
The "str" library provides high-level string processing functions,
some based on regular expressions. It is intended to support the kind
of file processing that is usually performed with scripting languages
such as "awk", "perl" or "sed".
Programs that use the "str" library must be linked as follows:
\begin{alltt}
ocamlc \var{other options} str.cma \var{other files}
ocamlopt \var{other options} str.cmxa \var{other files}
\end{alltt}
For interactive use of the "str" library, do:
\begin{alltt}
ocamlmktop -o mytop str.cma
./mytop
\end{alltt}
or (if dynamic linking of C libraries is supported on your platform),
start "ocaml" and type "#load \"str.cma\";;".
\ifouthtml
\begin{links}
\item \ahref{libref/Str.html}{Module \texttt{Str}: regular expressions and string processing}
\end{links}
\else
\input{Str.tex}
\fi

View File

@ -0,0 +1,60 @@
\chapter{The threads library}
\label{c:threads}\cutname{threads.html}
\pdfchapterfold{-5}{The threads library}
%HEVEA\cutname{libthreads.html}
The "threads" library allows concurrent programming in OCaml.
It provides multiple threads of control (also called lightweight
processes) that execute concurrently in the same memory space. Threads
communicate by in-place modification of shared data structures, or by
sending and receiving data on communication channels.
The "threads" library is implemented by time-sharing on a single
processor. It will not take advantage of multi-processor machines.
Using this library will therefore never make programs run
faster. However, many programs are easier to write when structured as
several communicating processes.
Two implementations of the "threads" library are available, depending
on the capabilities of the operating system:
\begin{itemize}
\item System threads. This implementation builds on the OS-provided threads
facilities: POSIX 1003.1c threads for Unix, and Win32 threads for
Windows. When available, system threads support both bytecode and
native-code programs.
\item VM-level threads. This implementation performs time-sharing and
context switching at the level of the OCaml virtual machine (bytecode
interpreter). It is available on Unix systems, and supports only
bytecode programs. It cannot be used with native-code programs.
\end{itemize}
Programs that use system threads must be linked as follows:
\begin{alltt}
ocamlc -thread \var{other options} unix.cma threads.cma \var{other files}
ocamlopt -thread \var{other options} unix.cmxa threads.cmxa \var{other files}
\end{alltt}
Compilation units that use the "threads" library must also be compiled with
the "-thread" option (see chapter~\ref{c:camlc}).
Programs that use VM-level threads must be compiled with the "-vmthread"
option to "ocamlc" (see chapter~\ref{c:camlc}), and be linked as follows:
\begin{alltt}
ocamlc -vmthread \var{other options} threads.cma \var{other files}
\end{alltt}
Compilation units that use "threads" library must also be compiled with
the "-vmthread" option (see chapter~\ref{c:camlc}).
\ifouthtml
\begin{links}
\item \ahref{libref/Thread.html}{Module \texttt{Thread}: lightweight threads}
\item \ahref{libref/Mutex.html}{Module \texttt{Mutex}: locks for mutual exclusion}
\item \ahref{libref/Condition.html}{Module \texttt{Condition}: condition variables to synchronize between threads}
\item \ahref{libref/Event.html}{Module \texttt{Event}: first-class synchronous communication}
\item \ahref{libref/ThreadUnix.html}{Module \texttt{ThreadUnix}: thread-compatible system calls}
\end{links}
\else
\input{Thread.tex}
\input{Mutex.tex}
\input{Condition.tex}
\input{Event.tex}
\input{ThreadUnix.tex}
\fi

View File

@ -0,0 +1,92 @@
\chapter{The unix library: Unix system calls}
\pdfchapterfold{-1}{The unix library: Unix system calls}
%HEVEA\cutname{libunix.html}
The "unix" library makes many Unix
system calls and system-related library functions available to
OCaml programs. This chapter describes briefly the functions
provided. Refer to sections 2~and~3 of the Unix manual for more
details on the behavior of these functions.
Not all functions are provided by all Unix variants. If some functions
are not available, they will raise "Invalid_arg" when called.
Programs that use the "unix" library must be linked as follows:
\begin{alltt}
ocamlc \var{other options} unix.cma \var{other files}
ocamlopt \var{other options} unix.cmxa \var{other files}
\end{alltt}
For interactive use of the "unix" library, do:
\begin{alltt}
ocamlmktop -o mytop unix.cma
./mytop
\end{alltt}
or (if dynamic linking of C libraries is supported on your platform),
start "ocaml" and type "#load \"unix.cma\";;".
\begin{windows}
A fairly complete emulation of the Unix system calls is provided in
the Windows version of OCaml. The end of this chapter gives
more information on the functions that are not supported under Windows.
\end{windows}
\ifouthtml
\begin{links}
\item \ahref{libref/Unix.html}{Module \texttt{Unix}: Unix system calls}
\item \ahref{libref/UnixLabels.html}{Module \texttt{UnixLabels}: Labeled
Unix system calls}
\end{links}
\else
\input{Unix.tex}
\section{Module \texttt{UnixLabels}: labelized version of the interface}
\label{UnixLabels}
\index{UnixLabels (module)@\verb~UnixLabels~ (module)}%
\pdfsection{Module UnixLabels: labelized version of the interface}
This module is identical to "Unix"~(\ref{Unix}), and only differs by
the addition of labels. You may see these labels directly by looking
at "unixLabels.mli", or by using the "ocamlbrowser" tool.
\fi
\newpage
\begin{windows}
The Cygwin port of OCaml fully implements all functions from
the Unix module. The native Win32 ports implement a subset of them.
Below is a list of the functions that are not implemented, or only
partially implemented, by the Win32 ports. Functions not mentioned are
fully implemented and behave as described previously in this chapter.
\begin{tableau}{|l|p{8cm}|}{Functions}{Comment}
\entree{"fork"}{not implemented, use "create_process" or threads}
\entree{"wait"}{not implemented, use "waitpid"}
\entree{"waitpid"}{can only wait for a given PID, not any child process}
\entree{"getppid"}{not implemented (meaningless under Windows)}
\entree{"nice"}{not implemented}
\entree{"truncate", "ftruncate"}{not implemented}
\entree{"link", "symlink", "readlink"}{not implemented (no links under
Windows)}
\entree{"access"}{execute permission "X_OK" cannot be tested,
it just tests for read permission instead}
\entree{"fchmod"}{not implemented}
\entree{"chown", "fchown"}{not implemented (make no sense on a DOS
file system)}
\entree{"umask"}{not implemented}
\entree{"mkfifo"}{not implemented}
\entree{"kill", "pause"}{not implemented (no inter-process signals in Windows)}
\entree{"alarm"}{not implemented}
\entree{"times"}{partially implemented, will not report timings for child
processes}
\entree{"getitimer", "setitimer"}{not implemented}
\entree{"getuid", "getgid"}{always return 1}
\entree{"getgid", "getegid", "getgroups"}{not implemented}
\entree{"setuid", "setgid"}{not implemented}
\entree{"getpwnam", "getpwuid"}{always raise "Not_found"}
\entree{"getgrnam", "getgrgid"}{always raise "Not_found"}
\entree{type "socket_domain"}{the domains "PF_UNIX" and "PF_INET6"
are not supported; "PF_INET" is fully supported}
\entree{"establish_server"}{not implemented; use threads}
\entree{terminal functions ("tc*")}{not implemented}
\end{tableau}
\end{windows}

View File

@ -0,0 +1,175 @@
\chapter{The standard library} \label{c:stdlib}\cutname{stdlib.html}
\pdfchapterfold{-32}{The standard library}
This chapter describes the functions provided by the OCaml
standard library. The modules from the standard library are
automatically linked with the user's object code files by the "ocamlc"
command. Hence, these modules can be used in standalone programs without
having to add any ".cmo" file on the command line for the linking
phase. Similarly, in interactive use, these globals can be used in
toplevel phrases without having to load any ".cmo" file in memory.
Unlike the "Pervasives" module from the core library, the modules from the
standard library are not automatically ``opened'' when a compilation
starts, or when the toplevel system is launched. Hence it is necessary
to use qualified identifiers to refer to the functions provided by these
modules, or to add "open" directives.
\label{stdlib:top}
\section*{Conventions}
For easy reference, the modules are listed below in alphabetical order
of module names.
For each module, the declarations from its signature are printed
one by one in typewriter font, followed by a short comment.
All modules and the identifiers they export are indexed at the end of
this report.
\begin{latexonly}
\section*{Overview}
Here is a short listing, by theme, of the standard library modules.
\subsubsection*{Data structures:}
\begin{tabular}{lll}
"Char" & p.~\pageref{Char} & character operations \\
"String" & p.~\pageref{String} & string operations \\
"Bytes" & p.~\pageref{Bytes} & operations on byte sequences\\
"Array" & p.~\pageref{Array} & array operations \\
"List" & p.~\pageref{List} & list operations \\
"StdLabels" &p.~\pageref{StdLabels} & labelized versions of
the above 4 modules \\
"Sort" & p.~\pageref{Sort} & sorting and merging lists \\
"Hashtbl" & p.~\pageref{Hashtbl} & hash tables and hash functions \\
"Random" & p.~\pageref{Random} & pseudo-random number generator \\
"Set" & p.~\pageref{Set} & sets over ordered types \\
"Map" & p.~\pageref{Map} & association tables over ordered types \\
"MoreLabels" &p.~\pageref{MoreLabels} & labelized versions of
"Hashtbl", "Set", and "Map" \\
"Oo" & p.~\pageref{Oo} & useful functions on objects \\
"Stack" & p.~\pageref{Stack} & last-in first-out stacks \\
"Queue" & p.~\pageref{Queue} & first-in first-out queues \\
"Buffer" & p.~\pageref{Buffer} & buffers that grow on demand \\
"Lazy" & p.~\pageref{Lazy} & delayed evaluation \\
"Weak" & p.~\pageref{Weak} & references that don't prevent objects
from being garbage-collected
\end{tabular}
\subsubsection*{Arithmetic:}
\begin{tabular}{lll}
"Complex" & p.~\pageref{Complex} & Complex numbers \\
"Int32" & p.~\pageref{Int32} & operations on 32-bit integers \\
"Int64" & p.~\pageref{Int64} & operations on 64-bit integers \\
"Nativeint" & p.~\pageref{Nativeint} & operations on platform-native
integers
\end{tabular}
\subsubsection{Input/output:}
\begin{tabular}{lll}
"Format" & p.~\pageref{Format} & pretty printing with automatic
indentation and line breaking \\
"Marshal" & p.~\pageref{Marshal} & marshaling of data structures \\
"Printf" & p.~\pageref{Printf} & formatting printing functions \\
"Scanf" & p.~\pageref{Scanf} & formatted input functions \\
"Digest" & p.~\pageref{Digest} & MD5 message digest \\
\end{tabular}
\subsubsection{Parsing:}
\begin{tabular}{lll}
"Genlex" & p.~\pageref{Genlex} & a generic lexer over streams \\
"Lexing" & p.~\pageref{Lexing} & the run-time library for lexers generated by "ocamllex" \\
"Parsing" & p.~\pageref{Parsing} & the run-time library for parsers generated by "ocamlyacc" \\
"Stream" & p.~\pageref{Stream} & basic functions over streams \\
\end{tabular}
\subsubsection{System interface:}
\begin{tabular}{lll}
"Arg" & p.~\pageref{Arg} & parsing of command line arguments \\
"Callback" & p.~\pageref{Callback} & registering OCaml functions to
be called from C \\
"Filename" & p.~\pageref{Filename} & operations on file names \\
"Gc" & p.~\pageref{Gc} & memory management control and statistics \\
"Printexc" & p.~\pageref{Printexc} & a catch-all exception handler \\
"Sys" & p.~\pageref{Sys} & system interface \\
\end{tabular}
\end{latexonly}
\ifouthtml
\begin{links}
\item \ahref{libref/Arg.html}{Module \texttt{Arg}: parsing of command line arguments}
\item \ahref{libref/Array.html}{Module \texttt{Array}: array operations}
\item \ahref{libref/ArrayLabels.html}{Module \texttt{ArrayLabels}: array operations (with labels)}
\item \ahref{libref/Buffer.html}{Module \texttt{Buffer}: extensible buffers}
\item \ahref{libref/Bytes.html}{Module \texttt{Bytes}: byte sequences}
\item \ahref{libref/Callback.html}{Module \texttt{Callback}: registering OCaml values with the C runtime}
\item \ahref{libref/Char.html}{Module \texttt{Char}: character operations}
\item \ahref{libref/Complex.html}{Module \texttt{Complex}: Complex numbers}
\item \ahref{libref/Digest.html}{Module \texttt{Digest}: MD5 message digest}
\item \ahref{libref/Filename.html}{Module \texttt{Filename}: operations on file names}
\item \ahref{libref/Format.html}{Module \texttt{Format}: pretty printing}
\item \ahref{libref/Gc.html}{Module \texttt{Gc}: memory management control and statistics; finalized values}
\item \ahref{libref/Genlex.html}{Module \texttt{Genlex}: a generic lexical analyzer}
\item \ahref{libref/Hashtbl.html}{Module \texttt{Hashtbl}: hash tables and hash functions}
\item \ahref{libref/Int32.html}{Module \texttt{Int32}: 32-bit integers}
\item \ahref{libref/Int64.html}{Module \texttt{Int64}: 64-bit integers}
\item \ahref{libref/Lazy.html}{Module \texttt{Lazy}: deferred computations}
\item \ahref{libref/Lexing.html}{Module \texttt{Lexing}: the run-time library for lexers generated by \texttt{ocamllex}}
\item \ahref{libref/List.html}{Module \texttt{List}: list operations}
\item \ahref{libref/ListLabels.html}{Module \texttt{ListLabels}: list operations (with labels)}
\item \ahref{libref/Map.html}{Module \texttt{Map}: association tables over ordered types}
\item \ahref{libref/Marshal.html}{Module \texttt{Marshal}: marshaling of data structures}
\item \ahref{libref/MoreLabels.html}{Module \texttt{MoreLabels}: Include modules \texttt{Hashtbl}, \texttt{Map} and \texttt{Set} with labels}
\item \ahref{libref/Nativeint.html}{Module \texttt{Nativeint}: processor-native integers}
\item \ahref{libref/Oo.html}{Module \texttt{Oo}: object-oriented extension}
\item \ahref{libref/Parsing.html}{Module \texttt{Parsing}: the run-time library for parsers generated by \texttt{ocamlyacc}}
\item \ahref{libref/Printexc.html}{Module \texttt{Printexc}: facilities for printing exceptions}
\item \ahref{libref/Printf.html}{Module \texttt{Printf}: formatting printing functions}
\item \ahref{libref/Queue.html}{Module \texttt{Queue}: first-in first-out queues}
\item \ahref{libref/Random.html}{Module \texttt{Random}: pseudo-random number generator (PRNG)}
\item \ahref{libref/Scanf.html}{Module \texttt{Scanf}: formatted input functions}
\item \ahref{libref/Set.html}{Module \texttt{Set}: sets over ordered types}
\item \ahref{libref/Sort.html}{Module \texttt{Sort}: sorting and merging lists}
\item \ahref{libref/Stack.html}{Module \texttt{Stack}: last-in first-out stacks}
\item \ahref{libref/StdLabels.html}{Module \texttt{StdLabels}: Include modules \texttt{Array}, \texttt{List} and \texttt{String} with labels}
\item \ahref{libref/Stream.html}{Module \texttt{Stream}: streams and parsers}
\item \ahref{libref/String.html}{Module \texttt{String}: string operations}
\item \ahref{libref/StringLabels.html}{Module \texttt{StringLabels}: string operations (with labels)}
\item \ahref{libref/Sys.html}{Module \texttt{Sys}: system interface}
\item \ahref{libref/Weak.html}{Module \texttt{Weak}: arrays of weak pointers}
\end{links}
\else
\input{Arg.tex}
\input{Array.tex}
\input{Buffer.tex}
\input{Bytes.tex}
\input{Callback.tex}
\input{Char.tex}
\input{Complex.tex}
\input{Digest.tex}
\input{Filename.tex}
\input{Format.tex}
\input{Gc.tex}
\input{Genlex.tex}
\input{Hashtbl.tex}
\input{Int32.tex}
\input{Int64.tex}
\input{Lazy.tex}
\input{Lexing.tex}
\input{List.tex}
\input{Map.tex}
\input{Marshal.tex}
\input{MoreLabels.tex}
\input{Nativeint.tex}
\input{Oo.tex}
\input{Parsing.tex}
\input{Printexc.tex}
\input{Printf.tex}
\input{Queue.tex}
\input{Random.tex}
\input{Scanf.tex}
\input{Set.tex}
\input{Sort.tex}
\input{Stack.tex}
\input{StdLabels.tex}
\input{Stream.tex}
\input{String.tex}
\input{Sys.tex}
\input{Weak.tex}
\fi

View File

@ -0,0 +1,192 @@
(* $Id$ *)
(** Basic functions and types for LablTk *)
open Widget
(** {6 Initialization and termination} *)
val openTk : ?display:string -> ?clas:string -> unit -> toplevel widget
(** Initialize LablTk and open a toplevel window.
[display] is described according to the X11 conventions.
[clas] is used for the X11 resource mechanism. *)
val mainLoop : unit -> unit
(** Start the main event loop *)
val closeTk : unit -> unit
(** Quit the main loop and close all open windows. *)
val destroy : 'a Widget.widget -> unit
(** Destroy an individual widget. *)
(** {6 Application wide commands} *)
val update : unit -> unit
(** Synchronize display with internal state. *)
val appname_get : unit -> string
val appname_set : string -> unit
(** Get or set the application name. *)
(** {6 Dimensions} *)
type units = [`Pix of int | `Cm of float | `In of float | `Mm of float | `Pt of float]
val pixels : units -> int
(** Converts various on-screen units to pixels,
respective to the default display. Available units are
pixels, centimeters, inches, millimeters and points *)
(** {6 Widget layout commands} *)
type anchor = [`Center|`E|`N|`Ne|`Nw|`S|`Se|`Sw|`W]
type fillMode = [`Both|`None|`X|`Y]
type side = [`Bottom|`Left|`Right|`Top]
val pack :
?after:'a Widget.widget ->
?anchor:anchor ->
?before:'b Widget.widget ->
?expand:bool ->
?fill:fillMode ->
?inside:'c Widget.widget ->
?ipadx:int ->
?ipady:int ->
?padx:int ->
?pady:int ->
?side:side ->
'd Widget.widget list -> unit
(** Pack a widget inside its parent,
using the standard layout engine. *)
val grid :
?column:int ->
?columnspan:int ->
?inside:'a Widget.widget ->
?ipadx:int ->
?ipady:int ->
?padx:int ->
?pady:int ->
?row:int ->
?rowspan:int ->
?sticky:string -> 'b Widget.widget list -> unit
(** Pack a widget inside its parent, using the grid layout engine. *)
type borderMode = [`Ignore|`Inside|`Outside]
val place :
?anchor:anchor ->
?bordermode:borderMode ->
?height:int ->
?inside:'a Widget.widget ->
?relheight:float ->
?relwidth:float ->
?relx:float ->
?rely:float ->
?width:int ->
?x:int -> ?y:int -> 'b Widget.widget -> unit
(** Pack a widget inside its parent, at absolute coordinates. *)
val raise_window :
?above:'a Widget.widget -> 'b Widget.widget -> unit
val lower_window :
?below:'a Widget.widget -> 'b Widget.widget -> unit
(** Raise or lower the window associated to a widget. *)
(** {6 Event handling} *)
type modifier =
[ `Control | `Shift | `Lock
| `Button1 | `Button2 | `Button3 | `Button4 | `Button5
| `Double | `Triple
| `Mod1 | `Mod2 | `Mod3 | `Mod4 | `Mod5 | `Meta | `Alt ]
type event =
[ `ButtonPress | `ButtonPressDetail of int
| `ButtonRelease | `ButtonReleaseDetail of int
| `Circulate | `ColorMap | `Configure | `Destroy
| `Enter | `Expose | `FocusIn | `FocusOut | `Gravity
| `KeyPress | `KeyPressDetail of string
| `KeyRelease | `KeyReleaseDetail of string
| `Leave | `Map | `Motion | `Property
| `Reparent | `Unmap | `Visibility
| `Modified of modifier list * event ]
(** An event can be either a basic X event, or modified by a
key or mouse modifier. *)
type eventInfo =
{ mutable ev_Above: int;
mutable ev_ButtonNumber: int;
mutable ev_Count: int;
mutable ev_Detail: string;
mutable ev_Focus: bool;
mutable ev_Height: int;
mutable ev_KeyCode: int;
mutable ev_Mode: string;
mutable ev_OverrideRedirect: bool;
mutable ev_Place: string;
mutable ev_State: string;
mutable ev_Time: int;
mutable ev_Width: int;
mutable ev_MouseX: int;
mutable ev_MouseY: int;
mutable ev_Char: string;
mutable ev_BorderWidth: int;
mutable ev_SendEvent: bool;
mutable ev_KeySymString: string;
mutable ev_KeySymInt: int;
mutable ev_RootWindow: int;
mutable ev_SubWindow: int;
mutable ev_Type: int;
mutable ev_Widget: Widget.any Widget.widget;
mutable ev_RootX: int;
mutable ev_RootY: int }
(** Event related information accessible in callbacks. *)
type eventField =
[ `Above | `ButtonNumber | `Count | `Detail | `Focus | `Height
| `KeyCode | `Mode | `OverrideRedirect | `Place | `State
| `Time | `Width | `MouseX | `MouseY | `Char | `BorderWidth
| `SendEvent | `KeySymString | `KeySymInt | `RootWindow
| `SubWindow | `Type | `Widget | `RootX | `RootY ]
(** In order to access the above event information, one has to pass
a list of required event fields to the [bind] function. *)
val bind :
events:event list ->
?extend:bool ->
?breakable:bool ->
?fields:eventField list ->
?action:(eventInfo -> unit) ->
'a Widget.widget -> unit
(** Bind a succession of [events] on a widget to an [action].
If [extend] is true then then binding is added after existing
ones, otherwise it replaces them.
[breakable] should be true when [break] is to be called inside
the action.
[action] is called with the [fields] required set in
an [eventInfo] structure. Other fields should not be accessed.
If [action] is omitted then existing bindings are removed. *)
val bind_class :
events:event list ->
?extend:bool ->
?breakable:bool ->
?fields:eventField list ->
?action:(eventInfo -> unit) ->
?on:'a Widget.widget ->
string -> unit
(** Same thing for all widgets of a given class. If a widget
is given with label [~on:], the binding will be removed as
soon as it is destroyed. *)
val bind_tag :
events:event list ->
?extend:bool ->
?breakable:bool ->
?fields:eventField list ->
?action:(eventInfo -> unit) ->
?on:'a Widget.widget ->
string -> unit
(** Same thing for all widgets having a given tag *)
val break : unit -> unit
(** Used inside a bound action, do not call other actions
after this one. This is only possible if this action
was bound with [~breakable:true]. *)

113
manual/manual/macros.hva Normal file
View File

@ -0,0 +1,113 @@
%%Colors for links
\def\visited@color{\#006000}
\def\link@color{\#00A000}
\def\hover@color{\@getstylecolor{subsection}}
\newstyle{a:link}{color:\link@color;text-decoration:underline;}
\newstyle{a:visited}{color:\visited@color;text-decoration:underline;}
\newstyle{a:hover}{color:black;text-decoration:none;background-color:\hover@color}
%%%
\newcommand{\input@color}{\htmlcolor{006000}}
\newcommand{\output@color}{\maroon}
\newcommand{\machine}{\tt}
\newenvironment{machineenv}{\begin{alltt}}{\end{alltt}}
\newcommand{\firstline}{\black\#\input@color\ }
\newcommand{\nextline}{\ \ }
\newcommand{\@zyva}{\firstline\renewcommand{\?}{\nextline}}
\newenvironment{camlunder}{\@style{U}}{}
\newcommand{\caml}{\begin{alltt}\renewcommand{\;}{}\renewcommand{\\}{\char92}\def\<{\begin{camlunder}}\def\>{\end{camlunder}}\activebracefalse}
\let\?=\@zyva
\newcommand{\endcaml}{\activebracetrue\end{alltt}}
\renewcommand{\:}{\renewcommand{\?}{\@zyva}\output@color}
\newcommand{\var}[1]{\textit{#1}}
\newenvironment{library}{}{}
\newcounter{page}
\newenvironment{comment}{\begin{quote}}{\end{quote}}
\newcommand{\nth}[2]{\({#1}_{#2}\)}
\newenvironment{options}{\begin{description}}{\end{description}}
%%venant de macros.tex
\def\versionspecific#1{\begin{quote}\textsf{#1:}\quad}
\def\unix{\versionspecific{Unix}}
\def\endunix{\end{quote}}
\def\macos{\versionspecific{MacOS~9}}
\def\endmacos{\end{quote}}
\def\windows{\versionspecific{Windows}}
\def\endwindows{\end{quote}}
\def\requirements{\trivlist \item[\hskip\labelsep {\bf Requirements.}]}
\def\endrequirements{\endtrivlist}
\def\installation{\trivlist \item[\hskip\labelsep {\bf Installation.}]}
\def\endinstallation{\endtrivlist}
\def\troubleshooting{\trivlist \item[\hskip\labelsep {\bf Troubleshooting.}]}
\def\endtroubleshooting{\endtrivlist}
\newtheorem{gcrule}{Rule}
% Pour les tables de priorites et autres tableaux a deux colonnes, encadres
\def\entree#1#2{#1 & #2 \\}
\def\tableau#1#2#3{%
\par\begin{center}%
\begin{tabular*}{.8\linewidth}{#1}%
\multicolumn{1}{c}{\textbf{#2}} &
\multicolumn{1}{c}{\textbf{#3}} \\
%%#2 & #3 \\%
}%
\def\endtableau{\end{tabular*}\end{center}\par}
% L'environnement library (pour composer les descriptions des modules
% de bibliotheque).
\def\restoreindent{\begingroup\let\@listI=\@savedlistI}
\def\endrestoreindent{\endgroup}
% PDF stuff
\def\pdfchapterfold#1#2{}
\def\pdfsection#1{}
\def\pdfchapter{\pdfchapterfold{0}}
%%% Pour camlidl
\def\transl#1{$[\![\mbox{#1}]\!]$}
% Pour l'index
\usepackage{multind}
\let\indexentry=\index
\renewcommand{\index}[1]{\indexentry{\jobname}{#1}}
\def\ikwd#1{\indexentry{\jobname.kwd}{#1}}
% nth
\def\th{^{\mbox{\scriptsize th}}}
\renewcommand{\hbox}[1]{\mbox{#1}}
% Notations pour les metavariables
\def\nmth#1#2#3{\({#1}_{#2}^{#3}\)}
\def\optvar#1{[\var{#1}\/]}
\def\event{§§}
\def\fromoneto#1#2{$#1 = 1,\ldots{} , #2$}
\newcommand{\vfill}{}
\def\number{}
\def\year{2013}
% Pour alltt
\def\rminalltt#1{{\rm #1}}
\def\goodbreak{\ \\}
\def\@savedlistI{}
%List of links with no space around items
\newstyle{.li-links}{margin:0ex 0ex;}
\newenvironment{links}
{\setenvclass{itemize}{ftoc2}\setenvclass{li-itemize}{li-links}\itemize}
{\enditemize}
% Pour le chapitre ocamlbuild
\newcommand{\mathscr}[1]{{\mathcal{#1}}}
\newcommand{\ocb}{\texttt{ocamlbuild}\xspace}
\newcommand{\tags}{\texttt{\_tags}\xspace}

255
manual/manual/macros.tex Normal file
View File

@ -0,0 +1,255 @@
\makeatletter
% Pour hevea
\newif\ifouthtml\outhtmlfalse
\newcommand{\cutname}[1]{}
% Notations pour les metavariables
\def\var#1{{\it#1}}
\def\nth#1#2{${\it#1}_{#2}$}
\def\nmth#1#2#3{${\it#1}_{#2}^{#3}$}
\def\optvar#1{\textrm{[}\var{#1}\/\textrm{]}}
\def\event{$\bowtie$}
\def\fromoneto#1#2{$#1 = 1, \ldots, #2$}
% Pour avoir les exposants sur la ligne au-dessus (???)
\ifplaintext
\fontdimen14\tensy=12pt
\fi
% Numerotation
\setcounter{secnumdepth}{2} % Pour numeroter les \subsection
\setcounter{tocdepth}{1} % Pour ne pas mettre les \subsection
% dans la table des matieres
% Pour avoir "_" qui marche en mode math et en mode normal
\catcode`\_=13
\catcode`\=8
\def\_{\hbox{\tt\char95}}
\def_{\ifmmode\else\_\fi}
\ifplaintext
\def\ttstretch{\tt}
\else
\def\ttstretch{\tt\spaceskip=5.77pt plus 1.83pt minus 1.22pt}
% La fonte cmr10 a normalement des espaces de 5.25pt non extensibles.
% En 11 pt ca fait 5.77 pt. On lui ajoute la meme flexibilite que
% cmr10 agrandie a 11 pt.
\fi
% Pour la traduction "xxxx" -> {\machine{xxxx}} faite par texquote2
\def\machine#1{\mbox{\ttstretch{#1}}}
% Pour la traduction "\begin{verbatim}...\end{verbatim}"
% -> "\begin{machineenv}...\end{machineenv}"
% faite aussi par texquote2.
\newenvironment{machineenv}{\alltt}{\endalltt}
% Environnements
\newlength{\versionwidth}
\setbox0=\hbox{\bf Windows:} \setlength{\versionwidth}{\wd0}
\def\versionspecific#1{
\begin{description}\item[#1:]~\\}
\def\unix{\versionspecific{Unix}}
\def\endunix{\end{description}}
%\def\macos{\versionspecific{MacOS 9}}
%\def\endmacos{\end{description}}
\def\windows{\versionspecific{Windows}}
\def\endwindows{\end{description}}
\def\requirements{\trivlist \item[\hskip\labelsep {\bf Requirements.}]}
\def\endrequirements{\endtrivlist}
\def\installation{\trivlist \item[\hskip\labelsep {\bf Installation.}]}
\def\endinstallation{\endtrivlist}
\def\troubleshooting{\trivlist \item[\hskip\labelsep {\bf Troubleshooting.}]}
\def\endtroubleshooting{\endtrivlist}
\newtheorem{gcrule}{Rule}
% Pour les tables de priorites et autres tableaux a deux colonnes, encadres
\def\tableau#1#2#3{%
\begin{center}
\begin{tabular}{#1}
\hline
#2 & #3 \\
\hline
}
\def\endtableau{\hline\end{tabular}\end{center}}
\def\entree#1#2{#1 & #2 \\}
% L'environnement option
\def\optionitem[#1]{\if@noparitem \@donoparitem
\else \if@inlabel \indent \par \fi
\ifhmode \unskip\unskip \par \fi
\if@newlist \if@nobreak \@nbitem \else
\addpenalty\@beginparpenalty
\addvspace\@topsep \addvspace{-\parskip}\fi
\else \addpenalty\@itempenalty \addvspace\itemsep
\fi
\global\@inlabeltrue
\fi
\everypar{\global\@minipagefalse\global\@newlistfalse
\if@inlabel\global\@inlabelfalse \hskip -\parindent \box\@labels
\penalty\z@ \fi
\everypar{}}\global\@nobreakfalse
\if@noitemarg \@noitemargfalse \if@nmbrlist \refstepcounter{\@listctr}\fi \fi
\setbox\@tempboxa\hbox{\makelabel{#1}}%
\global\setbox\@labels
\ifdim \wd\@tempboxa >\labelwidth
\hbox{\unhbox\@labels
\hskip -\leftmargin
\box\@tempboxa}\hfil\break
\else
\hbox{\unhbox\@labels
\hskip -\leftmargin
\hbox to\leftmargin {\makelabel{#1}\hfil}}
\fi
\ignorespaces}
\def\optionlabel#1{\bf #1}
\def\options{\list{}{\let\makelabel\optionlabel\let\@item\optionitem}}
\def\endoptions{\endlist}
% L'environnement library (pour composer les descriptions des modules
% de bibliotheque).
\def\comment{\penalty200\list{}{}\item[]}
\def\endcomment{\endlist\penalty-100}
\def\library{
\begingroup
\raggedright
\let\@savedlistI=\@listI%
\def\@listI{\leftmargin\leftmargini\parsep 0pt plus 1pt\topsep 0pt plus 2pt}%
\itemsep 0pt
\topsep 0pt plus 2pt
\partopsep 0pt
}
\def\endlibrary{
\endgroup
}
\def\restoreindent{\begingroup\let\@listI=\@savedlistI}
\def\endrestoreindent{\endgroup}
% ^^A...^^A: compose l'interieur en \tt, comme \verb
\catcode`\^^A=\active
\def{%
\begingroup\catcode``=13\@noligs\ttstretch\let\do\@makeother\dospecials%
\def\@xobeysp{\leavevmode\penalty100\ }%
\@vobeyspaces\frenchspacing\catcode`\^^A=\active\def{\endgroup}}
% Pour l'index
\let\indexentry=\index
\def\index{\indexentry{\jobname}}
\def\ikwd{\indexentry{\jobname.kwd}}
% Les en-tetes personnalises
\pagestyle{myheadings}
\def\partmark#1{\markboth{Part \thepart. \ #1}{}}
\def\chaptermark#1{\markright{Chapter \thechapter. \ #1}}
% nth
\def\th{^{\hbox{\scriptsize th}}}
% Pour annuler l'espacement vertical qui suit un "verbatim"
\def\cancelverbatim{\vspace{-\topsep}\vspace{-\parskip}}% exact.
% Pour annuler l'espacement vertical entre deux \item consecutifs dans \options
\def\cancelitemspace{\vspace{-8mm}}% determine empiriquement
% Pour faire la cesure apres _ dans les identificateurs
\def\={\discretionary{}{}{}}
\def\cuthere{\discretionary{}{}{}}
% Pour la coupure en petits documents
\let\mysection=\section
%%% Augmenter l'espace entre numero de section
% et nom de section dans la table des matieres.
\ifplaintext\else
\def\l@section{\@dottedtocline{1}{1.5em}{2.8em}} % D'origine: 2.3
\fi
% Pour alltt
\def\rminalltt#1{{\rm #1}}
% redefinition de l'environnement alltt pour que les {} \ et % soient
% dans la bonne fonte
\let\@oldalltt=\alltt
\let\@oldendalltt=\endalltt
\renewenvironment{alltt}{%
\begingroup%
\renewcommand{\{}{\char`\{}%
\renewcommand{\}}{\char`\}}%
\renewcommand{\\}{\char`\\}%
\renewcommand{\%}{\char`\%}%
\@oldalltt%
}{%
\@oldendalltt%
\endgroup%
}
% Index stuff -- cf multind.sty
\def\printindex#1#2{\@restonecoltrue\if@twocolumn\@restonecolfalse\fi
\columnseprule \z@ \columnsep 35pt
\newpage \twocolumn[{\Large\bf #2 \vskip4ex}]
\markright{\uppercase{#2}}
\addcontentsline{toc}{section}{#2}
\pdfsection{#2}
\@input{#1.ind}}
% PDF stuff -- no longer needed, Hyperref does the job
\def\pdfchapterfold#1#2{}
\def\pdfchapter#1{}
\def\pdfsection#1{}
%\ifpdf
%\newcount\pdflabel
%\pdflabel=1
%\def\pdfchapterfold#1#2{
%\pdfdest num \pdflabel fit
%\pdfoutline goto num \pdflabel count #1 {\arabic{chapter}. #2}
%\global\advance\pdflabel by 1
%}
%\def\pdfsection#1{
%\pdfdest num \pdflabel fit
%\pdfoutline goto num \pdflabel {#1}
%\global\advance\pdflabel by 1
%}
%\else
%\def\pdfchapterfold#1#2{}
%\def\pdfsection#1{}
%\fi
%
%\def\pdfchapter{\pdfchapterfold{0}}
%%% Pour camlidl
\def\transl#1{$[\![\mbox{#1}]\!]$}
%%% Pour les references des modules
\newcommand{\moduleref}[1]{\ref{#1}}
%%% Fin des hacks
\makeatother
% Pour le chapitre ocamlbuild
\newcommand{\mathscr}[1]{{\mathcal{#1}}}
\newcommand{\ocb}{\texttt{ocamlbuild}\xspace}
\newcommand{\tags}{\texttt{\_tags}\xspace}

4
manual/manual/manual.hva Normal file
View File

@ -0,0 +1,4 @@
\input{book.hva}
\input{fancysection.hva}
\input{macros.hva}
\newif\ifouthtml\outhtmltrue

120
manual/manual/manual.inf Normal file
View File

@ -0,0 +1,120 @@
\input{book.hva}
\renewcommand{\@indexsection}[1]{\chapter{#1}}
\newcommand{\black}{\htmlcolor{#000000}}
\newcommand{\machine}{\tt}
\newenvironment{machineenv}{\begin{alltt}}{\end{alltt}}
\newenvironment{camlunder}{\@style{U}}{}
\newcommand{\caml}{\begin{alltt}\renewcommand{\\}{\char92}\def\<{\begin{camlunder}}\def\>{\end{camlunder}}\activebracefalse}
\newcommand{\endcaml}{\activebracetrue\end{alltt}}
\newcommand{\?}{\black\#\blue }
\renewcommand{\:}{\maroon}
\newcommand{\var}[1]{\textit{#1}}
\newenvironment{library}{}{}
\newcounter{page}
\newenvironment{comment}{\begin{quote}}{\end{quote}}
\newcommand{\nth}[2]{\({#1}_{#2}\)}
\newenvironment{options}{\begin{description}}{\end{description}}
%%venant de macros.tex
\newif\ifouthtml\outhtmlfalse
\def\versionspecific#1{
\quad\textsf{#1:}
\begin{quote}}
\def\unix{\versionspecific{Unix}}
\def\endunix{\end{quote}}
\def\macos{\versionspecific{MacOS}}
\def\endmacos{\end{quote}}
\def\windows{\versionspecific{Windows}}
\def\endwindows{\end{quote}}
\def\requirements{\trivlist \item[\hskip\labelsep {\bf Requirements.}]}
\def\endrequirements{\endtrivlist}
\def\installation{\trivlist \item[\hskip\labelsep {\bf Installation.}]}
\def\endinstallation{\endtrivlist}
\def\troubleshooting{\trivlist \item[\hskip\labelsep {\bf Troubleshooting.}]}
\def\endtroubleshooting{\endtrivlist}
\newtheorem{gcrule}{Rule}
% Pour les tables de priorites et autres tableaux a deux colonnes, encadres
%\def\entree#1#2{#1 & #2 \\}
%\def\tableau#1#2#3{%
%\par\begin{center}%
%\begin{tabular}{#1}%
%\multicolumn{1}{c}{\textbf{#2}} &
%\multicolumn{1}{c}{\textbf{#3}} \\
%%#2 & #3 \\%
%}%
%\def\endtableau{\end{tabular}\end{center}\par}
% Pour les tables de priorites et autres tableaux a deux colonnes, encadres
\def\tableau#1#2#3{%
\begin{center}
\begin{tabular}{#1}
\hline
\multicolumn{1}{|c|}{\textbf{#2}} & \multicolumn{1}{c|}{\textbf{#3}} \\
\hline
}
\def\endtableau{\hline\end{tabular}\end{center}}
\def\entree#1#2{#1 & #2 \\}
% L'environnement library (pour composer les descriptions des modules
% de bibliotheque).
\def\restoreindent{\begingroup\let\@listI=\@savedlistI}
\def\endrestoreindent{\endgroup}
% PDF stuff
\def\pdfchapterfold#1#2{}
\def\pdfsection#1{}
\def\pdfchapter{\pdfchapterfold{0}}
%%% Pour camlidl
\def\transl#1{$[\![\mbox{#1}]\!]$}
% Pour l'index
\usepackage{multind}
\let\indexentry=\index
\renewcommand{\index}[1]{\indexentry{\jobname}{#1}}
\def\ikwd#1{\indexentry{\jobname.kwd}{#1}}
% nth
\def\th{^{\mbox{\scriptsize th}}}
\renewcommand{\hbox}[1]{\mbox{#1}}
% Notations pour les metavariables
\def\nmth#1#2#3{\({#1}_{#2}^{#3}\)}
\def\optvar#1{[\var{#1}\/]}
\def\event{§§}
\def\fromoneto#1#2{$#1 = 1,\ldots{} , #2$}
\newcommand{\vfill}{}
\def\number{}
\def\year{2013}
% Pour alltt
\def\rminalltt#1{{\rm #1}}
\def\goodbreak{\ \\}
\def\@savedlistI{}
%%
% Pour le chapitre ocamlbuild
\newcommand{\mathscr}[1]{{\mathcal{#1}}}
\newcommand{\ocb}{\texttt{ocamlbuild}\xspace}
\newcommand{\tags}{\texttt{\_tags}\xspace}
\newcommand{\@cup}{|\_|}

View File

@ -0,0 +1,4 @@
INFO-DIR-SECTION OCaml Programming Language
START-INFO-DIR-ENTRY
* ocaml: (ocaml). OCaml Reference Manual
END-INFO-DIR-ENTRY

30
manual/manual/manual.tex Normal file
View File

@ -0,0 +1,30 @@
\documentclass[11pt]{book}
\usepackage[latin1]{inputenc}
%HEVEA\@def@charset{US-ASCII}%
\usepackage{alltt}
\usepackage{fullpage}
\usepackage{syntaxdef}
\usepackage{multind}
\usepackage{html}
\usepackage{textcomp}
\usepackage{caml-sl}
\usepackage{ocamldoc}
\usepackage{xspace}
\newif\ifplaintext
\plaintextfalse
%\newif\ifpdf
%\pdffalse
\input{macros.tex}
\usepackage{hyperref}
%\makeatletter \def\@wrindex#1#2{\xdef \@indexfile{\csname #1@idxfile\endcsname}\@@wrindex#2||\\}\makeatother
\def\th{^{\hbox{\scriptsize th}}}
\raggedbottom
\input{version.tex}
%HEVEA\setcounter{cuttingdepth}{1}
%HEVEA\title{The OCaml system, release \ocamlversion}
\input{allfiles.tex}

View File

@ -0,0 +1,31 @@
%\pdfoutput=1
\pdfpagewidth=21cm
\pdfpageheight=11in
\pdfcompresslevel=7
\documentclass[11pt]{book}
\usepackage[latin1]{inputenc}
\usepackage{alltt}
\usepackage{fullpage}
\usepackage{syntaxdef}
\usepackage{multind}
\usepackage{html}
\usepackage{textcomp}
\usepackage{caml-sl}
\usepackage{ocamldoc}
\usepackage{xspace}
\newif\ifplaintext
\plaintextfalse
%\newif\ifpdf
%\pdftrue
\input macros.tex
\usepackage{hyperref}
\def\th{^{\hbox{\scriptsize th}}}
\raggedbottom
\input{version.tex}
\input allfiles.tex

View File

@ -0,0 +1,17 @@
\documentclass[11pt]{report}
\usepackage{plaintext}
\usepackage[latin1]{inputenc}
\usepackage{alltt}
\usepackage{fullpage}
\usepackage{syntaxdef}
\usepackage{multind}
\usepackage{html}
\usepackage{caml-sl}
\newif\ifplaintext
\plaintexttrue
%\newif\ifpdf
%\pdffalse
\input macros.tex
\input allfiles.tex

View File

@ -0,0 +1,2 @@
*.tex
*.htex

2
manual/manual/refman/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
*.tex
*.htex

View File

@ -0,0 +1,21 @@
FILES= refman.tex lex.tex names.tex values.tex const.tex types.tex \
patterns.tex expr.tex typedecl.tex modtypes.tex modules.tex compunit.tex \
exten.tex classes.tex
TRANSF=../../tools/transf
TEXQUOTE=../../tools/texquote2
ALLFILES=$(FILES)
all: $(ALLFILES)
clean:
rm -f $(ALLFILES)
.SUFFIXES:
.SUFFIXES: .etex .tex
.etex.tex:
$(TRANSF) < $*.etex | $(TEXQUOTE) > $*.tex
$(ALLFILES): $(TRANSF) $(TEXQUOTE)

View File

@ -0,0 +1,507 @@
\section{Classes}
\pdfsection{Classes}
%HEVEA\cutname{classes.html}
Classes are defined using a small language, similar to the module
language.
\subsection{Class types}
Class types are the class-level equivalent of type expressions: they
specify the general shape and type properties of classes.
\ikwd{object\@\texttt{object}}
\ikwd{end\@\texttt{end}}
\ikwd{inherit\@\texttt{inherit}}
\ikwd{val\@\texttt{val}}
\ikwd{mutable\@\texttt{mutable}}
\ikwd{method\@\texttt{method}}
\ikwd{private\@\texttt{private}}
\ikwd{virtual\@\texttt{virtual}}
\ikwd{constraint\@\texttt{constraint}}
\begin{syntax}
class-type:
[['?']label-name':'] typexpr '->' class-type
| class-body-type
;
class-body-type:
'object' ['(' typexpr ')'] {class-field-spec} 'end'
| ['[' typexpr {',' typexpr} ']'] classtype-path
;
%\end{syntax} \begin{syntax}
class-field-spec:
'inherit' class-body-type
| 'val' ['mutable'] ['virtual'] inst-var-name ':' typexpr
| 'val' 'virtual' 'mutable' inst-var-name ':' typexpr
| 'method' ['private'] ['virtual'] method-name ':' poly-typexpr
| 'method' 'virtual' 'private' method-name ':' poly-typexpr
| 'constraint' typexpr '=' typexpr
\end{syntax}
\subsubsection*{Simple class expressions}
The expression @classtype-path@ is equivalent to the class type bound to
the name @classtype-path@. Similarly, the expression
@'[' typexpr_1 ',' \ldots typexpr_n ']' classtype-path@ is equivalent to
the parametric class type bound to the name @classtype-path@, in which
type parameters have been instantiated to respectively @typexpr_1@,
\ldots @typexpr_n@.
\subsubsection*{Class function type}
The class type expression @typexpr '->' class-type@ is the type of
class functions (functions from values to classes) that take as
argument a value of type @typexpr@ and return as result a class of
type @class-type@.
\subsubsection*{Class body type}
The class type expression
@'object' ['(' typexpr ')'] {class-field-spec} 'end'@
is the type of a class body. It specifies its instance variables and
methods. In this type, @typexpr@ is matched against the self type, therefore
providing a name for the self type.
A class body will match a class body type if it provides definitions
for all the components specified in the class body type, and these
definitions meet the type requirements given in the class body type.
Furthermore, all methods either virtual or public present in the class
body must also be present in the class body type (on the other hand, some
instance variables and concrete private methods may be omitted). A
virtual method will match a concrete method, which makes it possible
to forget its implementation. An immutable instance variable will match a
mutable instance variable.
\subsubsection*{Inheritance}
\ikwd{inherit\@\texttt{inherit}}
The inheritance construct @'inherit' class-body-type@ provides for inclusion of
methods and instance variables from other class types.
The instance variable and method types from @class-body-type@ are added
into the current class type.
\subsubsection*{Instance variable specification}
\ikwd{val\@\texttt{val}}
\ikwd{mutable\@\texttt{mutable}}
\ikwd{virtual\@\texttt{virtual}}
A specification of an instance variable is written
@'val' ['mutable'] ['virtual'] inst-var-name ':' typexpr@, where
@inst-var-name@
is the name of the instance variable and @typexpr@ its expected type.
%
The flag @'mutable'@ indicates whether this instance variable can be
physically modified.
%
The flag @'virtual'@ indicates that this instance variable is not
initialized. It can be initialized later through inheritance.
An instance variable specification will hide any previous
specification of an instance variable of the same name.
\subsubsection*{Method specification}
\label{sec-methspec}
\ikwd{method\@\texttt{method}}
\ikwd{private\@\texttt{private}}
The specification of a method is written
@'method' ['private'] method-name ':' poly-typexpr@, where
@method-name@ is the name of the method and @poly-typexpr@ its
expected type, possibly polymorphic. The flag @'private'@ indicates
that the method cannot be accessed from outside the object.
The polymorphism may be left implicit in public method specifications:
any type variable which is not bound to a class parameter and does not
appear elsewhere inside the class specification will be assumed to be
universal, and made polymorphic in the resulting method type.
Writing an explicit polymorphic type will disable this behaviour.
If several specifications are present for the same method, they
must have compatible types.
Any non-private specification of a method forces it to be public.
\subsubsection*{Virtual method specification}
\ikwd{virtual\@\texttt{virtual}}
\ikwd{method\@\texttt{method}}
\ikwd{private\@\texttt{private}}
A virtual method specification is written @'method' ['private']
'virtual' method-name ':' poly-typexpr@, where @method-name@ is the
name of the method and @poly-typexpr@ its expected type.
\subsubsection*{Constraints on type parameters}
\ikwd{constraint\@\texttt{constraint}}
The construct @'constraint' typexpr_1 '=' typexpr_2@ forces the two
type expressions to be equal. This is typically used to specify type
parameters: in this way, they can be bound to specific type
expressions.
\subsection{Class expressions}
Class expressions are the class-level equivalent of value expressions:
they evaluate to classes, thus providing implementations for the
specifications expressed in class types.
\ikwd{object\@\texttt{object}}
\ikwd{end\@\texttt{end}}
\ikwd{fun\@\texttt{fun}}
\ikwd{let\@\texttt{let}}
\ikwd{rec\@\texttt{rec}}
\ikwd{in\@\texttt{in}}
\ikwd{and\@\texttt{and}}
\ikwd{inherit\@\texttt{inherit}}
\ikwd{as\@\texttt{as}}
\ikwd{val\@\texttt{val}}
\ikwd{mutable\@\texttt{mutable}}
\ikwd{method\@\texttt{method}}
\ikwd{private\@\texttt{private}}
\ikwd{virtual\@\texttt{virtual}}
\ikwd{constraint\@\texttt{constraint}}
\ikwd{initializer\@\texttt{initializer}}
\begin{syntax}
class-expr:
class-path
| '[' typexpr {',' typexpr} ']' class-path
| '(' class-expr ')'
| '(' class-expr ':' class-type ')'
| class-expr {{argument}}
| 'fun' {{parameter}} '->' class-expr
| 'let' ['rec'] let-binding {'and' let-binding} 'in' class-expr
| 'object' class-body 'end'
;
%BEGIN LATEX
\end{syntax} \begin{syntax}
%END LATEX
class-field:
'inherit' class-expr ['as' lowercase-ident]
| 'val' ['mutable'] inst-var-name [':' typexpr] '=' expr
| 'val' ['mutable'] 'virtual' inst-var-name ':' typexpr
| 'val' 'virtual' 'mutable' inst-var-name ':' typexpr
| 'method' ['private'] method-name {parameter} [':' typexpr] '=' expr
| 'method' ['private'] method-name ':' poly-typexpr '=' expr
| 'method' ['private'] 'virtual' method-name ':' poly-typexpr
| 'method' 'virtual' 'private' method-name ':' poly-typexpr
| 'constraint' typexpr '=' typexpr
| 'initializer' expr
\end{syntax}
\subsubsection*{Simple class expressions}
The expression @class-path@ evaluates to the class bound to the name
@class-path@. Similarly, the expression
@'[' typexpr_1 ',' \ldots typexpr_n ']' class-path@
evaluates to the parametric class bound to the name @class-path@,
in which type parameters have been instantiated respectively to
@typexpr_1@, \ldots @typexpr_n@.
The expression @'(' class-expr ')'@ evaluates to the same module as
@class-expr@.
The expression @'(' class-expr ':' class-type ')'@ checks that
@class-type@ matches the type of @class-expr@ (that is, that the
implementation @class-expr@ meets the type specification
@class-type@). The whole expression evaluates to the same class as
@class-expr@, except that all components not specified in
@class-type@ are hidden and can no longer be accessed.
\subsubsection*{Class application}
Class application is denoted by juxtaposition of (possibly labeled)
expressions. It denotes the class whose constructor is the first
expression applied to the given arguments. The arguments are
evaluated as for expression application, but the constructor itself will
only be evaluated when objects are created. In particular, side-effects
caused by the application of the constructor will only occur at object
creation time.
\subsubsection*{Class function}
The expression @'fun' [['?']label-name':']pattern '->' class-expr@ evaluates
to a function from values to classes.
When this function is applied to a value \var{v}, this value is
matched against the pattern @pattern@ and the result is the result of
the evaluation of @class-expr@ in the extended environment.
Conversion from functions with default values to functions with
patterns only works identically for class functions as for normal
functions.
The expression
\begin{center}
@"fun" parameter_1 \ldots parameter_n "->" class-expr@
\end{center}
is a short form for
\begin{center}
@"fun" parameter_1 "->" \ldots "fun" parameter_n "->" expr@
\end{center}
\subsubsection*{Local definitions}
The {\tt let} and {\tt let rec} constructs bind value names locally,
as for the core language expressions.
If a local definition occurs at the very beginning of a class
definition, it will be evaluated when the class is created (just as if
the definition was outside of the class).
Otherwise, it will be evaluated when the object constructor is called.
\subsubsection*{Class\label{ss:class-body} body}
\begin{syntax}
class-body: ['(' pattern [':' typexpr] ')'] { class-field }
\end{syntax}
The expression
@'object' class-body 'end'@ denotes
a class body. This is the prototype for an object : it lists the
instance variables and methods of an objet of this class.
A class body is a class value: it is not evaluated at once. Rather,
its components are evaluated each time an object is created.
In a class body, the pattern @'(' pattern [':' typexpr] ')'@ is
matched against self, therefore providing a binding for self and self
type. Self can only be used in method and initializers.
Self type cannot be a closed object type, so that the class remains
extensible.
Since OCaml 4.01, it is an error if the same method or instance
variable name is defined several times in the same class body.
\subsubsection*{Inheritance}
\ikwd{inherit\@\texttt{inherit}}
The inheritance construct @'inherit' class-expr@ allows reusing
methods and instance variables from other classes. The class
expression @class-expr@ must evaluate to a class body. The instance
variables, methods and initializers from this class body are added
into the current class. The addition of a method will override any
previously defined method of the same name.
\ikwd{as\@\texttt{as}}
An ancestor can be bound by appending @'as' lowercase-ident@
to the inheritance construct. @lowercase-ident@ is not a true
variable and can only be used to select a method, i.e. in an expression
@lowercase-ident '#' method-name@. This gives access to the
method @method-name@ as it was defined in the parent class even if it is
redefined in the current class.
The scope of this ancestor binding is limited to the current class.
The ancestor method may be called from a subclass but only indirectly.
\subsubsection*{Instance variable definition}
\ikwd{val\@\texttt{val}}
\ikwd{mutable\@\texttt{mutable}}
The definition @'val' ['mutable'] inst-var-name '=' expr@ adds an
instance variable @inst-var-name@ whose initial value is the value of
expression @expr@.
%
The flag @'mutable'@ allows physical modification of this variable by
methods.
An instance variable can only be used in the methods and
initializers that follow its definition.
Since version 3.10, redefinitions of a visible instance variable with
the same name do not create a new variable, but are merged, using the
last value for initialization. They must have identical types and
mutability.
However, if an instance variable is hidden by
omitting it from an interface, it will be kept distinct from
other instance variables with the same name.
\subsubsection*{Virtual instance variable definition}
\ikwd{virtual\@\texttt{virtual}}
\ikwd{val\@\texttt{val}}
\ikwd{mutable\@\texttt{mutable}}
A variable specification is written @'val' ['mutable'] 'virtual'
inst-var-name ':' typexpr@. It specifies whether the variable is
modifiable, and gives its type.
Virtual instance variables were added in version 3.10.
\subsubsection*{Method definition}
\ikwd{method\@\texttt{method}}
\ikwd{private\@\texttt{private}}
A method definition is written @'method' method-name '=' expr@. The
definition of a method overrides any previous definition of this
method. The method will be public (that is, not private) if any of
the definition states so.
A private method, @'method' 'private' method-name '=' expr@, is a
method that can only be invoked on self (from other methods of the
same object, defined in this class or one of its subclasses). This
invocation is performed using the expression
@value-name '#' method-name@, where @value-name@ is directly bound to
self at the beginning of the class definition. Private methods do
not appear in object types. A method may have both public and private
definitions, but as soon as there is a public one, all subsequent
definitions will be made public.
Methods may have an explicitly polymorphic type, allowing them to be
used polymorphically in programs (even for the same object). The
explicit declaration may be done in one of three ways: (1) by giving an
explicit polymorphic type in the method definition, immediately after
the method name, {\em i.e.}
@'method' ['private'] method-name ':' {{"'" ident}} '.' typexpr '='
expr@; (2) by a forward declaration of the explicit polymorphic type
through a virtual method definition; (3) by importing such a
declaration through inheritance and/or constraining the type of {\em
self}.
Some special expressions are available in method bodies for
manipulating instance variables and duplicating self:
\begin{syntax}
expr:
\ldots
| inst-var-name '<-' expr
| '{<' [ inst-var-name '=' expr { ';' inst-var-name '=' expr } [';'] ] '>}'
\end{syntax}
The expression @inst-var-name '<-' expr@ modifies in-place the current
object by replacing the value associated to @inst-var-name@ by the
value of @expr@. Of course, this instance variable must have been
declared mutable.
The expression
@'{<' inst-var-name_1 '=' expr_1 ';' \ldots ';' inst-var-name_n '=' expr_n '>}'@
evaluates to a copy of the current object in which the values of
instance variables @inst-var-name_1, \ldots, inst-var-name_n@ have
been replaced by the values of the corresponding expressions @expr_1,
\ldots, expr_n@.
\subsubsection*{Virtual method definition}
\ikwd{virtual\@\texttt{virtual}}
\ikwd{method\@\texttt{method}}
\ikwd{private\@\texttt{private}}
A method specification is written @'method' ['private'] 'virtual'
method-name ':' poly-typexpr@. It specifies whether the method is
public or private, and gives its type. If the method is intended to be
polymorphic, the type must be explicitly polymorphic.
\subsubsection*{Constraints on type parameters}
\ikwd{constraint\@\texttt{constraint}}
The construct @'constraint' typexpr_1 '=' typexpr_2@ forces the two
type expressions to be equals. This is typically used to specify type
parameters: in that way they can be bound to specific type
expressions.
\subsubsection*{Initializers}
\ikwd{initializer\@\texttt{initializer}}
A class initializer @'initializer' expr@ specifies an expression that
will be evaluated whenever an object is created from the class, once
all its instance variables have been initialized.
\subsection{Class definitions}
\label{s:classdef}
\ikwd{class\@\texttt{class}}
\ikwd{and\@\texttt{and}}
\ikwd{virtual\@\texttt{virtual}}
\begin{syntax}
class-definition:
'class' class-binding { 'and' class-binding }
;
class-binding:
['virtual'] ['[' type-parameters ']'] class-name
{parameter} [':' class-type] \\ '=' class-expr
;
type-parameters:
"'" ident { "," "'" ident }
\end{syntax}
A class definition @'class' class-binding { 'and' class-binding }@ is
recursive. Each @class-binding@ defines a @class-name@ that can be
used in the whole expression except for inheritance. It can also be
used for inheritance, but only in the definitions that follow its own.
A class binding binds the class name @class-name@ to the value of
expression @class-expr@. It also binds the class type @class-name@ to
the type of the class, and defines two type abbreviations :
@class-name@ and @'#' class-name@. The first one is the type of
objects of this class, while the second is more general as it unifies
with the type of any object belonging to a subclass (see
section~\ref{s:sharp-types}).
\subsubsection*{Virtual class}
\ikwd{virtual\@\texttt{virtual}}
A class must be flagged virtual if one of its methods is virtual (that
is, appears in the class type, but is not actually defined).
Objects cannot be created from a virtual class.
\subsubsection*{Type parameters}
The class type parameters correspond to the ones of the class type and
of the two type abbreviations defined by the class binding. They must
be bound to actual types in the class definition using type
constraints. So that the abbreviations are well-formed, type
variables of the inferred type of the class must either be type
parameters or be bound in the constraint clause.
\subsection{Class specifications}
\label{s:class-spec}
\ikwd{class\@\texttt{class}}
\ikwd{and\@\texttt{and}}
\ikwd{virtual\@\texttt{virtual}}
\begin{syntax}
class-specification:
'class' class-spec { 'and' class-spec }
;
class-spec:
['virtual'] ['[' type-parameters ']'] class-name ':'
class-type
\end{syntax}
This is the counterpart in signatures of class definitions.
A class specification matches a class definition if they have the same
type parameters and their types match.
\subsection{Class type definitions}
\label{s:classtype}
\ikwd{class\@\texttt{class}}
\ikwd{type\@\texttt{type}}
\ikwd{and\@\texttt{and}}
\ikwd{virtual\@\texttt{virtual}}
\begin{syntax}
classtype-definition:
'class' 'type' classtype-def
{ 'and' classtype-def }
;
classtype-def:
['virtual'] ['[' type-parameters ']'] class-name '=' class-body-type
\end{syntax}
A class type definition @'class' class-name '=' class-body-type@
defines an abbreviation @class-name@ for the class body type
@class-body-type@. As for class definitions, two type abbreviations
@class-name@ and @'#' class-name@ are also defined. The definition can
be parameterized by some type parameters. If any method in the class
type body is virtual, the definition must be flagged @'virtual'@.
Two class type definitions match if they have the same type parameters
and they expand to matching types.

View File

@ -0,0 +1,42 @@
\section{Compilation units}
\pdfsection{Compilation units}
%HEVEA\cutname{compunit.html}
\begin{syntax}
unit-interface: { specification [';;'] }
;
unit-implementation: [ module-items ]
\end{syntax}
Compilation units bridge the module system and the separate
compilation system. A compilation unit is composed of two parts: an
interface and an implementation. The interface contains a sequence of
specifications, just as the inside of a @'sig' \ldots 'end'@
signature expression. The implementation contains a sequence of
definitions and expressions, just as the inside of a
@'struct' \ldots 'end'@ module
expression. A compilation unit also has a name @unit-name@, derived
from the names of the files containing the interface and the
implementation (see chapter~\ref{c:camlc} for more details). A
compilation unit behaves roughly as the module definition
\begin{center}
@'module' unit-name ':' 'sig' unit-interface 'end' '='
'struct' unit-implementation 'end'@
\end{center}
A compilation unit can refer to other compilation units by their
names, as if they were regular modules. For instance, if "U" is a
compilation unit that defines a type "t", other compilation units can
refer to that type under the name "U.t"; they can also refer to "U" as
a whole structure. Except for names of other compilation units, a unit
interface or unit implementation must not have any other free variables.
In other terms, the type-checking and compilation of an interface or
implementation proceeds in the initial environment
\begin{center}
@name_1 ':' 'sig' specification_1 'end' \ldots
name_n ':' 'sig' specification_n 'end'@
\end{center}
where @name_1 \ldots name_n@ are the names of the other
compilation units available in the search path (see
chapter~\ref{c:camlc} for more details) and @specification_1 \ldots
specification_n@ are their respective interfaces.

View File

@ -0,0 +1,26 @@
\section{Constants}
\pdfsection{Constants}
%HEVEA\cutname{const.html}
\begin{syntax}
constant:
integer-literal
| float-literal
| char-literal
| string-literal
| constr
| "false"
| "true"
| "("")"
| "begin" "end"
| "[""]"
| "[|""|]"
| "`"tag-name
\end{syntax}
The syntactic class of constants comprises literals from the four
base types (integers, floating-point numbers, characters, character
strings), and constant constructors from both normal and polymorphic
variants, as well as the special constants @"false"@, @"true"@, @"("")"@,
@"[""]"@, and @"[|""|]"@, which behave like constant constructors, and
@"begin" "end"@, which is equivalent to @'('')'@.

View File

@ -0,0 +1,25 @@
\section{Directives} \label{s:directives}
\begin{syntax}
directive:
'#' 'open' string
| '#' 'close' string
| '#' ident string
\end{syntax}
Directives control the behavior of the compiler. They apply to the
remainder of the current compilation unit.
The two directives \verb"#open" and \verb"#close" modify the list of
opened modules, that the compiler uses to complete unqualified
identifiers, as described in section~\ref{s:names}. The directive
@'#open' string@ adds the module whose name is given by the string
constant @string@ to the list of opened modules, in first position.
The directive @'#close' string@ removes the first occurrence of the
module whose name is given by the string constant @string@ from the
list of opened modules.
Implementations can provide other directives, provided they follow the
syntax @'#' ident string@, where @ident@ is the name of the directive,
and the string constant @string@ is the argument to the directive. The
behavior of these additional directives is implementation-dependent.

View File

@ -0,0 +1,897 @@
\section{Expressions\label{s:value-expr}}
\pdfsection{Expressions}
%HEVEA\cutname{expr.html}
\ikwd{in\@\texttt{in}|see{\texttt{let}}}
\ikwd{and\@\texttt{and}|see{\texttt{let}, \texttt{type}, \texttt{class}}}
\ikwd{rec\@\texttt{rec}|see{\texttt{let}}}
\ikwd{let\@\texttt{let}}
\ikwd{try\@\texttt{try}}
\ikwd{function\@\texttt{function}}
\ikwd{fun\@\texttt{fun}}
\ikwd{with\@\texttt{with}|see{\texttt{match}, \texttt{try}}}
\ikwd{done\@\texttt{done}|see{\texttt{while}, \texttt{for}}}
\ikwd{do\@\texttt{do}|see{\texttt{while}, \texttt{for}}}
\ikwd{downto\@\texttt{downto}|see{\texttt{for}}}
\ikwd{to\@\texttt{to}|see{\texttt{for}}}
\ikwd{for\@\texttt{for}}
\ikwd{else\@\texttt{else}|see{\texttt{if}}}
\ikwd{then\@\texttt{then}|see{\texttt{if}}}
\ikwd{if\@\texttt{if}}
\ikwd{of\@\texttt{of}|see{\texttt{type}, \texttt{exception}}}
\ikwd{or\@\texttt{or}}
\ikwd{match\@\texttt{match}}
\ikwd{begin\@\texttt{begin}}
\ikwd{end\@\texttt{end}}
\ikwd{when\@\texttt{when}}
\ikwd{new\@\texttt{new}}
\ikwd{object\@\texttt{object}}
\begin{syntax}
expr:
value-path
| constant
| '(' expr ')'
| 'begin' expr 'end'
| '(' expr ':' typexpr ')'
| expr {{',' expr}}
| constr expr
| "`"tag-name expr
| expr '::' expr
| '[' expr { ';' expr } [';'] ']'
| '[|' expr { ';' expr } [';'] '|]'
| '{' field '=' expr { ';' field '=' expr } [';'] '}'
| '{' expr 'with' field '=' expr { ';' field '=' expr } [';'] '}'
| expr {{ argument }}
| prefix-symbol expr
| '-' expr
| '-.' expr
| expr infix-op expr
| expr '.' field
| expr '.' field '<-' expr
| expr '.(' expr ')'
| expr '.(' expr ')' '<-' expr
| expr '.[' expr ']'
| expr '.[' expr ']' '<-' expr
| 'if' expr 'then' expr [ 'else' expr ]
| 'while' expr 'do' expr 'done'
| 'for' value-name '=' expr ( 'to' || 'downto' ) expr 'do' expr 'done'
| expr ';' expr
| 'match' expr 'with' pattern-matching
| 'function' pattern-matching
| 'fun' {{ parameter }} '->' expr
| 'try' expr 'with' pattern-matching
| 'let' ['rec'] let-binding { 'and' let-binding } 'in' expr
| 'new' class-path
| 'object' class-body 'end'
| expr '#' method-name
| inst-var-name
| inst-var-name '<-' expr
| '(' expr ':>' typexpr ')'
| '(' expr ':' typexpr ':>' typexpr ')'
| '{<' [ inst-var-name '=' expr { ';' inst-var-name '=' expr } [';'] ] '>}'
| 'assert' expr
| 'lazy' expr
| 'let' 'module' module-name { '(' module-name ':' module-type ')' }
[ ':' module-type ] \\ '=' module-expr 'in' expr
;
%BEGIN LATEX
\end{syntax} \begin{syntax}
%END LATEX
argument:
expr
| '~' label-name
| '~' label-name ':' expr
| '?' label-name
| '?' label-name ':' expr
;
%\end{syntax} \begin{syntax}
pattern-matching:
[ '|' ] pattern ['when' expr] '->' expr
{ '|' pattern ['when' expr] '->' expr }
;
let-binding:
pattern '=' expr
| value-name { parameter } [':' typexpr] [':>' typexpr] '=' expr
;
parameter:
pattern
| '~' label-name
| '~' '(' label-name [':' typexpr] ')'
| '~' label-name ':' pattern
| '?' label-name
| '?' '(' label-name [':' typexpr] ['=' expr] ')'
| '?' label-name ':' pattern
| '?' label-name ':' '(' pattern [':' typexpr] ['=' expr] ')'
\end{syntax}
The table below shows the relative precedences and associativity of
operators and non-closed constructions. The constructions with higher
precedence come first. For infix and prefix symbols, we write
``"*"\ldots'' to mean ``any symbol starting with "*"''.
\ikwd{or\@\texttt{or}}%
\ikwd{if\@\texttt{if}}%
\ikwd{fun\@\texttt{fun}}%
\ikwd{function\@\texttt{function}}%
\ikwd{match\@\texttt{match}}%
\ikwd{try\@\texttt{try}}%
\ikwd{let\@\texttt{let}}%
\begin{tableau}{|l|l|}{Construction or operator}{Associativity}
\entree{prefix-symbol}{--}
\entree{". .( .[ .{" (see section~\ref{s:bigarray-access})}{--}
\entree{"#"\ldots}{--}
\entree{function application, constructor application, tag
application, "assert",
"lazy"}{left}
\entree{"- -." (prefix)}{--}
\entree{"**"\ldots" lsl lsr asr"}{right}
\entree{"*"\ldots" /"\ldots" %"\ldots" mod land lor lxor"}{left}
%% "`"@ident@"`"
\entree{"+"\ldots" -"\ldots}{left}
\entree{"::"}{right}
\entree{{\tt \char64}\ldots " ^"\ldots}{right}
\entree{"="\ldots" <"\ldots" >"\ldots" |"\ldots" &"\ldots" $"\ldots" !="}{left}
\entree{"& &&"}{right}
\entree{"or ||"}{right}
\entree{","}{--}
\entree{"<- :="}{right}
\entree{"if"}{--}
\entree{";"}{right}
\entree{"let match fun function try"}{--}
\end{tableau}
\subsection{Basic expressions}
\subsubsection*{Constants}
An expression consisting in a constant evaluates to this constant.
\subsubsection*{Value paths} \label{expr:var}
An expression consisting in an access path evaluates to the value bound to
this path in the current evaluation environment. The path can
be either a value name or an access path to a value component of a module.
\subsubsection*{Parenthesized expressions}
\ikwd{begin\@\texttt{begin}}
\ikwd{end\@\texttt{end}}
The expressions @'(' expr ')'@ and @'begin' expr 'end'@ have the same
value as @expr@. The two constructs are semantically equivalent, but it
is good style to use @'begin' \ldots 'end'@ inside control structures:
\begin{alltt}
if \ldots then begin \ldots ; \ldots end else begin \ldots ; \ldots end
\end{alltt}
and @'(' \ldots ')'@ for the other grouping situations.
Parenthesized expressions can contain a type constraint, as in @'('
expr ':' typexpr ')'@. This constraint forces the type of @expr@ to be
compatible with @typexpr@.
Parenthesized expressions can also contain coercions
@'(' expr [':' typexpr] ':>' typexpr')'@ (see
subsection~\ref{s:coercions} below).
\subsubsection*{Function application}
Function application is denoted by juxtaposition of (possibly labeled)
expressions. The expression @expr argument_1 \ldots argument_n@
evaluates the expression @expr@ and those appearing in @argument_1@
to @argument_n@. The expression @expr@ must evaluate to a
functional value $f$, which is then applied to the values of
@argument_1, \ldots, argument_n@.
The order in which the expressions @expr, argument_1, \ldots,
argument_n@ are evaluated is not specified.
Arguments and parameters are matched according to their respective
labels. Argument order is irrelevant, except among arguments with the
same label, or no label.
If a parameter is specified as optional (label prefixed by @"?"@) in the
type of @expr@, the corresponding argument will be automatically
wrapped with the constructor "Some", except if the argument itself is
also prefixed by @"?"@, in which case it is passed as is.
%
If a non-labeled argument is passed, and its corresponding parameter
is preceded by one or several optional parameters, then these
parameters are {\em defaulted}, {\em i.e.} the value "None" will be
passed for them.
%
All other missing parameters (without corresponding argument), both
optional and non-optional, will be kept, and the result of the
function will still be a function of these missing parameters to the
body of $f$.
As a special case, if the function has a known arity, all the
arguments are unlabeled, and their number matches the number of
non-optional parameters, then labels are ignored and non-optional
parameters are matched in their definition order. Optional arguments
are defaulted.
In all cases but exact match of order and labels, without optional
parameters, the function type should be known at the application
point. This can be ensured by adding a type constraint. Principality
of the derivation can be checked in the "-principal" mode.
\subsubsection*{Function definition}
Two syntactic forms are provided to define functions. The first form
is introduced by the keyword "function":
\ikwd{function\@\texttt{function}}
$$\begin{array}{rlll}
\token{function} & \textsl{pattern}_1 & \token{->} & \textsl{expr}_1 \\
\token{|} & \ldots \\
\token{|} & \textsl{pattern}_n & \token{->} & \textsl{expr}_n
\end{array}$$
This expression evaluates to a functional value with one argument.
When this function is applied to a value \var{v}, this value is
matched against each pattern @pattern_1@ to @pattern_n@.
If one of these matchings succeeds, that is, if the value \var{v}
matches the pattern @pattern_i@ for some \var{i},
then the expression @expr_i@ associated to the selected pattern
is evaluated, and its value becomes the value of the function
application. The evaluation of @expr_i@ takes place in an
environment enriched by the bindings performed during the matching.
If several patterns match the argument \var{v}, the one that occurs
first in the function definition is selected. If none of the patterns
matches the argument, the exception "Match_failure" is raised.
%
\index{Matchfailure\@\verb`Match_failure`}
\medskip
The other form of function definition is introduced by the keyword "fun":
\ikwd{fun\@\texttt{fun}}
\begin{center}
@"fun" parameter_1 \ldots parameter_n "->" expr@
\end{center}
This expression is equivalent to:
\begin{center}
@"fun" parameter_1 "->" \ldots "fun" parameter_n "->" expr@
\end{center}
The parameter patterns @"~"lab@ and @"~("lab [":" typ]")"@
are shorthands for respectively @"~"lab":"lab@ and
@"~"lab":("lab [":" typ]")"@, and similarly for their optional
counterparts.
A function of the form @"fun" "?" lab ":(" pattern '=' expr_0 ')' '->'
expr@ is equivalent to
\begin{center}
@"fun" "?" lab ":" ident '->'
"let" pattern '='
"match" ident "with" "Some" ident "->" ident '|' "None" '->' expr_0
"in" expr@
\end{center}
where @ident@
is a fresh variable, except that it is unspecified when @expr_0@ is evaluated.
After these two transformations, expressions are of the form
\begin{center}
@"fun" [label_1] pattern_1 "->" \ldots "fun" [label_n] pattern_n "->" expr@
\end{center}
If we ignore labels, which will only be meaningful at function
application, this is equivalent to
\begin{center}
@"function" pattern_1 "->" \ldots "function" pattern_n "->" expr@
\end{center}
That is, the @"fun"@ expression above evaluates to a curried function
with \var{n} arguments: after applying this function $n$ times to the
values @@v@_1 \ldots @v@_n@, the values will be matched
in parallel against the patterns @pattern_1 \ldots pattern_n@.
If the matching succeeds, the function returns the value of @expr@ in
an environment enriched by the bindings performed during the matchings.
If the matching fails, the exception "Match_failure" is raised.
\subsubsection*{Guards in pattern-matchings}
\ikwd{when\@\texttt{when}}
The cases of a pattern matching (in the @"function"@, @"match"@ and
@"try"@ constructs) can include guard expressions, which are
arbitrary boolean expressions that must evaluate to "true" for the
match case to be selected. Guards occur just before the @"->"@ token and
are introduced by the @"when"@ keyword:
$$\begin{array}{rlll}
\token{function} & \nt{pattern}_1 \; [\token{when} \; \nt{cond}_1] & \token{->} & \nt{expr}_1 \\
\token{|} & \ldots \\
\token{|} & \nt{pattern}_n \; [\token{when} \; \nt{cond}_n] & \token{->} & \nt{expr}_n
\end{array}$$
Matching proceeds as described before, except that if the value
matches some pattern @pattern_i@ which has a guard @@cond@_i@, then the
expression @@cond@_i@ is evaluated (in an environment enriched by the
bindings performed during matching). If @@cond@_i@ evaluates to "true",
then @expr_i@ is evaluated and its value returned as the result of the
matching, as usual. But if @@cond@_i@ evaluates to "false", the matching
is resumed against the patterns following @pattern_i@.
\subsubsection*{Local definitions} \label{s:localdef}
\ikwd{let\@\texttt{let}}
The @"let"@ and @"let" "rec"@ constructs bind value names locally.
The construct
\begin{center}
@"let" pattern_1 "=" expr_1 "and" \ldots "and" pattern_n "=" expr_n "in" expr@
\end{center}
evaluates @expr_1 \ldots expr_n@ in some unspecified order and matches
their values against the patterns @pattern_1 \ldots pattern_n@. If the
matchings succeed, @expr@ is evaluated in the environment enriched by
the bindings performed during matching, and the value of @expr@ is
returned as the value of the whole @"let"@ expression. If one of the
matchings fails, the exception "Match_failure" is raised.
%
\index{Matchfailure\@\verb`Match_failure`}
An alternate syntax is provided to bind variables to functional
values: instead of writing
\begin{center}
@"let" ident "=" "fun" parameter_1 \ldots parameter_m "->" expr@
\end{center}
in a @"let"@ expression, one may instead write
\begin{center}
@"let" ident parameter_1 \ldots parameter_m "=" expr@
\end{center}
\medskip
\noindent
Recursive definitions of names are introduced by @"let" "rec"@:
\begin{center}
@"let" "rec" pattern_1 "=" expr_1 "and" \ldots "and" pattern_n "=" expr_n
"in" expr@
\end{center}
The only difference with the @"let"@ construct described above is
that the bindings of names to values performed by the
pattern-matching are considered already performed when the expressions
@expr_1@ to @expr_n@ are evaluated. That is, the expressions @expr_1@
to @expr_n@ can reference identifiers that are bound by one of the
patterns @pattern_1, \ldots, pattern_n@, and expect them to have the
same value as in @expr@, the body of the @"let" "rec"@ construct.
The recursive definition is guaranteed to behave as described above if
the expressions @expr_1@ to @expr_n@ are function definitions
(@"fun" \ldots@ or @"function" \ldots@), and the patterns @pattern_1
\ldots pattern_n@ are just value names, as in:
\begin{center}
@"let" "rec" name_1 "=" "fun" \ldots
"and" \ldots
"and" name_n "=" "fun" \ldots
"in" expr@
\end{center}
This defines @name_1 \ldots name_n@ as mutually recursive functions
local to @expr@.
The behavior of other forms of @"let" "rec"@ definitions is
implementation-dependent. The current implementation also supports
a certain class of recursive definitions of non-functional values,
as explained in section~\ref{s:letrecvalues}.
\subsection{Control structures}
\subsubsection*{Sequence}
The expression @expr_1 ";" expr_2@ evaluates @expr_1@ first, then
@expr_2@, and returns the value of @expr_2@.
\subsubsection*{Conditional}
\ikwd{if\@\texttt{if}}
The expression @"if" expr_1 "then" expr_2 "else" expr_3@ evaluates to
the value of @expr_2@ if @expr_1@ evaluates to the boolean @"true"@,
and to the value of @expr_3@ if @expr_1@ evaluates to the boolean
@"false"@.
The @"else" expr_3@ part can be omitted, in which case it defaults to
@"else" "()"@.
\subsubsection*{Case expression}\ikwd{match\@\texttt{match}}
The expression
$$\begin{array}{rlll}
\token{match} & \textsl{expr} \\
\token{with} & \textsl{pattern}_1 & \token{->} & \textsl{expr}_1 \\
\token{|} & \ldots \\
\token{|} & \textsl{pattern}_n & \token{->} & \textsl{expr}_n
\end{array}$$
matches the value of @expr@ against the patterns @pattern_1@ to
@pattern_n@. If the matching against @pattern_i@ succeeds, the
associated expression @expr_i@ is evaluated, and its value becomes the
value of the whole @'match'@ expression. The evaluation of
@expr_i@ takes place in an environment enriched by the bindings
performed during matching. If several patterns match the value of
@expr@, the one that occurs first in the @'match'@ expression is
selected. If none of the patterns match the value of @expr@, the
exception "Match_failure" is raised.
%
\index{Matchfailure\@\verb`Match_failure`}
\subsubsection*{Boolean operators}
The expression @expr_1 '&&' expr_2@ evaluates to @'true'@ if both
@expr_1@ and @expr_2@ evaluate to @'true'@; otherwise, it evaluates to
@'false'@. The first component, @expr_1@, is evaluated first. The
second component, @expr_2@, is not evaluated if the first component
evaluates to @'false'@. Hence, the expression @expr_1 '&&' expr_2@ behaves
exactly as
\begin{center}
@'if' expr_1 'then' expr_2 'else' 'false'@.
\end{center}
The expression @expr_1 '||' expr_2@ evaluates to @'true'@ if one of
the expressions
@expr_1@ and @expr_2@ evaluates to @'true'@; otherwise, it evaluates to
@'false'@. The first component, @expr_1@, is evaluated first. The
second component, @expr_2@, is not evaluated if the first component
evaluates to @'true'@. Hence, the expression @expr_1 '||' expr_2@ behaves
exactly as
\begin{center}
@'if' expr_1 'then' 'true' 'else' expr_2@.
\end{center}
\ikwd{or\@\texttt{or}}
The boolean operators @'&'@ and @'or'@ are deprecated synonyms for
(respectively) @'&&'@ and @'||'@.
\subsubsection*{Loops}
\ikwd{while\@\texttt{while}}
The expression @'while' expr_1 'do' expr_2 'done'@ repeatedly
evaluates @expr_2@ while @expr_1@ evaluates to @'true'@. The loop
condition @expr_1@ is evaluated and tested at the beginning of each
iteration. The whole @'while' \ldots 'done'@ expression evaluates to
the unit value @'()'@.
\ikwd{for\@\texttt{for}}
The expression @'for' name '=' expr_1 'to' expr_2 'do' expr_3 'done'@
first evaluates the expressions @expr_1@ and @expr_2@ (the boundaries)
into integer values \var{n} and \var{p}. Then, the loop body @expr_3@ is
repeatedly evaluated in an environment where @name@ is successively
bound to the values
$n$, $n+1$, \ldots, $p-1$, $p$.
The loop body is never evaluated if $n > p$.
The expression @'for' name '=' expr_1 'downto' expr_2 'do' expr_3 'done'@
evaluates similarly, except that @name@ is successively bound to the values
$n$, $n-1$, \ldots, $p+1$, $p$.
The loop body is never evaluated if $n < p$.
In both cases, the whole @'for'@ expression evaluates to the unit
value @'()'@.
\subsubsection*{Exception handling}
\ikwd{try\@\texttt{try}}
The expression
$$\begin{array}{rlll}
\token{try~} & \textsl{expr} \\
\token{with} & \textsl{pattern}_1 & \token{->} & \textsl{expr}_1 \\
\token{|} & \ldots \\
\token{|} & \textsl{pattern}_n & \token{->} & \textsl{expr}_n
\end{array}$$
evaluates the expression @expr@ and returns its value if the
evaluation of @expr@ does not raise any exception. If the evaluation
of @expr@ raises an exception, the exception value is matched against
the patterns @pattern_1@ to @pattern_n@. If the matching against
@pattern_i@ succeeds, the associated expression @expr_i@ is evaluated,
and its value becomes the value of the whole @'try'@ expression. The
evaluation of @expr_i@ takes place in an environment enriched by the
bindings performed during matching. If several patterns match the value of
@expr@, the one that occurs first in the @'try'@ expression is
selected. If none of the patterns matches the value of @expr@, the
exception value is raised again, thereby transparently ``passing
through'' the @'try'@ construct.
\subsection{Operations on data structures}
\subsubsection*{Products}
The expression @expr_1 ',' \ldots ',' expr_n@ evaluates to the
\var{n}-tuple of the values of expressions @expr_1@ to @expr_n@. The
evaluation order of the subexpressions is not specified.
\subsubsection*{Variants}
The expression @constr expr@ evaluates to the unary variant value
whose constructor is @constr@, and whose argument is the value of
@expr@. Similarly, the expression @constr '(' expr_1 ',' \ldots ','
expr_n ')'@ evaluates to the n-ary variant value whose constructor is
@constr@ and whose arguments are the values of @expr_1, \ldots,
expr_n@.
The expression @constr '('expr_1, \ldots, expr_n')'@ evaluates to the
variant value whose constructor is @constr@, and whose arguments are
the values of @expr_1 \ldots expr_n@.
For lists, some syntactic sugar is provided. The expression
@expr_1 '::' expr_2@ stands for the constructor @'(' '::' ')' @
applied to the arguments @'(' expr_1 ',' expr_2 ')'@, and therefore
evaluates to the list whose head is the value of @expr_1@ and whose tail
is the value of @expr_2@. The expression @'[' expr_1 ';' \ldots ';'
expr_n ']'@ is equivalent to @expr_1 '::' \ldots '::' expr_n '::'
'[]'@, and therefore evaluates to the list whose elements are the
values of @expr_1@ to @expr_n@.
\subsubsection*{Polymorphic variants}
The expression @"`"tag-name expr@ evaluates to the polymorphic variant
value whose tag is @tag-name@, and whose argument is the value of @expr@.
\subsubsection*{Records}
The expression @'{' field_1 '=' expr_1 ';' \ldots ';' field_n '='
expr_n '}'@ evaluates to the record value
$\{ field_1 = v_1; \ldots; field_n = v_n \}$
where $v_i$ is the value of @expr_i@ for \fromoneto{i}{n}.
The fields @field_1@ to @field_n@ must all belong to the same record
type; each field of this record type must appear exactly
once in the record expression, though they can appear in any
order. The order in which @expr_1@ to @expr_n@ are evaluated is not
specified.
The expression
@"{" expr "with" field_1 "=" expr_1 ";" \ldots ";" field_n "=" expr_n "}"@
builds a fresh record with fields @field_1 \ldots field_n@ equal to
@expr_1 \ldots expr_n@, and all other fields having the same value as
in the record @expr@. In other terms, it returns a shallow copy of
the record @expr@, except for the fields @field_1 \ldots field_n@,
which are initialized to @expr_1 \ldots expr_n@.
The expression @expr_1 '.' field@ evaluates @expr_1@ to a record
value, and returns the value associated to @field@ in this record
value.
The expression @expr_1 '.' field '<-' expr_2@ evaluates @expr_1@ to a record
value, which is then modified in-place by replacing the value
associated to @field@ in this record by the value of
@expr_2@. This operation is permitted only if @field@ has been
declared @'mutable'@ in the definition of the record type. The whole
expression @expr_1 '.' field '<-' expr_2@ evaluates to the unit value
@'()'@.
\subsubsection*{Arrays}
The expression @'[|' expr_1 ';' \ldots ';' expr_n '|]'@ evaluates to
a \var{n}-element array, whose elements are initialized with the values of
@expr_1@ to @expr_n@ respectively. The order in which these
expressions are evaluated is unspecified.
The expression @expr_1 '.(' expr_2 ')'@ returns the value of element
number @expr_2@ in the array denoted by @expr_1@. The first element
has number 0; the last element has number $n-1$, where \var{n} is the
size of the array. The exception "Invalid_argument" is raised if the
access is out of bounds.
The expression @expr_1 '.(' expr_2 ')' '<-' expr_3@ modifies in-place
the array denoted by @expr_1@, replacing element number @expr_2@ by
the value of @expr_3@. The exception "Invalid_argument" is raised if
the access is out of bounds. The value of the whole expression is @'()'@.
\subsubsection*{Strings}
The expression @expr_1 '.[' expr_2 ']'@ returns the value of character
number @expr_2@ in the string denoted by @expr_1@. The first character
has number 0; the last character has number $n-1$, where \var{n} is the
length of the string. The exception "Invalid_argument" is raised if the
access is out of bounds.
The expression @expr_1 '.[' expr_2 ']' '<-' expr_3@ modifies in-place
the string denoted by @expr_1@, replacing character number @expr_2@ by
the value of @expr_3@. The exception "Invalid_argument" is raised if
the access is out of bounds. The value of the whole expression is @'()'@.
{\bf Note:} this possibility is offered only for backward
compatibility with older versions of OCaml and will be removed in a
future version. New code should use byte sequences and the "Bytes.set"
function.
\subsection{Operators}
Symbols from the class @infix-symbol@, as well as the keywords
@"*"@, @"+"@, @"-"@, @'-.'@, @"="@, @"!="@, @"<"@, @">"@, @"or"@, @"||"@,
@"&"@, @"&&"@, @":="@, @"mod"@, @"land"@, @"lor"@, @"lxor"@, @"lsl"@, @"lsr"@,
and @"asr"@ can appear in infix position (between two
expressions). Symbols from the class @prefix-symbol@, as well as
the keywords @"-"@ and @"-."@
can appear in prefix position (in front of an expression).
Infix and prefix symbols do not have a fixed meaning: they are simply
interpreted as applications of functions bound to the names
corresponding to the symbols. The expression @prefix-symbol expr@ is
interpreted as the application @'(' prefix-symbol ')'
expr@. Similarly, the expression @expr_1 infix-symbol expr_2@ is
interpreted as the application @'(' infix-symbol ')' expr_1 expr_2@.
The table below lists the symbols defined in the initial environment
and their initial meaning. (See the description of the core
library module "Pervasives" in chapter~\ref{c:corelib} for more
details). Their meaning may be changed at any time using
@"let" "(" infix-op ")" name_1 name_2 "=" \ldots@
Note: the operators @'&&'@, @'||'@, and @'~-'@ are handled specially
and it is not advisable to change their meaning.
The keywords @'-'@ and @'-.'@ can appear both as infix and
prefix operators. When they appear as prefix operators, they are
interpreted respectively as the functions @'(~-)'@ and @'(~-.)'@.
%% Conversely, a regular function identifier can also be used as an infix
%% operator by enclosing it in backquotes: @expr_1 '`' ident '`' expr_2@
%% is interpreted as the application @ident expr_1 expr_2@.
\begin{tableau}{|l|p{12cm}|}{Operator}{Initial meaning}
\entree{"+"}{Integer addition.}
\entree{"-" (infix)}{Integer subtraction.}
\entree{"~- -" (prefix)}{Integer negation.}
\entree{"*"}{Integer multiplication.}
\entree{"/"}{Integer division.
Raise "Division_by_zero" if second argument is zero.}
\entree{"mod"}{Integer modulus. Raise
"Division_by_zero" if second argument is zero.}
\entree{"land"}{Bitwise logical ``and'' on integers.}
\entree{"lor"}{Bitwise logical ``or'' on integers.}
\entree{"lxor"}{Bitwise logical ``exclusive or'' on integers.}
\entree{"lsl"}{Bitwise logical shift left on integers.}
\entree{"lsr"}{Bitwise logical shift right on integers.}
\entree{"asr"}{Bitwise arithmetic shift right on integers.}
\entree{"+."}{Floating-point addition.}
\entree{"-." (infix)}{Floating-point subtraction.}
\entree{"~-. -." (prefix)}{Floating-point negation.}
\entree{"*."}{Floating-point multiplication.}
\entree{"/."}{Floating-point division.}
\entree{"**"}{Floating-point exponentiation.}
\entree{{\tt\char64} }{List concatenation.}
\entree{"^" }{String concatenation.}
\entree{"!" }{Dereferencing (return the current
contents of a reference).}
\entree{":="}{Reference assignment (update the
reference given as first argument with the value of the second
argument).}
\entree{"=" }{Structural equality test.}
\entree{"<>" }{Structural inequality test.}
\entree{"==" }{Physical equality test.}
\entree{"!=" }{Physical inequality test.}
\entree{"<" }{Test ``less than''.}
\entree{"<=" }{Test ``less than or equal''.}
\entree{">" }{Test ``greater than''.}
\entree{">=" }{Test ``greater than or equal''.}
\entree{"&& &"}{Boolean conjunction.}
\entree{"|| or"}{Boolean disjunction.}
\end{tableau}
\subsection{Objects} \label{s:objects}
\subsubsection*{Object creation}
\ikwd{new\@\texttt{new}}
When @class-path@ evaluates to a class body, @'new' class-path@
evaluates to a new object containing the instance variables and
methods of this class.
When @class-path@ evaluates to a class function, @'new' class-path@
evaluates to a function expecting the same number of arguments and
returning a new object of this class.
\subsubsection*{Immediate object creation}
\ikwd{object\@\texttt{object}}
Creating directly an object through the @'object' class-body 'end'@
construct is operationally equivalent to defining locally a @'class'
class-name '=' 'object' class-body 'end'@ ---see sections
\ref{ss:class-body} and following for the syntax of @class-body@---
and immediately creating a single object from it by @'new' class-name@.
The typing of immediate objects is slightly different from explicitly
defining a class in two respects. First, the inferred object type may
contain free type variables. Second, since the class body of an
immediate object will never be extended, its self type can be unified
with a closed object type.
\subsubsection*{Method invocation}
The expression @expr '#' method-name@ invokes the method
@method-name@ of the object denoted by @expr@.
If @method-name@ is a polymorphic method, its type should be known at
the invocation site. This is true for instance if @expr@ is the name
of a fresh object (@'let' ident = 'new' class-path \dots @) or if
there is a type constraint. Principality of the derivation can be
checked in the "-principal" mode.
\subsubsection*{Accessing and modifying instance variables}
The instance variables of a class are visible only in the body of the
methods defined in the same class or a class that inherits from the
class defining the instance variables. The expression @inst-var-name@
evaluates to the value of the given instance variable. The expression
@inst-var-name '<-' expr@ assigns the value of @expr@ to the instance
variable @inst-var-name@, which must be mutable. The whole expression
@inst-var-name '<-' expr@ evaluates to @"()"@.
\subsubsection*{Object duplication}
An object can be duplicated using the library function "Oo.copy"
(see
\ifouthtml \ahref{libref/Oo.html}{Module \texttt{Oo}}\else
section~\ref{Oo}\fi). Inside a method, the expression
@ '{<' inst-var-name '=' expr { ';' inst-var-name '=' expr } '>}'@
returns a copy of self with the given instance variables replaced by
the values of the associated expressions; other instance variables
have the same value in the returned object as in self.
\subsection{Coercions} \label{s:coercions}
Expressions whose type contains object or polymorphic variant types
can be explicitly coerced (weakened) to a supertype.
%
The expression @'('expr ':>' typexpr')'@ coerces the expression @expr@
to type @typexpr@.
%
The expression @'('expr ':' typexpr_1 ':>' typexpr_2')'@ coerces the
expression @expr@ from type @typexpr_1@ to type @typexpr_2@.
The former operator will sometimes fail to coerce an expression @expr@
from a type @typ_1@ to a type @typ_2@
even if type @typ_1@ is a subtype of type
@typ_2@: in the current implementation it only expands two levels of
type abbreviations containing objects and/or polymorphic variants,
keeping only recursion when it is explicit in the class type (for objects).
As an exception to the above algorithm, if both the inferred type of @expr@
and @typ@ are ground ({\em i.e.} do not contain type variables), the
former operator behaves as the latter one, taking the inferred type of
@expr@ as @typ_1@. In case of failure with the former operator,
the latter one should be used.
It is only possible to coerce an expression @expr@ from type
@typ_1@ to type @typ_2@, if the type of @expr@ is an instance of
@typ_1@ (like for a type annotation), and @typ_1@ is a subtype
of @typ_2@. The type of the coerced expression is an
instance of @typ_2@. If the types contain variables,
they may be instantiated by the subtyping algorithm, but this is only
done after determining whether @typ_1@ is a potential subtype of
@typ_2@. This means that typing may fail during this latter
unification step, even if some instance of @typ_1@ is a subtype of
some instance of @typ_2@.
%
In the following paragraphs we describe the subtyping relation used.
\subsubsection*{Object types}
A fixed object type admits as subtype any object type that includes all
its methods. The types of the methods shall be subtypes of those in
the supertype. Namely,
\begin{center}
@ '<' met_1 ':' typ_1 ';' \dots ';' met_n ':' typ_n '>' @
\end{center}
is a supertype of
\begin{center}
@ '<' met_1 ':' typ@$'_1$@ ';' \dots ';' met_n ':' typ@$'_n$@ ';'
met@$_{n+1}$@ ':' typ@$'_{n+1}$@ ';' \dots ';' met@$_{n+m}$@ ':' typ@$'_{n+m}$@
~[';' '..'] '>' @
\end{center}
which may contain an ellipsis ".." if every @typ_i@ is a supertype of
the corresponding @typ@$'_i$.
A monomorphic method type can be a supertype of a polymorphic method
type. Namely, if @typ@ is an instance of @typ@$'$, then @ "'"@a@_1
\dots "'"@a@_n '.' typ@$'$ is a subtype of @typ@.
Inside a class definition, newly defined types are not available for
subtyping, as the type abbreviations are not yet completely
defined. There is an exception for coercing @@self@@ to the (exact)
type of its class: this is allowed if the type of @@self@@ does not
appear in a contravariant position in the class type, {\em i.e.} if
there are no binary methods.
\subsubsection*{Polymorphic variant types}
A polymorphic variant type @typ@ is a subtype of another polymorphic
variant type @typ@$'$ if the upper bound of @typ@ ({\em i.e.} the
maximum set of constructors that may appear in an instance of @typ@)
is included in the lower bound of @typ@$'$, and the types of arguments
for the constructors of @typ@ are subtypes of those in
@typ@$'$. Namely,
\begin{center}
@ "["["<"] "`"C_1 "of" typ_1 "|" \dots "|" "`"C_n "of" typ_n "]" @
\end{center}
which may be a shrinkable type, is a subtype of
\begin{center}
@ "["[">"] "`"C_1 "of" typ@$'_1$@ "|" \dots "|" "`"C_n "of" typ@$'_n$@
"|" "`"C@$_{n+1}$@ "of" typ@$'_{n+1}$@ "|" \dots "|" "`"C@$_{n+m}$@ "of"
typ@$'_{n+m}$@ "]" @
\end{center}
which may be an extensible type, if every @typ_i@ is a subtype of @typ@$'_i$.
\subsubsection*{Variance}
Other types do not introduce new subtyping, but they may propagate the
subtyping of their arguments. For instance, @typ_1 "*" typ_2@ is a
subtype of @typ@$'_1$@ "*" typ@$'_2$ when @typ_1@ and @typ_2@ are
respectively subtypes of @typ@$'_1$ and @typ@$'_2$.
For function types, the relation is more subtle:
@typ_1 "->" typ_2@ is a subtype of @typ@$'_1$@~"->" typ@$'_2$
if @typ_1@ is a supertype of @typ@$'_1$ and @typ_2@ is a
subtype of @typ@$'_2$. For this reason, function types are covariant in
their second argument (like tuples), but contravariant in their first
argument. Mutable types, like "array" or "ref" are neither covariant
nor contravariant, they are nonvariant, that is they do not propagate
subtyping.
For user-defined types, the variance is automatically inferred: a
parameter is covariant if it has only covariant occurrences,
contravariant if it has only contravariant occurrences,
variance-free if it has no occurrences, and nonvariant otherwise.
A variance-free parameter may change freely through subtyping, it does
not have to be a subtype or a supertype.
%
For abstract and private types, the variance must be given explicitly
(see section~\ref{s:type-defs}),
otherwise the default is nonvariant. This is also the case for
constrained arguments in type definitions.
\subsection{Other}
\subsubsection*{Assertion checking}
\ikwd{assert\@\texttt{assert}}
OCaml supports the @"assert"@ construct to check debugging assertions.
The expression @"assert" expr@ evaluates the expression @expr@ and
returns @"()"@ if @expr@ evaluates to @"true"@. If it evaluates to
@"false"@ the exception
"Assert_failure" is raised with the source file name and the
location of @expr@ as arguments. Assertion
checking can be turned off with the "-noassert" compiler option. In
this case, @expr@ is not evaluated at all.
As a special case, @"assert false"@ is reduced to
@'raise' '('@"Assert_failure ..."@')'@, which gives it a polymorphic
type. This means that it can be used in place of any expression (for
example as a branch of any pattern-matching). It also means that
the @"assert false"@ ``assertions'' cannot be turned off by the
"-noassert" option.
%
\index{Assertfailure\@\verb`Assert_failure`}
\subsubsection*{Lazy expressions}
\ikwd{lazy\@\texttt{lazy}}
The expression @"lazy" expr@ returns a value \var{v} of type "Lazy.t" that
encapsulates the computation of @expr@. The argument @expr@ is not
evaluated at this point in the program. Instead, its evaluation will
be performed the first time the function "Lazy.force" is applied to the value
\var{v}, returning the actual value of @expr@. Subsequent applications
of "Lazy.force" to \var{v} do not evaluate @expr@ again. Applications
of "Lazy.force" may be implicit through pattern matching (see~\ref{s:lazypat}).
\subsubsection*{Local modules}
\ikwd{let\@\texttt{let}}
\ikwd{module\@\texttt{module}}
The expression
@"let" "module" module-name "=" module-expr "in" expr@
locally binds the module expression @module-expr@ to the identifier
@module-name@ during the evaluation of the expression @expr@.
It then returns the value of @expr@. For example:
\begin{verbatim}
let remove_duplicates comparison_fun string_list =
let module StringSet =
Set.Make(struct type t = string
let compare = comparison_fun end) in
StringSet.elements
(List.fold_right StringSet.add string_list StringSet.empty)
\end{verbatim}
%% \newpage

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,54 @@
\section{Module implementations}
\begin{syntax}
implementation:
{ impl-phrase ';;' }
;
impl-phrase:
expr
| value-definition
| type-definition
| exception-definition
| directive
;
value-definition:
'let' ['rec'] let-binding { 'and' let-binding }
\end{syntax}
A module implementation consists in a sequence of implementation
phrases, terminated by double semicolons. An implementation phrase is
either an expression, a value definition, a type or exception
definition, or a directive. At run-time, implementation phrases are
evaluated sequentially, in the order in which they appear in the
module implementation.
Implementation phrases consisting in an expression are
evaluated for their side-effects.
Value definitions bind global value variables in the same way as a
@'let' \ldots 'in' \ldots@ expression binds local variables. The
expressions are evaluated, and their values are matched against the
left-hand sides of the @'='@ sides, as explained in
section~\ref{s:localdef}. If the matching succeeds, the bindings of
identifiers to values performed during matching are interpreted as
bindings to the global value variables whose local name is the
identifier, and whose module name is the name of the module.
If the matching fails, the exception \verb"Match_failure" is
raised. The scope of these bindings is the phrases that follow the
value definition in the module implementation.
Type and exception definitions introduce type constructors, variant
constructors and record fields as described in sections
\ref{s:typdef}~and~\ref{s:excdef}.
The scope of these definitions is the phrases that follow the value
definition in the module implementation. The evaluation of an
implementation phrase consisting in a type or exception definition
produces no effect at run-time.
Directives modify the behavior of the compiler on the subsequent
phrases of the module implementation, as described in
section~\ref{s:directives}. The evaluation of an implementation phrase
consisting in a directive produces no effect at run-time. Directives
apply only to the module currently being compiled; in particular, they
have no effect on other modules that refer to globals exported by the
module being compiled.

View File

@ -0,0 +1,55 @@
\section{Module interfaces}
\ikwd{value\@\texttt{value}}
\ikwd{type\@\texttt{type}}
\ikwd{exception\@\texttt{exception}}
\begin{syntax}
interface:
{ intf-phrase ';;' }
;
intf-phrase:
value-declaration
| type-definition
| exception-definition
| directive
;
value-declaration:
'value' ident ':' typexpr { 'and' ident ':' typexpr }
\end{syntax}
Module interfaces declare the global objects (value variables, type
constructors, variant constructors, record fields) that a module
exports, that is, makes available to other modules.
Other modules can refer to these globals using qualified identifiers
or the \verb"#open" directive, as explained in section~\ref{s:names}.
A module interface consists in a sequence of interface
phrases, terminated by double semicolons. An interface phrase is
either a value declaration, a type definition, an exception
definition, or a directive.
Value declarations declare global value variables that are
exported by the module implementation, and the types with which they are
exported. The module implementation must define these variables, with
types at least as general as the types declared in the interface. The
scope of the bindings for these global variables extends from the
module implementation itself to all modules that refer to those variables.
Type or exception definitions introduce type constructors, variant
constructors and record fields as described in sections
\ref{s:typdef}~and~\ref{s:excdef}. Exception definitions and type
definitions that are not abstract type declarations also take effect
in the module implementation; that is, the type constructors, variant
constructors and record fields they define are considered bound on
entrance to the module implementation, and can be referred to by the
implementation phrases. Type definitions that are not abstract type
declarations must not be redefined in the module implementation. In
contrast, the type constructors that are declared abstract in a module
interface must be defined in the module implementation, with the same names.
Directives modify the behavior of the compiler on the subsequent
phrases of the module interface, as described in
section~\ref{s:directives}. Directives apply only to the interface
currently being compiled; in particular, they have no effect on other
modules that refer to globals exported by the interface being
compiled.

View File

@ -0,0 +1,274 @@
\section{Lexical conventions}
\pdfsection{Lexical conventions}
%HEVEA\cutname{lex.html}
\subsubsection*{Blanks}
The following characters are considered as blanks: space,
horizontal tabulation, carriage return, line feed and form feed. Blanks are
ignored, but they separate adjacent identifiers, literals and
keywords that would otherwise be confused as one single identifier,
literal or keyword.
\subsubsection*{Comments}
Comments are introduced by the two characters @"(*"@, with no
intervening blanks, and terminated by the characters @"*)"@, with
no intervening blanks. Comments are treated as blank characters.
Comments do not occur inside string or character literals. Nested
comments are handled correctly.
\subsubsection*{Identifiers}
\begin{syntax}
ident: ( letter || "_" ) { letter || "0" \ldots "9" || "_" || "'" } ;
capitalized-ident: ("A" \ldots "Z") { letter || "0" \ldots "9" || "_" || "'" } ;
lowercase-ident:
("a" \ldots "z" || "_") { letter || "0" \ldots "9" || "_" || "'" } ;
letter: "A" \ldots "Z" || "a" \ldots "z"
\end{syntax}
Identifiers are sequences of letters, digits, "_" (the underscore
character), and "'" (the single quote), starting with a
letter or an underscore.
Letters contain at least the 52 lowercase and uppercase
letters from the ASCII set. The current implementation
also recognizes as letters some characters from the ISO
8859-1 set (characters 192--214 and 216--222 as uppercase letters;
characters 223--246 and 248--255 as lowercase letters). This
feature is deprecated and should be avoided for future compatibility.
All characters in an identifier are
meaningful. The current implementation accepts identifiers up to
16000000 characters in length.
In many places, OCaml makes a distinction between capitalized
identifiers and identifiers that begin with a lowercase letter. The
underscore character is considered a lowercase letter for this
purpose.
\subsubsection*{Integer literals}
\begin{syntax}
integer-literal:
["-"] ("0"\ldots"9") { "0"\ldots"9" || "_" }
| ["-"] ("0x"||"0X") ("0"\ldots"9"||"A"\ldots"F"||"a"\ldots"f")
{ "0"\ldots"9"||"A"\ldots"F"||"a"\ldots"f"||"_" }
| ["-"] ("0o"||"0O") ("0"\ldots"7") { "0"\ldots"7"||"_" }
| ["-"] ("0b"||"0B") ("0"\ldots"1") { "0"\ldots"1"||"_" }
\end{syntax}
An integer literal is a sequence of one or more digits, optionally
preceded by a minus sign. By default, integer literals are in decimal
(radix 10). The following prefixes select a different radix:
\begin{tableau}{|l|l|}{Prefix}{Radix}
\entree{"0x", "0X"}{hexadecimal (radix 16)}
\entree{"0o", "0O"}{octal (radix 8)}
\entree{"0b", "0B"}{binary (radix 2)}
\end{tableau}
(The initial @"0"@ is the digit zero; the @"O"@ for octal is the letter O.)
The interpretation of integer literals that fall outside the range of
representable integer values is undefined.
For convenience and readability, underscore characters (@"_"@) are accepted
(and ignored) within integer literals.
\subsubsection*{Floating-point literals}
\begin{syntax}
float-literal:
["-"] ("0"\ldots"9") { "0"\ldots"9"||"_" } ["." { "0"\ldots"9"||"_" }]
[("e"||"E") ["+"||"-"] ("0"\ldots"9") { "0"\ldots"9"||"_" }]
\end{syntax}
Floating-point decimals consist in an integer part, a decimal part and
an exponent part. The integer part is a sequence of one or more
digits, optionally preceded by a minus sign. The decimal part is a
decimal point followed by zero, one or more digits.
The exponent part is the character @"e"@ or @"E"@ followed by an
optional @"+"@ or @"-"@ sign, followed by one or more digits.
The decimal part or the exponent part can be omitted but not both, to
avoid ambiguity with integer literals.
The interpretation of floating-point literals that fall outside the
range of representable floating-point values is undefined.
For convenience and readability, underscore characters (@"_"@) are accepted
(and ignored) within floating-point literals.
\subsubsection*{Character literals}
\label{s:characterliteral}
\begin{syntax}
char-literal:
"'" regular-char "'"
| "'" escape-sequence "'"
;
escape-sequence:
"\" ( "\" || '"' || "'" || "n" || "t" || "b" || "r" || space )
| "\" ("0"\ldots"9") ("0"\ldots"9") ("0"\ldots"9")
| "\x" ("0"\ldots"9"||"A"\ldots"F"||"a"\ldots"f")
("0"\ldots"9"||"A"\ldots"F"||"a"\ldots"f")
\end{syntax}
Character literals are delimited by @"'"@ (single quote) characters.
The two single quotes enclose either one character different from
@"'"@ and @'\'@, or one of the escape sequences below:
\begin{tableau}{|l|l|}{Sequence}{Character denoted}
\entree{"\\\\"}{backslash ("\\")}
\entree{"\\\""}{double quote ("\"")}
\entree{"\\'"}{single quote ("'")}
\entree{"\\n"}{linefeed (LF)}
\entree{"\\r"}{carriage return (CR)}
\entree{"\\t"}{horizontal tabulation (TAB)}
\entree{"\\b"}{backspace (BS)}
\entree{"\\"\var{space}}{space (SPC)}
\entree{"\\"\var{ddd}}{the character with ASCII code \var{ddd} in decimal}
\entree{"\\x"\var{hh}}{the character with ASCII code \var{hh} in hexadecimal}
\end{tableau}
\subsubsection*{String literals}
\label{s:stringliteral}
\begin{syntax}
string-literal:
'"' { string-character } '"'
;
string-character:
regular-string-char
| escape-sequence
| '\' newline { space || tab }
\end{syntax}
String literals are delimited by @'"'@ (double quote) characters.
The two double quotes enclose a sequence of either characters
different from @'"'@ and @'\'@, or escape sequences from the
table given above for character literals.
To allow splitting long string literals across lines, the sequence
"\\"\var{newline}~\var{spaces-or-tabs} (a backslash at the end of a line
followed by any number of spaces and horizontal tabulations at the
beginning of the next line) is ignored inside string literals.
The current implementation places practically no restrictions on the
length of string literals.
\subsubsection*{Naming labels}
\label{s:labelname}
To avoid ambiguities, naming labels in expressions cannot just be defined
syntactically as the sequence of the three tokens "~", @ident@ and
":", and have to be defined at the lexical level.
\begin{syntax}
label-name: lowercase-ident
;
label: "~" label-name ":"
;
optlabel: "?" label-name ":"
\end{syntax}
Naming labels come in two flavours: @label@ for normal arguments and
@optlabel@ for optional ones. They are simply distinguished by their
first character, either "~" or "?".
Despite @label@ and @optlabel@ being lexical entities in expressions,
their expansions @'~' label-name ':'@ and @'?' label-name ':'@ will be
used in grammars, for the sake of readability. Note also that inside
type expressions, this expansion can be taken literally, {\em i.e.}
there are really 3 tokens, with optional blanks between them.
\subsubsection*{Prefix and infix symbols}
%% || '`' lowercase-ident '`'
\begin{syntax}
infix-symbol:
('=' || '<' || '>' || '@' || '^' || '|' || '&' ||
'+' || '-' || '*' || '/' || '$' || '%') { operator-char }
| "#" {{ operator-char }}
;
prefix-symbol:
'!' { operator-char }
| ('?' || '~') {{ operator-char }}
;
operator-char:
'!' || '$' || '%' || '&' || '*' || '+' || '-' || '.' ||
'/' || ':' || '<' || '=' || '>' || '?' || '@' ||
'^' || '|' || '~'
\end{syntax}
Sequences of ``operator characters'', such as "<=>" or "!!",
are read as a single token from the @infix-symbol@ or @prefix-symbol@
class. These symbols are parsed as prefix and infix operators inside
expressions, but otherwise behave like normal identifiers.
%% Identifiers starting with a lowercase letter and enclosed
%% between backquote characters @'`' lowercase-ident '`'@ are also parsed
%% as infix operators.
\subsubsection*{Keywords}
The identifiers below are reserved as keywords, and cannot be employed
otherwise:
\begin{verbatim}
and as assert asr begin class
constraint do done downto else end
exception external false for fun function
functor if in include inherit initializer
land lazy let lor lsl lsr
lxor match method mod module mutable
new object of open or private
rec sig struct then to true
try type val virtual when while
with nonrec
\end{verbatim}
%
\goodbreak%
%
The following character sequences are also keywords:
%
%% FIXME the token >] is not used anywhere in the syntax
%
\begin{alltt}
" != # & && ' ( ) * + , -"
" -. -> . .. : :: := :> ; ;; <"
" <- = > >] >} ? [ [< [> [| ]"
" _ ` { {< | |] || } ~"
\end{alltt}
%
Note that the following identifiers are keywords of the Camlp4
extensions and should be avoided for compatibility reasons.
%
\begin{verbatim}
parser value $ $$ $: <: << >> ??
\end{verbatim}
\subsubsection*{Ambiguities}
Lexical ambiguities are resolved according to the ``longest match''
rule: when a character sequence can be decomposed into two tokens in
several different ways, the decomposition retained is the one with the
longest first token.
\subsubsection*{Line number directives}
\begin{syntax}
linenum-directive:
'#' {{"0" \ldots "9"}}
| '#' {{"0" \ldots "9"}} '"' { string-character } '"'
\end{syntax}
Preprocessors that generate OCaml source code can insert line number
directives in their output so that error messages produced by the
compiler contain line numbers and file names referring to the source
file before preprocessing, instead of after preprocessing.
A line number directive is composed of a @"#"@ (sharp sign), followed by
a positive integer (the source line number), optionally followed by a
character string (the source file name).
Line number directives are treated as blanks during lexical
analysis.
% FIXME spaces and tabs are allowed before and after the number
% FIXME ``string-character'' is inaccurate: everything is allowed except
% CR, LF, and doublequote; moreover, backslash escapes are not
% interpreted (especially backslash-doublequote)
% FIXME any number of random characters are allowed (and ignored) at the
% end of the line, except CR and LF.

View File

@ -0,0 +1,290 @@
\section{Module types (module specifications)}
\pdfsection{Module types (module specifications)}
%HEVEA\cutname{modtypes.html}
Module types are the module-level equivalent of type expressions: they
specify the general shape and type properties of modules.
\ikwd{sig\@\texttt{sig}}
\ikwd{end\@\texttt{end}}
\ikwd{functor\@\texttt{functor}}
\ikwd{with\@\texttt{with}}
\ikwd{val\@\texttt{val}}
\ikwd{external\@\texttt{external}}
\ikwd{type\@\texttt{type}}
\ikwd{exception\@\texttt{exception}}
\ikwd{class\@\texttt{class}}
\ikwd{module\@\texttt{module}}
\ikwd{open\@\texttt{open}}
\ikwd{include\@\texttt{include}}
\begin{syntax}
module-type:
modtype-path
| 'sig' { specification [';;'] } 'end'
| 'functor' '(' module-name ':' module-type ')' '->' module-type
| module-type 'with' mod-constraint { 'and' mod-constraint }
| '(' module-type ')'
;
mod-constraint:
'type' [type-params] typeconstr type-equation
| 'module' module-path '=' extended-module-path
;
%BEGIN LATEX
\end{syntax}
\begin{syntax}
%END LATEX
specification:
'val' value-name ':' typexpr
| 'external' value-name ':' typexpr '=' external-declaration
| type-definition
| 'exception' constr-decl
| class-specification
| classtype-definition
| 'module' module-name ':' module-type
| 'module' module-name { '(' module-name ':' module-type ')' }
':' module-type
| 'module' 'type' modtype-name
| 'module' 'type' modtype-name '=' module-type
| 'open' module-path
| 'include' module-type
\end{syntax}
\subsection{Simple module types}
The expression @modtype-path@ is equivalent to the module type bound
to the name @modtype-path@.
The expression @'(' module-type ')'@ denotes the same type as
@module-type@.
\subsection{Signatures}
\ikwd{sig\@\texttt{sig}}
\ikwd{end\@\texttt{end}}
Signatures are type specifications for structures. Signatures
@'sig' \ldots 'end'@ are collections of type specifications for value
names, type names, exceptions, module names and module type names. A
structure will match a signature if the structure provides definitions
(implementations) for all the names specified in the signature (and
possibly more), and these definitions meet the type requirements given
in the signature.
An optional @";;"@ is allowed after each specification in a
signature. It serves as a syntactic separator with no semantic
meaning.
\subsubsection*{Value specifications}
\ikwd{val\@\texttt{val}}
A specification of a value component in a signature is written
@'val' value-name ':' typexpr@, where @value-name@ is the name of the
value and @typexpr@ its expected type.
\ikwd{external\@\texttt{external}}
The form @'external' value-name ':' typexpr '=' external-declaration@
is similar, except that it requires in addition the name to be
implemented as the external function specified in @external-declaration@
(see chapter~\ref{c:intf-c}).
\subsubsection*{Type specifications}
\ikwd{type\@\texttt{type}}
A specification of one or several type components in a signature is
written @'type' typedef { 'and' typedef }@ and consists of a sequence
of mutually recursive definitions of type names.
Each type definition in the signature specifies an optional type
equation @'=' typexpr@ and an optional type representation
@'=' constr-decl \ldots@ or @'=' '{' field-decl \ldots '}'@.
The implementation of the type name in a matching structure must
be compatible with the type expression specified in the equation (if
given), and have the specified representation (if given). Conversely,
users of that signature will be able to rely on the type equation
or type representation, if given. More precisely, we have the
following four situations:
\begin{description}
\item[Abstract type: no equation, no representation.] ~ \\
Names that are defined as abstract types in a signature can be
implemented in a matching structure by any kind of type definition
(provided it has the same number of type parameters). The exact
implementation of the type will be hidden to the users of the
structure. In particular, if the type is implemented as a variant type
or record type, the associated constructors and fields will not be
accessible to the users; if the type is implemented as an
abbreviation, the type equality between the type name and the
right-hand side of the abbreviation will be hidden from the users of the
structure. Users of the structure consider that type as incompatible
with any other type: a fresh type has been generated.
\item[Type abbreviation: an equation @'=' typexpr@, no representation.] ~ \\
The type name must be implemented by a type compatible with @typexpr@.
All users of the structure know that the type name is
compatible with @typexpr@.
\item[New variant type or record type: no equation, a representation.] ~ \\
The type name must be implemented by a variant type or record type
with exactly the constructors or fields specified. All users of the
structure have access to the constructors or fields, and can use them
to create or inspect values of that type. However, users of the
structure consider that type as incompatible with any other type: a
fresh type has been generated.
\item[Re-exported variant type or record type: an equation,
a representation.] ~ \\
This case combines the previous two: the representation of the type is
made visible to all users, and no fresh type is generated.
\end{description}
\subsubsection*{Exception specification}
\ikwd{exception\@\texttt{exception}}
The specification @'exception' constr-decl@ in a signature requires the
matching structure to provide an exception with the name and arguments
specified in the definition, and makes the exception available to all
users of the structure.
\subsubsection*{Class specifications}
\ikwd{class\@\texttt{class}}
A specification of one or several classes in a signature is written
@'class' class-spec { 'and' class-spec }@ and consists of a sequence
of mutually recursive definitions of class names.
Class specifications are described more precisely in
section~\ref{s:class-spec}.
\subsubsection*{Class type specifications}
\ikwd{class\@\texttt{class}}
\ikwd{type\@\texttt{type}}
A specification of one or several classe types in a signature is
written @'class' 'type' classtype-def@ @{ 'and' classtype-def }@ and
consists of a sequence of mutually recursive definitions of class type
names. Class type specifications are described more precisely in
section~\ref{s:classtype}.
\subsubsection*{Module specifications}
\ikwd{module\@\texttt{module}}
A specification of a module component in a signature is written
@'module' module-name ':' module-type@, where @module-name@ is the
name of the module component and @module-type@ its expected type.
Modules can be nested arbitrarily; in particular, functors can appear
as components of structures and functor types as components of
signatures.
For specifying a module component that is a functor, one may write
\begin{center}
@'module' module-name '(' name_1 ':' module-type_1 ')'
\ldots '(' name_n ':' module-type_n ')'
':' module-type@
\end{center}
instead of
\begin{center}
@'module' module-name ':'
'functor' '(' name_1 ':' module-type_1 ')' '->' \ldots
'->' module-type@
\end{center}
\subsubsection*{Module type specifications}
\ikwd{type\@\texttt{type}}
\ikwd{module\@\texttt{module}}
A module type component of a signature can be specified either as a
manifest module type or as an abstract module type.
An abstract module type specification
@'module' 'type' modtype-name@ allows the name @modtype-name@ to be
implemented by any module type in a matching signature, but hides the
implementation of the module type to all users of the signature.
A manifest module type specification
@'module' 'type' modtype-name '=' module-type@
requires the name @modtype-name@ to be implemented by the module type
@module-type@ in a matching signature, but makes the equality between
@modtype-name@ and @module-type@ apparent to all users of the signature.
\subsubsection{Opening a module path}
\ikwd{open\@\texttt{open}}
The expression @'open' module-path@ in a signature does not specify
any components. It simply affects the parsing of the following items
of the signature, allowing components of the module denoted by
@module-path@ to be referred to by their simple names @name@ instead of
path accesses @module-path '.' name@. The scope of the @"open"@
stops at the end of the signature expression.
\subsubsection{Including a signature}
\ikwd{include\@\texttt{include}}
The expression @'include' module-type@ in a signature performs textual
inclusion of the components of the signature denoted by @module-type@.
It behaves as if the components of the included signature were copied
at the location of the @'include'@. The @module-type@ argument must
refer to a module type that is a signature, not a functor type.
\subsection{Functor types}
\ikwd{functor\@\texttt{functor}}
The module type expression
@'functor' '(' module-name ':' module-type_1 ')' '->' module-type_2@
is the type of functors (functions from modules to modules) that take
as argument a module of type @module-type_1@ and return as result a
module of type @module-type_2@. The module type @module-type_2@ can
use the name @module-name@ to refer to type components of the actual
argument of the functor. No restrictions are placed on the type of the
functor argument; in particular, a functor may take another functor as
argument (``higher-order'' functor).
\subsection{The "with" operator}
\ikwd{with\@\texttt{with}}
Assuming @module-type@ denotes a signature, the expression
@module-type 'with' mod-constraint@ @{ 'and' mod-constraint }@ denotes
the same signature where type equations have been added to some of the
type specifications, as described by the constraints following the
"with" keyword. The constraint @'type' [type-parameters] typeconstr
'=' typexpr@ adds the type equation @'=' typexpr@ to the specification
of the type component named @typeconstr@ of the constrained signature.
The constraint @'module' module-path '=' extended-module-path@ adds
type equations to all type components of the sub-structure denoted by
@module-path@, making them equivalent to the corresponding type
components of the structure denoted by @extended-module-path@.
For instance, if the module type name "S" is bound to the signature
\begin{verbatim}
sig type t module M: (sig type u end) end
\end{verbatim}
then "S with type t=int" denotes the signature
\begin{verbatim}
sig type t=int module M: (sig type u end) end
\end{verbatim}
and "S with module M = N" denotes the signature
\begin{verbatim}
sig type t module M: (sig type u=N.u end) end
\end{verbatim}
A functor taking two arguments of type "S" that share their "t" component
is written
\begin{verbatim}
functor (A: S) (B: S with type t = A.t) ...
\end{verbatim}
Constraints are added left to right. After each constraint has been
applied, the resulting signature must be a subtype of the signature
before the constraint was applied. Thus, the @'with'@ operator can
only add information on the type components of a signature, but never
remove information.

View File

@ -0,0 +1,231 @@
\section{Module\label{s:module-expr} expressions (module implementations)}
\pdfsection{Module expressions (module implementations)}
%HEVEA\cutname{modules.html}
Module expressions are the module-level equivalent of value
expressions: they evaluate to modules, thus providing implementations
for the specifications expressed in module types.
\ikwd{struct\@\texttt{struct}}
\ikwd{end\@\texttt{end}}
\ikwd{functor\@\texttt{functor}}
\ikwd{let\@\texttt{let}}
\ikwd{external\@\texttt{external}}
\ikwd{type\@\texttt{type}}
\ikwd{exception\@\texttt{exception}}
\ikwd{class\@\texttt{class}}
\ikwd{module\@\texttt{module}}
\ikwd{open\@\texttt{open}}
\ikwd{include\@\texttt{include}}
\begin{syntax}
module-expr:
module-path
| 'struct' [ module-items ] 'end'
| 'functor' '(' module-name ':' module-type ')' '->' module-expr
| module-expr '(' module-expr ')'
| '(' module-expr ')'
| '(' module-expr ':' module-type ')'
;
module-items:
{';;'} ( definition || expr ) { {';;'} ( definition || ';;' expr) } {';;'}
;
%\end{syntax} \begin{syntax}
definition:
'let' ['rec'] let-binding { 'and' let-binding }
| 'external' value-name ':' typexpr '=' external-declaration
| type-definition
| exception-definition
| class-definition
| classtype-definition
| 'module' module-name { '(' module-name ':' module-type ')' }
[ ':' module-type ] \\ '=' module-expr
| 'module' 'type' modtype-name '=' module-type
| 'open' module-path
| 'include' module-expr
\end{syntax}
\subsection{Simple module expressions}
The expression @module-path@ evaluates to the module bound to the name
@module-path@.
The expression @'(' module-expr ')'@ evaluates to the same module as
@module-expr@.
The expression @'(' module-expr ':' module-type ')'@ checks that the
type of @module-expr@ is a subtype of @module-type@, that is, that all
components specified in @module-type@ are implemented in
@module-expr@, and their implementation meets the requirements given
in @module-type@. In other terms, it checks that the implementation
@module-expr@ meets the type specification @module-type@. The whole
expression evaluates to the same module as @module-expr@, except that
all components not specified in @module-type@ are hidden and can no
longer be accessed.
\subsection{Structures}
\ikwd{struct\@\texttt{struct}}
\ikwd{end\@\texttt{end}}
Structures @'struct' \ldots 'end'@ are collections of definitions for
value names, type names, exceptions, module names and module type
names. The definitions are evaluated in the order in which they appear
in the structure. The scopes of the bindings performed by the
definitions extend to the end of the structure. As a consequence, a
definition may refer to names bound by earlier definitions in the same
structure.
For compatibility with toplevel phrases (chapter~\ref{c:camllight}),
optional @";;"@ are allowed after and before each definition in a structure. These
@";;"@ have no semantic meanings. Similarly, an @expr@ preceded by ";;" is allowed as
a component of a structure. It is equivalent to @'let' '_' '=' expr@, i.e. @expr@ is
evaluated for its side-effects but is not bound to any identifier. If @expr@ is
the first component of a structure, the preceding ";;" can be omitted.
\subsubsection*{Value definitions}
\ikwd{let\@\texttt{let}}
A value definition @'let' ['rec'] let-binding { 'and' let-binding }@
bind value names in the same way as a @'let' \ldots 'in' \ldots@ expression
(see section~\ref{s:localdef}). The value names appearing in the
left-hand sides of the bindings are bound to the corresponding values
in the right-hand sides.
\ikwd{external\@\texttt{external}}
A value definition @'external' value-name ':' typexpr '=' external-declaration@
implements @value-name@ as the external function specified in
@external-declaration@ (see chapter~\ref{c:intf-c}).
\subsubsection*{Type definitions}
\ikwd{type\@\texttt{type}}
A definition of one or several type components is written
@'type' typedef { 'and' typedef }@ and consists of a sequence
of mutually recursive definitions of type names.
\subsubsection*{Exception definitions}
\ikwd{exception\@\texttt{exception}}
Exceptions are defined with the syntax @'exception' constr-decl@
or @'exception' constr-name '=' constr@.
\subsubsection*{Class definitions}
\ikwd{class\@\texttt{class}}
A definition of one or several classes is written @'class'
class-binding { 'and' class-binding }@ and consists of a sequence of
mutually recursive definitions of class names. Class definitions are
described more precisely in section~\ref{s:classdef}.
\subsubsection*{Class type definitions}
\ikwd{class\@\texttt{class}}
\ikwd{type\@\texttt{type}}
A definition of one or several classes is written
@'class' 'type' classtype-def { 'and' classtype-def }@ and consists of
a sequence of mutually recursive definitions of class type names.
Class type definitions are described more precisely in
section~\ref{s:classtype}.
\subsubsection*{Module definitions}
\ikwd{module\@\texttt{module}}
The basic form for defining a module component is
@'module' module-name '=' module-expr@, which evaluates @module-expr@ and binds
the result to the name @module-name@.
One can write
\begin{center}
@'module' module-name ':' module-type '=' module-expr@
\end{center}
instead of
\begin{center}
@'module' module-name '=' '(' module-expr ':' module-type ')'@.
\end{center}
Another derived form is
\begin{center}
@'module' module-name '(' name_1 ':' module-type_1 ')' \ldots
'(' name_n ':' module-type_n ')' '=' module-expr@
\end{center}
which is equivalent to
\begin{center}
@'module' module-name '='
'functor' '(' name_1 ':' module-type_1 ')' '->' \ldots
'->' module-expr@
\end{center}
\subsubsection*{Module type definitions}
\ikwd{type\@\texttt{type}}
\ikwd{module\@\texttt{module}}
A definition for a module type is written
@'module' 'type' modtype-name '=' module-type@.
It binds the name @modtype-name@ to the module type denoted by the
expression @module-type@.
\subsubsection*{Opening a module path}
\ikwd{open\@\texttt{open}}
The expression @'open' module-path@ in a structure does not define any
components nor perform any bindings. It simply affects the parsing of
the following items of the structure, allowing components of the
module denoted by @module-path@ to be referred to by their simple names
@name@ instead of path accesses @module-path '.' name@. The scope of
the @"open"@ stops at the end of the structure expression.
\subsubsection*{Including the components of another structure}
\ikwd{include\@\texttt{include}}
The expression @'include' module-expr@ in a structure re-exports in
the current structure all definitions of the structure denoted by
@module-expr@. For instance, if the identifier "S" is bound to the
module
\begin{verbatim}
struct type t = int let x = 2 end
\end{verbatim}
the module expression
\begin{verbatim}
struct include S let y = (x + 1 : t) end
\end{verbatim}
is equivalent to the module expression
\begin{verbatim}
struct type t = S.t let x = S.x let y = (x + 1 : t) end
\end{verbatim}
The difference between @'open'@ and @'include'@ is that @'open'@
simply provides short names for the components of the opened
structure, without defining any components of the current structure,
while @'include'@ also adds definitions for the components of the
included structure.
\subsection{Functors}
\subsubsection*{Functor definition}
\ikwd{functor\@\texttt{functor}}
The expression @'functor' '(' module-name ':' module-type ')' '->'
module-expr@ evaluates to a functor that takes as argument modules of
the type @module-type_1@, binds @module-name@ to these modules,
evaluates @module-expr@ in the extended environment, and returns the
resulting modules as results. No restrictions are placed on the type of the
functor argument; in particular, a functor may take another functor as
argument (``higher-order'' functor).
\subsubsection*{Functor application}
The expression @module-expr_1 '(' module-expr_2 ')'@ evaluates
@module-expr_1@ to a functor and @module-expr_2@ to a module, and
applies the former to the latter. The type of @module-expr_2@ must
match the type expected for the arguments of the functor @module-expr_1@.

View File

@ -0,0 +1,144 @@
\section{Names} \label{s:names}
\pdfsection{Names}
%HEVEA\cutname{names.html}
Identifiers are used to give names to several classes of language
objects and refer to these objects by name later:
\begin{itemize}
\item value names (syntactic class @value-name@),
\item value constructors and exception constructors (class @constr-name@),
\item labels (@label-name@, defined in section~\ref{s:labelname}),
\item polymorphic variant tags (@tag-name@),
\item type constructors (@typeconstr-name@),
\item record fields (@field-name@),
\item class names (@class-name@),
\item method names (@method-name@),
\item instance variable names (@inst-var-name@),
\item module names (@module-name@),
\item module type names (@modtype-name@).
\end{itemize}
These eleven name spaces are distinguished both by the context and by the
capitalization of the identifier: whether the first letter of the
identifier is in lowercase (written @lowercase-ident@ below) or in
uppercase (written @capitalized-ident@). Underscore is considered a
lowercase letter for this purpose.
\ikwd{false\@\texttt{false}}
\ikwd{true\@\texttt{true}}
\subsubsection*{Naming objects}
\begin{syntax}
value-name:
lowercase-ident
| '(' operator-name ')'
;
operator-name:
prefix-symbol || infix-op
;
infix-op:
infix-symbol
| '*' || '+' || '-' || '-.' || '=' || '!=' || '<' || '>' || 'or' || '||'
|| '&' || '&&' || ':='
| 'mod' || 'land' || 'lor' || 'lxor' || 'lsl' || 'lsr' || 'asr'
;
constr-name:
capitalized-ident
;
tag-name:
capitalized-ident
;
typeconstr-name:
lowercase-ident
;
field-name:
lowercase-ident
;
module-name:
capitalized-ident
;
modtype-name:
ident
;
class-name:
lowercase-ident
;
inst-var-name:
lowercase-ident
;
method-name:
lowercase-ident
\end{syntax}
As shown above, prefix and infix symbols as well as some keywords can
be used as value names, provided they are written between parentheses.
The capitalization rules are summarized in the table below.
\begin{tableau}{|l|l|}{Name space}{Case of first letter}
\entree{Values}{lowercase}
\entree{Constructors}{uppercase}
\entree{Labels}{lowercase}
\entree{Polymorphic variant tags}{uppercase}
\entree{Exceptions}{uppercase}
\entree{Type constructors}{lowercase}
\entree{Record fields}{lowercase}
\entree{Classes}{lowercase}
\entree{Instance variables}{lowercase}
\entree{Methods}{lowercase}
\entree{Modules}{uppercase}
\entree{Module types}{any}
\end{tableau}
{\it Note on polymorphic variant tags:\/} the current implementation accepts
lowercase variant tags in addition to capitalized variant tags, but we
suggest you avoid lowercase variant tags for portability and
compatibility with future OCaml versions.
\subsubsection*{Referring to named objects}
\begin{syntax}
value-path:
[ module-path '.' ] value-name
;
constr:
[ module-path '.' ] constr-name
;
typeconstr:
[ extended-module-path '.' ] typeconstr-name
;
field:
[ module-path '.' ] field-name
;
modtype-path:
[ extended-module-path '.' ] modtype-name
;
class-path:
[ module-path '.' ] class-name
;
classtype-path:
[ extended-module-path '.' ] class-name
;
module-path:
module-name { '.' module-name }
;
extended-module-path:
extended-module-name { '.' extended-module-name }
;
extended-module-name:
module-name { '(' extended-module-path ')' }
\end{syntax}
A named object can be referred to either by its name (following the
usual static scoping rules for names) or by an access path @prefix '.' name@,
where @prefix@ designates a module and @name@ is the name of an object
defined in that module. The first component of the path, @prefix@, is
either a simple module name or an access path @name_1 '.' name_2 \ldots@,
in case the defining module is itself nested inside other modules.
For referring to type constructors, module types, or class types,
the @prefix@ can
also contain simple functor applications (as in the syntactic class
@extended-module-path@ above) in case the defining module is the
result of a functor application.
Label names, tag names, method names and instance variable names need
not be qualified: the former three are global labels, while the latter
are local to a class.

View File

@ -0,0 +1,161 @@
\section{Patterns}
\pdfsection{Patterns}
\ikwd{as\@\texttt{as}}
%HEVEA\cutname{patterns.html}
\begin{syntax}
pattern:
value-name
| '_'
| constant
| pattern 'as' value-name
| '(' pattern ')'
| '(' pattern ':' typexpr ')'
| pattern '|' pattern
| constr pattern
| "`"tag-name pattern
| "#"typeconstr
| pattern {{ ',' pattern }}
| '{' field '=' pattern { ';' field '=' pattern } [ ';' ] '}'
| '[' pattern { ';' pattern } [ ';' ] ']'
| pattern '::' pattern
| '[|' pattern { ';' pattern } [ ';' ] '|]'
| char-literal '..' char-literal
\end{syntax}
The table below shows the relative precedences and associativity of
operators and non-closed pattern constructions. The constructions with
higher precedences come first.
\ikwd{as\@\texttt{as}}
\begin{tableau}{|l|l|}{Operator}{Associativity}
\entree{".."}{--}
\entree{"lazy" (see section~\ref{s:lazypat})}{--}
\entree{Constructor application, Tag application}{right}
\entree{"::"}{right}
\entree{","}{--}
\entree{"|"}{left}
\entree{"as"}{--}
\end{tableau}
Patterns are templates that allow selecting data structures of a
given shape, and binding identifiers to components of the data
structure. This selection operation is called pattern matching; its
outcome is either ``this value does not match this pattern'', or
``this value matches this pattern, resulting in the following bindings
of names to values''.
\subsubsection*{Variable patterns}
A pattern that consists in a value name matches any value,
binding the name to the value. The pattern @"_"@ also matches
any value, but does not bind any name.
Patterns are {\em linear\/}: a variable cannot be bound several times by
a given pattern. In particular, there is no way to test for equality
between two parts of a data structure using only a pattern (but
@"when"@ guards can be used for this purpose).
\subsubsection*{Constant patterns}
A pattern consisting in a constant matches the values that
are equal to this constant.
%% FIXME for negative numbers, blanks are allowed between the minus
%% sign and the first digit.
\subsubsection*{Alias patterns}
\ikwd{as\@\texttt{as}}
The pattern @pattern_1 "as" value-name@ matches the same values as
@pattern_1@. If the matching against @pattern_1@ is successful,
the name @value-name@ is bound to the matched value, in addition to the
bindings performed by the matching against @pattern_1@.
\subsubsection*{Parenthesized patterns}
The pattern @"(" pattern_1 ")"@ matches the same values as
@pattern_1@. A type constraint can appear in a
parenthesized pattern, as in @"(" pattern_1 ":" typexpr ")"@. This
constraint forces the type of @pattern_1@ to be compatible with
@typexpr@.
\subsubsection*{``Or'' patterns}
The pattern @pattern_1 "|" pattern_2@ represents the logical ``or'' of
the two patterns @pattern_1@ and @pattern_2@. A value matches
@pattern_1 "|" pattern_2@ if it matches @pattern_1@ or
@pattern_2@. The two sub-patterns @pattern_1@ and @pattern_2@
must bind exactly the same identifiers to values having the same types.
Matching is performed from left to right.
More precisely,
in case some value~$v$ matches @pattern_1 "|" pattern_2@, the bindings
performed are those of @pattern_1@ when $v$ matches @pattern_1@.
Otherwise, value~$v$ matches @pattern_2@ whose bindings are performed.
\subsubsection*{Variant patterns}
The pattern @constr '(' pattern_1 ',' \ldots ',' pattern_n ')'@ matches
all variants whose
constructor is equal to @constr@, and whose arguments match
@pattern_1 \ldots pattern_n@. It is a type error if $n$ is not the
number of arguments expected by the constructor.
The pattern @constr '_'@ matches all variants whose constructor is
@constr@.
The pattern @pattern_1 "::" pattern_2@ matches non-empty lists whose
heads match @pattern_1@, and whose tails match @pattern_2@.
The pattern @"[" pattern_1 ";" \ldots ";" pattern_n "]"@ matches lists
of length $n$ whose elements match @pattern_1@ \ldots @pattern_n@,
respectively. This pattern behaves like
@pattern_1 "::" \ldots "::" pattern_n "::" "[]"@.
\subsubsection*{Polymorphic variant patterns}
The pattern @"`"tag-name pattern_1@ matches all polymorphic variants
whose tag is equal to @tag-name@, and whose argument matches
@pattern_1@.
\subsubsection*{Polymorphic variant abbreviation patterns}
If the type @["('a,'b,"\ldots")"] typeconstr = "[" "`"tag-name_1 typexpr_1 "|"
\ldots "|" "`"tag-name_n typexpr_n"]"@ is defined, then the pattern @"#"typeconstr@
is a shorthand for the following or-pattern:
@"(" "`"tag-name_1"(_" ":" typexpr_1")" "|" \ldots "|" "`"tag-name_n"(_"
":" typexpr_n"))"@. It matches all values of type @"[<" typeconstr "]"@.
\subsubsection*{Tuple patterns}
The pattern @pattern_1 "," \ldots "," pattern_n@ matches $n$-tuples
whose components match the patterns @pattern_1@ through @pattern_n@. That
is, the pattern matches the tuple values $(v_1, \ldots, v_n)$ such that
@pattern_i@ matches $v_i$ for \fromoneto{i}{n}.
\subsubsection*{Record patterns}
The pattern @"{" field_1 "=" pattern_1 ";" \ldots ";" field_n "="
pattern_n "}"@ matches records that define at least the fields
@field_1@ through @field_n@, and such that the value associated to
@field_i@ matches the pattern @pattern_i@, for \fromoneto{i}{n}.
The record value can define more fields than @field_1@ \ldots
@field_n@; the values associated to these extra fields are not taken
into account for matching.
\subsubsection*{Array patterns}
The pattern @"[|" pattern_1 ";" \ldots ";" pattern_n "|]"@
matches arrays of length $n$ such that the $i$-th array element
matches the pattern @pattern_i@, for \fromoneto{i}{n}.
\subsubsection*{Range patterns}
The pattern
@"'" @c@ "'" ".." "'" @d@ "'"@ is a shorthand for the pattern
\begin{center}
@"'" @c@ "'" "|" "'" @c@_1 "'" "|" "'" @c@_2 "'" "|" \ldots
"|" "'" @c@_n "'" "|" "'" @d@ "'"@
\end{center}
where \nth{c}{1}, \nth{c}{2}, \ldots, \nth{c}{n} are the characters
that occur between \var{c} and \var{d} in the ASCII character set. For
instance, the pattern "'0'"@'..'@"'9'" matches all characters that are digits.

View File

@ -0,0 +1,48 @@
\chapter{The OCaml language} \label{c:refman}
\pdfchapterfold{-12}{Reference manual for the OCaml language}
%HEVEA\cutname{language.html}
%better html output that way, sniff.
%HEVEA\subsection*{Foreword}
%BEGIN LATEX
\section*{Foreword}
%END LATEX
This document is intended as a reference manual for the OCaml
language. It lists the language constructs, and gives their precise
syntax and informal semantics. It is by no means a tutorial
introduction to the language: there is not a single example. A good
working knowledge of OCaml is assumed.
No attempt has been made at mathematical rigor: words are employed
with their intuitive meaning, without further definition. As a
consequence, the typing rules have been left out, by lack of the
mathematical framework required to express them, while they are
definitely part of a full formal definition of the language.
\subsection*{Notations}
The syntax of the language is given in BNF-like notation. Terminal
symbols are set in typewriter font (@'like' 'this'@).
Non-terminal symbols are set in italic font (@like that@).
Square brackets @[\ldots]@ denote optional components. Curly brackets
@{\ldots}@ denotes zero, one or several repetitions of the enclosed
components. Curly brackets with a trailing plus sign @{{\ldots}}@
denote one or several repetitions of the enclosed components.
Parentheses @(\ldots)@ denote grouping.
%HEVEA\cutdef{section}
\input{lex}
\input{values}
\input{names}
\input{types}
\input{const}
\input{patterns}
\input{expr}
\input{typedecl}
\input{classes}
\input{modtypes}
\input{modules}
\input{compunit}
%HEVEA\cutend

View File

@ -0,0 +1,209 @@
\section{Type and exception definitions}
%HEVEA\cutname{typedecl.html}%
\pdfsection{Type and exception definitions}
\subsection{Type definitions}
\label{s:type-defs}
Type definitions bind type constructors to data types: either
variant types, record types, type abbreviations, or abstract data
types. They also bind the value constructors and record fields
associated with the definition.
\ikwd{type\@\texttt{type}}
\begin{syntax}
type-definition:
'type' ['nonrec'] typedef { 'and' typedef }
;
typedef:
[type-params] typeconstr-name type-information
;
type-information:
[type-equation] [type-representation] { type-constraint }
;
type-equation:
'=' typexpr
;
type-representation:
'=' ['|'] constr-decl { '|' constr-decl }
| '=' '{' field-decl { ';' field-decl } [';'] '}'
;
type-params:
type-param
| '(' type-param { "," type-param } ')'
;
type-param:
[variance] "'" ident
;
variance:
'+'
| '-'
;
constr-decl:
(constr-name || '()') [ 'of' typexpr { '*' typexpr } ]
;
field-decl:
['mutable'] field-name ':' poly-typexpr
;
type-constraint:
'constraint' "'" ident '=' typexpr
\end{syntax}
\ikwd{mutable\@\texttt{mutable}}
\ikwd{constraint\@\texttt{constraint}}
Type definitions are introduced by the "type" keyword, and
consist in one or several simple definitions, possibly mutually
recursive, separated by the "and" keyword. Each simple definition
defines one type constructor.
A simple definition consists in a lowercase identifier, possibly
preceded by one or several type parameters, and followed by an
optional type equation, then an optional type representation, and then
a constraint clause. The identifier is the name of the type
constructor being defined.
In the right-hand side of type definitions, references to one of the
type constructor name being defined are considered as recursive,
unless "type" is followed by "nonrec". The "nonrec" keyword was
introduced in OCaml 4.02.2.
The optional type parameters are either one type variable @"'" ident@,
for type constructors with one parameter, or a list of type variables
@"('"ident_1,\ldots,"'"ident_n")"@, for type constructors with several
parameters. Each type parameter may be prefixed by a variance
constraint @"+"@ (resp. @"-"@) indicating that the parameter is
covariant (resp. contravariant). These type parameters can appear in
the type expressions of the right-hand side of the definition,
optionally restricted by a variance constraint ; {\em i.e.\/} a
covariant parameter may only appear on the right side of a functional
arrow (more precisely, follow the left branch of an even number of
arrows), and a contravariant parameter only the left side (left branch of
an odd number of arrows). If the type has a representation or
an equation, and the parameter is free ({\em i.e.\/} not bound via a
type constraint to a constructed type), its variance constraint is
checked but subtyping {\em etc.\/} will use the inferred variance of the
parameter, which may be less restrictive; otherwise ({\em i.e.\/} for abstract
types or non-free parameters), the variance must be given explicitly,
and the parameter is invariant if no variance is given.
The optional type equation @'=' typexpr@ makes the defined type
equivalent to the type expression @typexpr@:
one can be substituted for the other during typing.
If no type equation is given, a new type is generated: the defined type
is incompatible with any other type.
The optional type representation describes the data structure
representing the defined type, by giving the list of associated
constructors (if it is a variant type) or associated fields (if it is
a record type). If no type representation is given, nothing is
assumed on the structure of the type besides what is stated in the
optional type equation.
The type representation @'=' ['|'] constr-decl { '|' constr-decl }@
describes a variant type. The constructor declarations
@constr-decl_1, \ldots, constr-decl_n@ describe the constructors
associated to this variant type. The constructor
declaration @constr-name 'of' typexpr_1 '*' \ldots '*' typexpr_n@
declares the name @constr-name@ as a non-constant constructor, whose
arguments have types @typexpr_1@ \ldots @typexpr_n@.
The constructor declaration @constr-name@
declares the name @constr-name@ as a constant
constructor. Constructor names must be capitalized.
The type representation @'=' '{' field-decl { ';' field-decl } [';'] '}'@
describes a record type. The field declarations @field-decl_1, \ldots,
field-decl_n@ describe the fields associated to this record type.
The field declaration @field-name ':' poly-typexpr@ declares
@field-name@ as a field whose argument has type @poly-typexpr@.
The field declaration @'mutable' field-name ':' poly-typexpr@
\ikwd{mutable\@\texttt{mutable}}
behaves similarly; in addition, it allows physical modification of
this field.
Immutable fields are covariant, mutable fields are non-variant.
Both mutable and immutable fields may have a explicitly polymorphic
types. The polymorphism of the contents is statically checked whenever
a record value is created or modified. Extracted values may have their
types instantiated.
The two components of a type definition, the optional equation and the
optional representation, can be combined independently, giving
rise to four typical situations:
\begin{description}
\item[Abstract type: no equation, no representation.] ~\\
When appearing in a module signature, this definition specifies
nothing on the type constructor, besides its number of parameters:
its representation is hidden and it is assumed incompatible with any
other type.
\item[Type abbreviation: an equation, no representation.] ~\\
This defines the type constructor as an abbreviation for the type
expression on the right of the @'='@ sign.
\item[New variant type or record type: no equation, a representation.] ~\\
This generates a new type constructor and defines associated
constructors or fields, through which values of that type can be
directly built or inspected.
\item[Re-exported variant type or record type: an equation,
a representation.] ~\\
In this case, the type constructor is defined as an abbreviation for
the type expression given in the equation, but in addition the
constructors or fields given in the representation remain attached to
the defined type constructor. The type expression in the equation part
must agree with the representation: it must be of the same kind
(record or variant) and have exactly the same constructors or fields,
in the same order, with the same arguments.
\end{description}
The type variables appearing as type parameters can optionally be
prefixed by "+" or "-" to indicate that the type constructor is
covariant or contravariant with respect to this parameter. This
variance information is used to decide subtyping relations when
checking the validity of @":>"@ coercions (see section \ref{s:coercions}).
For instance, "type +'a t" declares "t" as an abstract type that is
covariant in its parameter; this means that if the type $\tau$ is a
subtype of the type $\sigma$, then $\tau " t"$ is a subtype of $\sigma
" t"$. Similarly, "type -'a t" declares that the abstract type "t" is
contravariant in its parameter: if $\tau$ is a subtype of $\sigma$, then
$\sigma " t"$ is a subtype of $\tau " t"$. If no "+" or "-" variance
annotation is given, the type constructor is assumed non-variant in the
corresponding parameter. For instance, the abstract type declaration
"type 'a t" means that $\tau " t"$ is neither a subtype nor a
supertype of $\sigma " t"$ if $\tau$ is subtype of $\sigma$.
The variance indicated by the "+" and "-" annotations on parameters
is enforced only for abstract and private types, or when there are
type constraints.
Otherwise, for abbreviations, variant and record types without type
constraints, the variance properties of the type constructor
are inferred from its definition, and the variance annotations are
only checked for conformance with the definition.
\ikwd{constraint\@\texttt{constraint}}
The construct @ 'constraint' "'" ident '=' typexpr @ allows the
specification of
type parameters. Any actual type argument corresponding to the type
parameter @ident@ has to be an instance of @typexpr@ (more precisely,
@ident@ and @typexpr@ are unified). Type variables of @typexpr@ can
appear in the type equation and the type declaration.
\subsection{Exception definitions} \label{s:excdef}
\ikwd{exception\@\texttt{exception}}
\begin{syntax}
exception-definition:
'exception' constr-name [ 'of' typexpr { '*' typexpr } ]
| 'exception' constr-name '=' constr
\end{syntax}
Exception definitions add new constructors to the built-in variant
type \verb"exn" of exception values. The constructors are declared as
for a definition of a variant type.
The form @'exception' constr-name ['of' typexpr {'*' typexpr}]@
generates a new exception, distinct from all other exceptions in the system.
The form @'exception' constr-name '=' constr@
gives an alternate name to an existing exception.

View File

@ -0,0 +1,233 @@
\section{Type expressions}
\pdfsection{Type expressions}
%HEVEA\cutname{types.html}
\ikwd{as\@\texttt{as}}
\begin{syntax}
typexpr:
"'" ident
| "_"
| '(' typexpr ')'
| [['?']label-name':'] typexpr '->' typexpr
| typexpr {{ '*' typexpr }}
| typeconstr
| typexpr typeconstr
| '(' typexpr { ',' typexpr } ')' typeconstr
| typexpr 'as' "'" ident
| polymorphic-variant-type
| '<' ['..'] '>'
| '<' method-type { ';' method-type } [';' || ';' '..'] '>'
| '#' class-path
| typexpr '#' class-path
| '(' typexpr { ',' typexpr } ')' '#' class-path
;
poly-typexpr:
typexpr
| {{ "'" ident }} '.' typexpr
;
method-type:
method-name ':' poly-typexpr
\end{syntax}
The table below shows the relative precedences and associativity of
operators and non-closed type constructions. The constructions with
higher precedences come first.
\ikwd{as\@\texttt{as}}
\begin{tableau}{|l|l|}{Operator}{Associativity}
\entree{Type constructor application}{--}
\entree{"#"}{--}
\entree{"*"}{--}
\entree{"->"}{right}
\entree{"as"}{--}
\end{tableau}
Type expressions denote types in definitions of data types as well as
in type constraints over patterns and expressions.
\subsubsection*{Type variables}
The type expression @"'" ident@ stands for the type variable named
@ident@. The type expression @"_"@ stands for an anonymous type variable.
In data type definitions, type variables are names for the
data type parameters. In type constraints, they represent unspecified
types that can be instantiated by any type to satisfy the type
constraint. In general the scope of a named type variable is the
whole top-level phrase where it appears, and it can only be
generalized when leaving
this scope. Anonymous variables have no such restriction.
In the following cases, the scope of named type variables is
restricted to the type expression where they appear: 1) for universal
(explicitly polymorphic) type variables; 2) for type variables that
only appear in public method specifications (as those variables will
be made universal, as described in section~\ref{sec-methspec});
3) for variables used as aliases, when the type they are aliased to
would be invalid in the scope of the enclosing definition ({\it i.e.}
when it contains free universal type variables, or locally
defined types.)
\subsubsection*{Parenthesized types}
The type expression @"(" typexpr ")"@ denotes the same type as
@typexpr@.
\subsubsection*{Function types}
The type expression @typexpr_1 '->' typexpr_2@ denotes the type of
functions mapping arguments of type @typexpr_1@ to results of type
@typexpr_2@.
@label-name ':' typexpr_1 '->' typexpr_2@ denotes the same function type, but
the argument is labeled @label@.
@'?' label-name ':' typexpr_1 '->' typexpr_2@ denotes the type of functions
mapping an optional labeled argument of type @typexpr_1@ to results of
type @typexpr_2@. That is, the physical type of the function will be
@typexpr_1 "option" '->' typexpr_2@.
\subsubsection*{Tuple types}
The type expression @typexpr_1 '*' \ldots '*' typexpr_n@
denotes the type of tuples whose elements belong to types @typexpr_1,
\ldots typexpr_n@ respectively.
\subsubsection*{Constructed types}
Type constructors with no parameter, as in @typeconstr@, are type
expressions.
The type expression @typexpr typeconstr@, where @typeconstr@ is a type
constructor with one parameter, denotes the application of the unary type
constructor @typeconstr@ to the type @typexpr@.
The type expression @(typexpr_1,\ldots,typexpr_n) typeconstr@, where
@typeconstr@ is a type constructor with $n$ parameters, denotes the
application of the $n$-ary type constructor @typeconstr@ to the types
@typexpr_1@ through @typexpr_n@.
\subsubsection*{Aliased and recursive types}
\ikwd{as\@\texttt{as}}
The type expression @typexpr 'as' "'" ident@ denotes the same type as
@typexpr@, and also binds the type variable @ident@ to type @typexpr@ both
in @typexpr@ and in other types. In general the scope of an alias is
the same as for a named type variable, and covers the whole enclosing
definition. If the type variable
@ident@ actually occurs in @typexpr@, a recursive type is created. Recursive
types for which there exists a recursive path that does not contain
an object or polymorphic variant type constructor are rejected, except
when the "-rectypes" mode is selected.
If @"'" ident@ denotes an explicit polymorphic variable, and @typexpr@
denotes either an object or polymorphic variant type, the row variable
of @typexpr@ is captured by @"'" ident@, and quantified upon.
\subsubsection*{Polymorphic variant types}
\begin{syntax}
polymorphic-variant-type:
'[' tag-spec-first { '|' tag-spec } ']'
| '[>' [ tag-spec ] { '|' tag-spec } ']'
| '[<' ['|'] tag-spec-full { '|' tag-spec-full }
[ '>' {{ '`'tag-name }} ] ']'
;
%\end{syntax} \begin{syntax}
tag-spec-first:
'`'tag-name [ 'of' typexpr ]
| [ typexpr ] '|' tag-spec
;
tag-spec:
'`'tag-name [ "of" typexpr ]
| typexpr
;
tag-spec-full:
'`'tag-name [ "of" ['&'] typexpr { '&' typexpr } ]
| typexpr
\end{syntax}
Polymorphic variant types describe the values a polymorphic variant
may take.
The first case is an exact variant type: all possible tags are
known, with their associated types, and they can all be present.
Its structure is fully known.
The second case is an open variant type, describing a polymorphic
variant value: it gives the list of all tags the value could take,
with their associated types. This type is still compatible with a
variant type containing more tags. A special case is the unknown
type, which does not define any tag, and is compatible with any
variant type.
The third case is a closed variant type. It gives information about
all the possible tags and their associated types, and which tags are
known to potentially appear in values. The exact variant type (first
case) is
just an abbreviation for a closed variant type where all possible tags
are also potentially present.
In all three cases, tags may be either specified directly in the
@'`'tag-name ["of" typexpr]@ form, or indirectly through a type
expression, which must expand to an
exact variant type, whose tag specifications are inserted in its
place.
Full specifications of variant tags are only used for non-exact closed
types. They can be understood as a conjunctive type for the argument:
it is intended to have all the types enumerated in the
specification.
Such conjunctive constraints may be unsatisfiable. In such a case the
corresponding tag may not be used in a value of this type. This
does not mean that the whole type is not valid: one can still use
other available tags.
Conjunctive constraints are mainly intended as output from the type
checker. When they are used in source programs, unsolvable constraints
may cause early failures.
\subsubsection*{Object types}
An object type
@'<' [method-type { ';' method-type }] '>'@
is a record of method types.
Each method may have an explicit polymorphic type: @{{ "'" ident }}
'.' typexpr@. Explicit polymorphic variables have a local scope, and
an explicit polymorphic type can only be unified to an
equivalent one, where only the order and names of polymorphic
variables may change.
The type @'<' {method-type ';'} '..' '>'@ is the
type of an object whose method names and types are described by
@method-type_1, \ldots, method-type_n@, and possibly some other
methods represented by the ellipsis. This ellipsis actually is
a special kind of type variable (called {\em row variable} in the
literature) that stands for any number of extra method types.
\subsubsection*{\#-types}
\label{s:sharp-types}
The type @'#' class-path@ is a special kind of abbreviation. This
abbreviation unifies with the type of any object belonging to a subclass
of class @class-path@.
%
It is handled in a special way as it usually hides a type variable (an
ellipsis, representing the methods that may be added in a subclass).
In particular, it vanishes when the ellipsis gets instantiated.
%
Each type expression @'#' class-path@ defines a new type variable, so
type @'#' class-path '->' '#' class-path@ is usually not the same as
type @('#' class-path 'as' "'" ident) '->' "'" ident@.
%
Use of \#-types to abbreviate polymorphic variant types is deprecated.
If @@t@@ is an exact variant type then @"#"@t@@ translates to @"[<" @t@"]"@,
and @"#"@t@"[>" "`"tag_1 \dots"`"tag_k"]"@ translates to
@"[<" @t@ ">" "`"tag_1 \dots"`"tag_k"]"@
\subsubsection*{Variant and record types}
There are no type expressions describing (defined) variant types nor
record types, since those are always named, i.e. defined before use
and referred to by name. Type definitions are described in
section~\ref{s:type-defs}.

View File

@ -0,0 +1,97 @@
\section{Values}
\pdfsection{Values}
%HEVEA\cutname{values.html}
This section describes the kinds of values that are manipulated by
OCaml programs.
\subsection{Base values}
\subsubsection*{Integer numbers}
Integer values are integer numbers from $-2^{30}$ to $2^{30}-1$, that
is $-1073741824$ to $1073741823$. The implementation may support a
wider range of integer values: on 64-bit platforms, the current
implementation supports integers ranging from $-2^{62}$ to $2^{62}-1$.
\subsubsection*{Floating-point numbers}
Floating-point values are numbers in floating-point representation.
The current implementation uses double-precision floating-point
numbers conforming to the IEEE 754 standard, with 53 bits of mantissa
and an exponent ranging from $-1022$ to $1023$.
\subsubsection*{Characters}
Character values are represented as 8-bit integers between 0 and 255.
Character codes between 0 and 127 are interpreted following the ASCII
standard. The current implementation interprets character codes
between 128 and 255 following the ISO 8859-1 standard.
\subsubsection*{Character strings} \label{s:string-val}
String values are finite sequences of characters. The current
implementation supports strings containing up to $2^{24} - 5$
characters (16777211 characters); on 64-bit platforms, the limit is
$2^{57} - 9$.
\subsection{Tuples}
Tuples of values are written @'('@v@_1',' \ldots',' @v@_n')'@, standing for the
$n$-tuple of values @@v@_1@ to @@v@_n@. The current implementation
supports tuple of up to $2^{22} - 1$ elements (4194303 elements).
\subsection{Records}
Record values are labeled tuples of values. The record value written
@'{' field_1 '=' @v@_1';' \ldots';' field_n '=' @v@_n '}'@ associates the value
@@v@_i@ to the record field @field_i@, for $i = 1 \ldots n$. The current
implementation supports records with up to $2^{22} - 1$ fields
(4194303 fields).
\subsection{Arrays}
Arrays are finite, variable-sized sequences of values of the same
type. The current implementation supports arrays containing up to
$2^{22} - 1$ elements (4194303 elements) unless the elements are
floating-point numbers (2097151 elements in this case); on 64-bit
platforms, the limit is $2^{54} - 1$ for all arrays.
\subsection{Variant values}
Variant values are either a constant constructor, or a non-constant
constructor applied to a number of values. The former case is written
@constr@; the latter case is written @constr '('@v@_1',' ... ',' @v@_n
')'@, where the @@v@_i@ are said to be the arguments of the non-constant
constructor @constr@. The parentheses may be omitted if there is only
one argument.
The following constants are treated like built-in constant
constructors:
\begin{tableau}{|l|l|}{Constant}{Constructor}
\entree{"false"}{the boolean false}
\entree{"true"}{the boolean true}
\entree{"()"}{the ``unit'' value}
\entree{"[]"}{the empty list}
\end{tableau}
The current implementation limits each variant type to have at most
246 non-constant constructors and $2^{30}-1$ constant constructors.
\subsection{Polymorphic variants}
Polymorphic variants are an alternate form of variant values, not
belonging explicitly to a predefined variant type, and following
specific typing rules. They can be either constant, written
@"`"tag-name@, or non-constant, written @"`"tag-name'('@v@')'@.
\subsection{Functions}
Functional values are mappings from values to values.
\subsection{Objects}
Objects are composed of a hidden internal state which is a
record of instance variables, and a set of methods for accessing and
modifying these variables. The structure of an object is described by
the toplevel class that created it.

32
manual/manual/style.css Normal file
View File

@ -0,0 +1,32 @@
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 : 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 }
.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: #90BDFF ; padding: 2px; }
div.h7 { font-size : 20pt ; border: 1px solid #000000; margin-top: 5px; margin-bottom: 2px;text-align: center; background-color: #90DDFF ; 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 }
pre { margin-bottom: 4px }
div.sig_block {margin-left: 2em}

View File

@ -0,0 +1,13 @@
*.aux
*.dvi
*.idx
*.ilg
*.ind
*.log
*.toc
*.ipr
*.txt
*.pdf
*.ps
pdfmanual.out
manual.out

13
manual/manual/texstuff/.gitignore vendored Normal file
View File

@ -0,0 +1,13 @@
*.aux
*.dvi
*.idx
*.ilg
*.ind
*.log
*.toc
*.ipr
*.txt
*.pdf
*.ps
pdfmanual.out
manual.out

View File

@ -0,0 +1,5 @@
manual.txt
manual.hmanual.kwd
*.haux
*.hind
*.htoc

5
manual/manual/textman/.gitignore vendored Normal file
View File

@ -0,0 +1,5 @@
manual.txt
manual.hmanual.kwd
*.haux
*.hind
*.htoc

View File

@ -0,0 +1,2 @@
*.tex
*.htex

Some files were not shown because too many files have changed in this diff Show More