638 search results for ""
-
The Compiler Frontend: Parsing and Type Checking
Adding Type Annotations to Find Errors
This error points directly to the correct line number that contains the typo. Once you fix the problem, you can remove the manual annotations if you prefer more succinct code. You can also leave
Runtime & Compiler -
How to Work with the Garbage Collector
Finalisation and the Weak Module
<!-- $MDX dir=examples --> Finally, we have some test code. I won't reproduce the test code here, but you can download the complete program and test code objcache.ml and compile it with: The
Guides -
The Compiler Frontend: Parsing and Type Checking
Inspecting Compilation Units with ocamlobjinfo
</div> This hash check is very conservative, but ensures that separate compilation remains type-safe all the way up to the final link phase. Your build system should ensure that you never see t
Runtime & Compiler -
Using the OCaml Compiler Toolchain
The ocamlc and ocamlopt Compilers
If your program depends upon third-party libraries, you must pass them on the command line. You must also indicate the libraries on which these libraries depend. You must also pass the -I option
Guides -
The Compiler Backend: Bytecode and Native code
Interactive Breakpoints with the GNU Debugger
One very useful feature of OCaml native code is that C and OCaml share the same stack. This means that GDB backtraces can give you a combined view of what's going on in your program and runtim
Runtime & Compiler -
Mutability and Imperative Control Flow
Bad: Side Effects Depending on Order of Evaluation
<!-- You can use the sequence operator `;` to execute expressions in a particular order: ```ocaml # print_endline "ha"; print_endline "ho";; ha ho - : unit = () ``` `let` expressions are executed in
Introduction -
The Compiler Frontend: Parsing and Type Checking
Wrapping Libraries with Module Aliases
If you want to disable this behavior of dune and deliberately include multiple toplevel modules, you can add (wrapped false) to your libraries stanza. However, this is discouraged in general du
Runtime & Compiler -
OCaml Programming Guidelines
When to use open modules rather than leaving them closed
In a program where type definitions are shared, it's beneficial to gather these definitions into one or more module(s) without implementations (containing only types). Then it's acceptable to sys
Resources -
The Compiler Backend: Bytecode and Native code
The Impact of Polymorphic Comparison
OCaml on x86_64 architectures caches the location of the minor heap in the %r15 register since it's so frequently referenced in OCaml functions. The minor heap pointer can also be changed by the
Runtime & Compiler -
Memory Representation of Values
Distinguishing Integers and Pointers at Runtime
The mechanism for this is simple, since the runtime system keeps track of the heap blocks it has allocated for OCaml values. If the pointer is inside a heap chunk that is marked as being managed
Runtime & Compiler -
The Compiler Backend: Bytecode and Native code
Using the Frame Pointer to Get More Accurate Traces
</div> Using the frame pointer changes the OCaml calling convention, but opam takes care of recompiling all your libraries with the new interface. OCaml thus makes the frame pointer an optio
Runtime & Compiler -
The Compiler Backend: Bytecode and Native code
Pattern Matching Optimization
The paper describes the backtracking algorithm used in classical pattern matching compilation, and also several OCaml-specific optimizations, such as the use of exhaustiveness information and co
Runtime & Compiler -
The Compiler Frontend: Parsing and Type Checking
Generating Documentation from Interfaces
You can also use odoc to generate complete snapshots of your project via integration with dune, as described in "Generating Documentation" . You should now have HTML files inside the html/ d
Runtime & Compiler -
The Compiler Frontend: Parsing and Type Checking
Displaying Inferred Types from the Compiler
<div class="note"> \noindent then, when you try to build, you'll get this error: \noindent and this as your mli : The compiler makes sure that your ml and mli files have compatible
Runtime & Compiler -
Basic Data Types and Pattern Matching
A Complete Example: Mathematical Expressions
The factorise function above introduces another feature: guards to each pattern. The conditional follows the when , and it means that the return code is executed only if the pattern matches an
Introduction -
The Compiler Frontend: Parsing and Type Checking
Examining the Typed Syntax Tree Directly
You'll rarely need to look at this raw output from the compiler unless you're building IDE tools, or are hacking on extensions to the core compiler itself. However, it's useful to know that this
Runtime & Compiler -
Preprocessors and PPXs
The Need for Controlling the PPX Ecosystem: ppxlib
For those interested in the history of OCaml, note that before ppxlib , there were other "official" libraries to deal with PPXs. Camlp4 was a way to extend the OCaml parser with added construc
Advanced Topics -
OCaml Programming Guidelines
Function application: the same rules as those in mathematics for usage of trigonometric functions
In mathematics you write sin x to mean sin (x) . In the same way sin x + cos x means (sin x) + (cos x) not sin (x + (cos x)) . Use the same conventions in OCaml: write f x + g x to mean
Resources -
Profiling
The Representation of Integers, Tag Bits, Heap-Allocated Values
Note that because > has type 'a -> 'a -> bool , both arguments must have the same type. The compiler should enforce this at compile time. I would assume that greaterthan probably contains code
Guides -
Loops and Recursions
Mutable Records, References (Again!) and Arrays
The OCaml compiler was designed with heavy numerical processing in mind (the sort of thing that FORTRAN is traditionally used for), so it contains various optimisations specifically for arrays
Introduction -
The Compiler Backend: Bytecode and Native code
Where Did the Bytecode Instruction Set Come From?
</div> Understanding the reasoning behind the different implementations of the bytecode interpreter and the native compiler is a very useful exercise for any budding language hacker. This pape
Runtime & Compiler -
The Compiler Frontend: Parsing and Type Checking
Which Comes First: The ml or the mli?
</div> Signature files provide a place to write succinct documentation and to abstract internal details that shouldn't be exported. Maintaining separate signature files also speeds up increment
Runtime & Compiler -
Preprocessors and PPXs
Dropping PPXs Dependency With [@@deriving_inline]
Note that, while it allows to drop a project's dependency both on ppxlib and on the used PPX, using deriving_inline comes with some drawbacks. It can increase the size (and readability) of th
Advanced Topics -
Memory Representation of Values
Some History About OCaml's Word-Aligned Pointers
An even more alert reader will be wondering about the performance implications are for integer arithmetic using this tagged representation. Since the bottom bit is set, any operation on the inte
Runtime & Compiler -
The Compiler Frontend: Parsing and Type Checking
Shorter Module Paths in Type Errors
You'll need to choose for yourself if you prefer short paths or the default behavior in your own projects, and pass the -short-paths flag to the compiler if you need The utop enhanced tople
Runtime & Compiler -
The Compiler Frontend: Parsing and Type Checking
Obtaining the Compiler Source Code
We'll go through each of the compilation stages now and explain how they will be useful to you during day-to-day OCaml development. testsuite/ : Regression tests for the core compiler. tools/
Runtime & Compiler -
Common Error Messages
The type of this expression... contains type variables that cannot be generalized
Now x has a known type: The compiler tells us that the type of x is not fully known yet. But by using x later, the compiler can infer the type of x : Data of type '_weak<n> may be al
Resources -
Loops and Recursions
Recursion Example: Maximum Element in a List
Notice how the solution proposed is both (a) very different from the imperative for-loop solution, and (b) much more closely tied to the problem specification. Functional programmers will tell yo
Introduction -
Mutability and Imperative Control Flow
Evaluating Expressions in Sequence
Fun fact : begin … end and parentheses are literally the same: Remember the value of a semicolon-separated sequence is the value of its last expression. Grouping the first two steps with begi
Introduction -
The Compiler Frontend: Parsing and Type Checking
Enforcing Principal Typing
If compiling in principal mode works, it is guaranteed that the program will pass type checking in non-principal mode, too. Bear in mind that the cmi files generated in principal mode differ f
Runtime & Compiler -
OCaml Programming Guidelines
OCaml code generally considered unreadable
If you naturally write the program print_string "Hello world!" in this way, please submit your work to the Obfuscated OCaml Contest . <!-- $MDX skip --> Systematically code sequences with
Resources -
Transitioning to Multicore with ThreadSanitizer
Install the Instrumenting TSan Compiler (Step 0)
If the above fails during installation of conf-unwind with No package 'libunwind' found , try setting the environment variable PKG_CONFIG_PATH to point to the location of libunwind.pc , for e
Guides -
OCaml Programming Guidelines
Local identifiers can be brief and should be reused from one function to another
A tolerated exception to the recommendation not to use capitalisation to separate words within identifiers when interfacing with existing libraries which use this naming convention. This lets OCa
Resources -
Understanding the Garbage Collector
What Values Can Be Finalized?
The finalizer can use all features of OCaml, including assignments that make the value reachable again and thus prevent it from being garbage-collected. It can also loop forever, which will cause
Runtime & Compiler -
Common Error Messages
This expression has type ... but is here used with type ...
For the compiler, the second definition of my_type is totally independent from the first definition. So we have defined two types which have the same name. Since "a" was defined earlier, it belon
Resources -
Formatting and Wrapping Text
Differences Between a Packing and a Structural “hov” Box
If we replace the packing boxes by structural boxes (open_box), each break hint that precedes a closing parenthesis can show the boxes structure, if it leads to a new line; hence [(---[(----[(
Tutorials -
The Compiler Backend: Bytecode and Native code
Embedding OCaml Bytecode in C
Embedding OCaml code like this lets you write OCaml that interfaces with any environment that works with a C compiler. You can even cross back from the C code into OCaml by using the Callback m
Runtime & Compiler -
Memoization
Just for Fun: Party Optimization
<!-- ***** MRC 7/22/21: the section below needs a lot more explanation. Also the value `big` was undefined in the original notes, so the code didn't compile. I added a definition of `target + 1` but
Data Structures -
Understanding the Garbage Collector
Marking and Scanning the Heap
Later in the marking process when the mark stack is empty it is replenished by redarkening the heap. This starts at the first heap chunk (by address) that has blocks needing redarkening (i.e wer
Runtime & Compiler -
Transitioning to Multicore with ThreadSanitizer
Address the Reported Races and Rerun the Tests, Take 2 (Steps 3 and 2)
This works well and TSan no longer complains, so our little library is ready for OCaml 5.x parallelism, hurrah! We can now rerun our tests under TSan to confirm the fix: Oh, wait! When raisin
Guides -
Transitioning to Multicore with ThreadSanitizer
Final Remarks and a Word of Warning
With that warning in mind and TSan in hand, you should now be equipped to hunt for data races. As a final word of warning, Domain s are so fast that in a too simple test runner, one Domain
Guides -
Error Handling
Using on Option.map and Option.bind
One of the limitations of the option type is that it doesn't record the reason that prevented having a return value. None is silent, it doesn't say anything about what went wrong. For this reas
Guides -
Calling C Libraries
Wrapping Calls to C Libraries
In order for it to get passed to OCaml code at all, we must somehow convert it to a value . Luckily we can quite easily use the C API to create value blocks which the OCaml garbage collector
Tutorials -
Transitioning to Multicore with ThreadSanitizer
Address the Reported Races and Rerun the Tests (Steps 3 and 2)
How come we may hit a resource deadlock error when adding just two pairs of Mutex.lock and Mutex.unlock calls? Rerunning our tests, we obtain: One way to address the reported races is to
Guides -
The Compiler Frontend: Parsing and Type Checking
Defining a Module Search Path
<div class="note"> By default, only the current directory and the OCaml standard library will be searched for cmi files. The Stdlib module from the standard library will also be opened by d
Runtime & Compiler -
Labelled and Optional Arguments
Optional Arguments and Partial Application
Note : Optional parameters make it difficult for the compiler to know if a function is partially applied or not. This is why at least one positional parameter is required after the optional ones. If
Introduction -
OCaml Programming Guidelines
Imperative and Functional Versions of list_length
This way, you get a program that has the same computational properties as the imperative program with the additional clarity and natural look of an algorithm that performs pattern-matching and re
Resources -
Labelled and Optional Arguments
Defining Optional Parameters Without Default Values
It is possible to use the same name for the len parameter and label name. This enables the following usages: <!-- TODO: consider a simpler example without any logic or exmplain use-case -->
Introduction -
Memory Representation of Values
Managing External Memory with Bigarray
The Lacaml library isn't part of Core but provides the recommended interfaces to the widely used BLAS and LAPACK mathematical Fortran libraries. These allow developers to write high-performan
Runtime & Compiler -
Basic Data Types and Pattern Matching
User-Defined Polymorphic Types
<!-- FIXME issue - "The polymorphic variants tutorial is unreleased, so the best at this point would probably be to comment out the paragraph with a FIXME comment and add it back when the new tutor
Introduction