mirror of
https://github.com/ocaml-tracing/ocaml-trace.git
synced 2026-03-08 03:47:57 -04:00
149 lines
32 KiB
HTML
149 lines
32 KiB
HTML
<!DOCTYPE html>
|
||
<html xmlns="http://www.w3.org/1999/xhtml"><head><title>matching-code (ppxlib.matching-code)</title><meta charset="utf-8"/><link rel="stylesheet" href="../_odoc-theme/odoc.css"/><meta name="generator" content="odoc 3.1.0"/><meta name="viewport" content="width=device-width,initial-scale=1.0"/><script src="../highlight.pack.js"></script><script>hljs.initHighlightingOnLoad();</script></head><body class="odoc"><nav class="odoc-nav"><a href="index.html">Up</a> – <a href="../index.html">Index</a> » <a href="index.html">ppxlib</a> » matching-code</nav><header class="odoc-preamble"><p> <div style="display: flex; justify-content:space-between"><div><a href="generating-code.html" title="generating-code">< Generating AST nodes</a> </div><div><a href="ast-traversal.html" title="ast-traversal">Traversing the AST ></a> </div></div></p><h1 id="destructing-ast-nodes"><a href="#destructing-ast-nodes" class="anchor"></a>Destructing AST Nodes</h1><p>In the previous chapter, we have seen how to generate code. However, the transformation function should depend on its input (the payload and maybe the derived item), which we have to be able to inspect.</p><p>Once again, directly inspecting the <a href="Astlib/Ast_502/Parsetree/index.html" title="Ppxlib.Parsetree"><code>Parsetree</code></a> value that we get as input is not a good option because it is very big to manipulate and can break at every new OCaml release. For instance, let's consider the case of <a href="https://github.com/janestreet/ppx_inline_test"><code>ppx_inline_test</code></a>. We want to recognize and extract the name and expression only from the form patterns:</p><pre class="language-ocaml"><code> [%%test let "name" = expr]</code></pre><p>If we wrote a function accepting the payload of <code>[%%test]</code>, and extracting the name and expression from it, using normal pattern matching we would have:</p><pre class="language-ocaml"><code> # let match_payload ~loc payload =
|
||
match payload with
|
||
| PStr
|
||
[
|
||
{
|
||
pstr_desc =
|
||
Pstr_value
|
||
( Nonrecursive,
|
||
[
|
||
{
|
||
pvb_pat =
|
||
{
|
||
ppat_desc =
|
||
Ppat_constant (Pconst_string (name, _, None));
|
||
_;
|
||
};
|
||
pvb_expr = expr;
|
||
_;
|
||
};
|
||
] );
|
||
_;
|
||
};
|
||
] ->
|
||
Ok (name, expr)
|
||
| _ -> Error (Location.Error.createf ~loc "Wrong pattern") ;;
|
||
val match_payload :
|
||
loc:location -> payload -> (string * expression, Location.Error.t) result =</code></pre><p><code>ppxlib</code>'s solution to the verbosity and stability problem is to provide helpers to <em>match</em> the AST, in a very similar way to what it does for generating AST nodes.</p></header><div class="odoc-tocs"><nav class="odoc-toc odoc-local-toc"><ul><li><a href="#the-different-options">The Different Options</a></li><li><a href="#ast_pattern_intro">The <code>Ast_pattern</code> Module</a><ul><li><a href="#the-type-for-patterns">The Type for Patterns</a></li><li><a href="#building-patterns">Building Patterns</a></li><li><a href="#pattern_examples">Useful patterns and examples</a></li></ul></li><li><a href="#metaquot"><code>Metaquot</code></a><ul><li><a href="#metaquot-for-patterns"><code>Metaquot</code> for Patterns</a></li><li><a href="#antiquotations">Anti-Quotations</a></li></ul></li></ul></nav></div><div class="odoc-content"><h2 id="the-different-options"><a href="#the-different-options" class="anchor"></a>The Different Options</h2><p>In this chapter, we will often mention the similarities between matching code and generating code (from the <a href="generating-code.html" title="generating-code">previous chapter</a>). Indeed, the options provided by <code>ppxlib</code> to match AST nodes mirror the ones for generating nodes:</p><ul><li><a href="Ppxlib/Ast_pattern/index.html" title="Ppxlib.Ast_pattern"><code>Ast_pattern</code></a>, the <a href="Ppxlib/Ast_builder/index.html" title="Ppxlib.Ast_builder"><code>Ast_builder</code></a> sibling,</li><li><a href="Ppxlib_metaquot/index.html" title="Ppxlib_metaquot"><code>Metaquot</code></a> again.</li></ul><p><a href="Ppxlib/Ast_pattern/index.html" title="Ppxlib.Ast_pattern"><code>Ast_pattern</code></a> is used in <a href="Ppxlib/Extension/V3/index.html#val-declare" title="Ppxlib.Extension.V3.declare"><code>Extension.V3.declare</code></a>, so you will need it to write extenders. <a href="Ppxlib_metaquot/index.html"><code>Ppxlib_metaquot</code></a> is, as for generating nodes, more natural to use but also restricted to some cases.</p><h2 id="ast_pattern_intro"><a href="#ast_pattern_intro" class="anchor"></a>The <code>Ast_pattern</code> Module</h2><p>A match is a "structural destruction" of a value into multiple subvalues to continue the computation. For instance, in the example above from the single variable <code>payload</code>, we structurally extract two variables: <code>name</code> and <code>expr</code>.</p><p>Destruction is very similar to construction, but in reverse. Instead of using several values to build a bigger one, we use one big value to define smaller ones. As an illustration, note how in OCaml the following construction and destruction are close:</p><pre class="language-ocaml"><code> let big = { x ; y } (** Construction from [x] and [y] *)
|
||
let { x ; y } = big (** Destruction recovering [x] and [y] *)</code></pre><p>For the same reason, building AST nodes using <a href="Ppxlib/Ast_builder/index.html" title="Ppxlib.Ast_builder"><code>Ast_builder</code></a> and destructing AST nodes using <a href="Ppxlib/Ast_pattern/index.html" title="Ppxlib.Ast_pattern"><code>Ast_pattern</code></a> look very similar. The difference is that in the construction "leaf," <a href="Ppxlib/Ast_builder/index.html" title="Ppxlib.Ast_builder"><code>Ast_builder</code></a> uses actual values, while <a href="Ppxlib/Ast_pattern/index.html" title="Ppxlib.Ast_pattern"><code>Ast_pattern</code></a> has "wildcards" at the leafs.</p><p>Consider the example in the introduction matching <code>[%%test let "name" = expr]</code>. Building such an expression with <a href="Ppxlib/Ast_builder/index.html" title="Ppxlib.Ast_builder"><code>Ast_builder</code></a> could look like:</p><pre class="language-ocaml"><code> # let build_payload_test ~loc name expr =
|
||
let (module B) = Ast_builder.make loc in
|
||
let open B in
|
||
Parsetree.PStr
|
||
(pstr_value Nonrecursive
|
||
(value_binding ~pat:(pstring name) ~expr :: [])
|
||
:: []) ;;
|
||
val build_payload_test :
|
||
loc:location -> string -> expression -> payload =
|
||
<abstr></code></pre><p>Constructing a first-class pattern is almost as simple as replacing <code>Ast_builder</code> with <code>Ast_pattern</code>, as well as replacing the base values <code>name</code> and <code>expr</code> with a capturing wildcard:</p><pre class="language-ocaml"><code> # let destruct_payload_test () =
|
||
let open Ast_pattern in
|
||
pstr
|
||
(pstr_value nonrecursive
|
||
(value_binding ~pat:(pstring __) ~expr:__ ^:: nil)
|
||
^:: nil) ;;
|
||
val destruct_payload_test :
|
||
unit -> (payload, string -> expression -> 'a, 'a) Ast_pattern.t =
|
||
<abstr></code></pre><p>Note that to facilitate viewing the similarity, we wrote <code>[v]</code> as <code>v :: []</code>, and we added a <code>unit</code> argument to avoid <a href="https://v2.ocaml.org/manual/polymorphism.html#ss:valuerestriction">value restriction</a> to mess with the type (that we explained right in the next section).</p><h3 id="the-type-for-patterns"><a href="#the-type-for-patterns" class="anchor"></a>The Type for Patterns</h3><p>The <a href="Ppxlib/Ast_pattern/index.html#type-t" title="Ppxlib.Ast_pattern.t"><code>Ast_pattern.t</code></a> type reflects the fact that a pattern-match or destruction is taking a value, extracting other values from it, and using them to finally output something. So, a value <code>v</code> of type <code>(matched, cont, res) Ast_pattern.t</code> means that:</p><ul><li>The type of values matched by <code>v</code> is <code>matched</code>. For instance, <code>matched</code> could be <a href="Astlib/Ast_502/Parsetree/index.html#type-payload" title="Ppxlib.Parsetree.payload"><code>payload</code></a>.</li><li>The continuation (what to do with the extracted values) has type <code>cont</code>. The values extracted from the destruction are passed as an argument to the continuation, therefore <code>cont</code> includes information about them. For instance, for a pattern that captures an <code>int</code> and a <code>string</code>, <code>cont</code> could be <code>int -> string -> structure</code>. The continuation is not part of <code>v</code>; it will be given with the value to match.</li><li>The result of the computation has type <code>res</code>. Note that this is additional information than what we have in <code>cont</code>: <a href="Ppxlib/Ast_pattern/index.html#val-map_result" title="Ppxlib.Ast_pattern.map_result"><code>Ast_pattern.map_result</code></a> allows mapping the continuation result through a function! This allows users to add a "construction" post-processing to the continuation. A value of type <code>(pattern, int -> int, expression) Ast_pattern.t</code> would contain how to extract an integer from a <code>pattern</code> and how to map a modified <code>int</code> into an <code>expression</code>.</li></ul><p>In the case of the example above, <code>destruct_payload_test</code> has type:</p><pre class="language-ocaml"><code> # destruct_payload_test ;;
|
||
val destruct_payload_test :
|
||
(payload, string -> expression -> 'a, 'a) Ast_pattern.t =
|
||
<abstr></code></pre><p>as it destructs values of type <code>pattern</code> extracts two values, respectively, of type <code>string</code> and <code>expression</code>, so the continuation has type <code>string -> expression -> 'a</code>. Then the result type is <code>'a</code> since no mapping on the result is made. Now that the type of <a href="Ppxlib/Ast_pattern/index.html#type-t" title="Ppxlib.Ast_pattern.t"><code>Ast_pattern.t</code></a> is explained, the type of <a href="Ppxlib/Ast_pattern/index.html#val-parse_res" title="Ppxlib.Ast_pattern.parse_res"><code>Ast_pattern.parse_res</code></a>, the function for applying patterns, should make sense:</p><pre class="language-ocaml"><code> # Ast_pattern.parse_res ;;
|
||
val parse_res :
|
||
( 'matched, 'cont, 'res ) t ->
|
||
Location.t ->
|
||
?on_error:( unit -> 'res) ->
|
||
'matched ->
|
||
'cont ->
|
||
( 'res, Location.Error.t Stdppx.NonEmptyList.t ) result =
|
||
<fun></code></pre><p>This function takes a pattern expecting values of type <code>'matched</code>, continuations of type <code>'cont</code> and output values of type <code>('res, _) result</code> (where the error case is when the <code>'matched</code> value does not have the expected structure). The types of the function's other arguments correspond to this understanding: the argument of type <code>'matched</code> is the value to match, the one of type <code>'cont</code> is the continuation, and the result of applying the pattern to those two values is of type <code>'res</code>!</p><p>Composing construction and destruction yield the identity:</p><pre class="language-ocaml"><code> # let f name expr =
|
||
Ast_pattern.parse_res
|
||
(destruct_payload_test ()) Location.none
|
||
(build_payload_test ~loc name expr)
|
||
(fun name expr -> (name, expr)) ;;
|
||
val f :
|
||
string ->
|
||
expression ->
|
||
(string * expression, _) result = <fun>
|
||
# f "name" [%expr ()] ;;
|
||
Ok
|
||
("name",
|
||
{pexp_desc =
|
||
Pexp_construct
|
||
({txt = Lident "()";
|
||
...}...)...}...)</code></pre><p>While the <a href="Ppxlib/Ast_pattern/index.html#val-parse_res" title="Ppxlib.Ast_pattern.parse_res"><code>Ast_pattern.parse_res</code></a> function is useful to match an AST node, you will also need the <a href="Ppxlib/Ast_pattern/index.html#type-t" title="Ppxlib.Ast_pattern.t"><code>Ast_pattern.t</code></a> value in other contexts. For instance, it is used when declaring extenders with <a href="Ppxlib/Extension/index.html#val-declare" title="Ppxlib.Extension.declare"><code>Extension.declare</code></a> to tell how to extract arguments from the payload to give them to the extender, or when parsing with <a href="Ppxlib/Deriving/Args/index.html#val-arg" title="Ppxlib.Deriving.Args.arg">deriving arguments</a>.</p><h3 id="building-patterns"><a href="#building-patterns" class="anchor"></a>Building Patterns</h3><p>Now that we know what these patterns represent and how to use them, and have seen an example in the <a href="#ast_pattern_intro" title="ast_pattern_intro">introduction</a> on <a href="Ppxlib/Ast_pattern/index.html" title="Ppxlib.Ast_pattern"><code>Ast_pattern</code></a>, the combinators in the <a href="Ppxlib/Ast_pattern/index.html" title="Ppxlib.Ast_pattern">API</a> should be much more easily understandable. So, for a comprehensive list of the different values in the module, the reader should directly refer to the API. In this guide; however, we explain in more detail a few important values with examples.</p><p><b>The wildcard pattern <code>| x -> </code></b>. The simplest way to extract a value from something is just to return it! In <a href="Ppxlib/Ast_pattern/index.html" title="Ppxlib.Ast_pattern"><code>Ast_pattern</code></a>, it corresponds to the value <a href="Ppxlib/Ast_pattern/index.html#val-__" title="Ppxlib.Ast_pattern.__"><code>__</code></a> (of type <code>('a, 'a -> 'b, 'b)</code>), which extract the value it's given: <a href="Ppxlib/Ast_pattern/index.html#val-parse_res" title="Ppxlib.Ast_pattern.parse_res">matching</a> a value <code>v</code> with this pattern and a continuation <code>k</code> would simply call <code>k v</code>.</p><p>This pattern is useful in combination with other combinators.</p><p><b>The wildcard-dropping pattern <code>| _ -> </code></b>. Despite their name ressemblance, <a href="Ppxlib/Ast_pattern/index.html#val-__" title="Ppxlib.Ast_pattern.__"><code>__</code></a> is very different from the OCaml pattern-match wildcard <code>_</code>, which accepts everything but <em>ignores</em> its input. In <a href="Ppxlib/Ast_pattern/index.html" title="Ppxlib.Ast_pattern"><code>Ast_pattern</code></a>, the wildcard-dropping pattern is <a href="Ppxlib/Ast_pattern/index.html#val-drop" title="Ppxlib.Ast_pattern.drop"><code>drop</code></a>. Again, it is useful in conjunction with other combinators, where one needs to accept all input in some places, but the value is not relevant.</p><p><b>The <code>| p as name -> </code> combinator</b>. The combinator <a href="Ppxlib/Ast_pattern/index.html#val-as__" title="Ppxlib.Ast_pattern.as__"><code>as__</code></a> allows passing a node to the continuation while still extracting values from this node. For instance, <code>as__ (some __)</code> corresponds to the OCaml pattern-match <code> Some n2 as n1</code>, where the continuation is called with <code>k n1 n2</code>.</p><p><b>The <code>| (p1 | p2) -> </code> combinator</b>. The combinator <a href="Ppxlib/Ast_pattern/index.html#val-alt" title="Ppxlib.Ast_pattern.alt"><code>alt</code></a> combines two patterns with the same type for extracted values into one pattern by first trying to apply the first, and if it fails, by applying the second one. For instance, <code>alt (pair (some __) drop) (pair drop (some __))</code> corresponds to the OCaml pattern <code>(Some a, _) | (_, Some b)</code>.</p><p><b>The constant patterns <code>| "constant" -> </code></b>. Using <a href="Ppxlib/Ast_pattern/index.html#val-cst" title="Ppxlib.Ast_pattern.cst"><code>Ast_pattern.cst</code></a> it is possible to create patterns matching only fixed values, such as the <code>"constant"</code> string. No values are extracted from this matching. The functions for creating such values are <a href="Ppxlib/Ast_pattern/index.html#val-int" title="Ppxlib.Ast_pattern.int"><code>Ast_pattern.int</code></a>, <a href="Ppxlib/Ast_pattern/index.html#val-string" title="Ppxlib.Ast_pattern.string"><code>Ast_pattern.string</code></a>, <a href="Ppxlib/Ast_pattern/index.html#val-bool" title="Ppxlib.Ast_pattern.bool"><code>Ast_pattern.bool</code></a>, ...</p><p><b>The common deconstructors</b>. Many usual common constructors have "deconstructors" in <a href="Ppxlib/Ast_pattern/index.html" title="Ppxlib.Ast_pattern"><code>Ast_pattern</code></a>. For instance:</p><ul><li><code>some __</code> corresponds to <code>Some a</code>,</li><li><code>__ ^:: drop ^:: nil</code> correspnds to <code>a :: _ :: []</code>,</li><li><code>pair __ __</code> (or equivalently <code>__ ** __</code>) corresponds to <code>(a,b)</code>, etc.</li></ul><p><b>The Parsetree deconstructors</b>. All constructors from <a href="Ppxlib/Ast_builder/index.html" title="Ppxlib.Ast_builder"><code>Ast_builder</code></a> have a "deconstructor" in <a href="Ppxlib/Ast_pattern/index.html" title="Ppxlib.Ast_pattern"><code>Ast_pattern</code></a> with the same name. For instance, since <a href="Ppxlib/Ast_builder/index.html" title="Ppxlib.Ast_builder"><code>Ast_builder</code></a> has a constructor <a href="Ppxlib/Ast_builder/Default/index.html#val-pstr_value" title="Ppxlib.Ast_builder.Default.pstr_value"><code>pstr_value</code></a> to build a structure item from a <code>rec_flag</code> and a <code>value_binding</code> list. <a href="Ppxlib/Ast_pattern/index.html" title="Ppxlib.Ast_pattern"><code>Ast_pattern</code></a> has an equally named <a href="Ppxlib/Ast_pattern/index.html#val-pstr_value" title="Ppxlib.Ast_pattern.pstr_value"><code>pstr_value</code></a> which, given ways to destruct rec flags and <code>value_binding</code> lists, creates a destructor for structure items.</p><p><b>The continuation modifiers</b>. Many <a href="Ppxlib/Ast_pattern/index.html" title="Ppxlib.Ast_pattern"><code>Ast_pattern</code></a> values allow modifying the continuation. It can be it a map on the continuation itself, the argument to the continuation, or the result of the continuation. So, <a href="Ppxlib/Ast_pattern/index.html#val-map" title="Ppxlib.Ast_pattern.map"><code>Ast_pattern.map</code></a> transforms the continuation itself, e.g., <code>map ~f:Fun.flip</code> will switch the arguments of the function. <a href="Ppxlib/Ast_pattern/index.html#val-map1" title="Ppxlib.Ast_pattern.map1"><code>map<i></code></a> modifies the arguments to a continuation of arity <code>i</code>: <code>map2 ~f:combine</code> is equivalent to <code>map ~f:(fun k -> (fun x y -> k (combine x y)))</code>. Finally, <a href="Ppxlib/Ast_pattern/index.html#val-map_result" title="Ppxlib.Ast_pattern.map_result"><code>Ast_pattern.map_result</code></a> modifies the continuation's result, and <code>map_result ~f:ignore</code> would ignore the continuation's result.</p><p><b>Common patterns</b> Some patterns are sufficiently common that, although they can be built from smaller bricks, they are already defined in <a href="Ppxlib/Ast_pattern/index.html" title="Ppxlib.Ast_pattern"><code>Ast_pattern</code></a>. For instance, matching a single expression in a payload is given as <a href="Ppxlib/Ast_pattern/index.html#val-single_expr_payload" title="Ppxlib.Ast_pattern.single_expr_payload"><code>Ast_pattern.single_expr_payload</code></a>.</p><h3 id="pattern_examples"><a href="#pattern_examples" class="anchor"></a>Useful patterns and examples</h3><p>Below, is a list of patterns that are commonly needed when using <a href="Ppxlib/Ast_pattern/index.html" title="Ppxlib.Ast_pattern"><code>Ast_pattern</code></a>:</p><pre class="language-ocaml"><code> open Ast_pattern</code></pre><ul><li>A pattern to extract an expression from an extension point payload:</li></ul><pre class="language-ocaml"><code> # let extractor () = single_expr_payload __ ;
|
||
val extractor : unit -> (payload, expression -> 'a, 'a) t = <fun></code></pre><ul><li>A pattern to extract a string from an extension point payload:</li></ul><pre class="language-ocaml"><code> # let extractor () = single_expr_payload (estring __) ;
|
||
val extractor : unit -> (payload, string -> 'a, 'a) t = <fun></code></pre><ul><li>A pattern to extract a pair <code>int * float</code> from an extension point payload:</li></ul><pre class="language-ocaml"><code> # let extractor () = single_expr_payload (pexp_tuple (eint __ ^:: efloat __ ^:: nil)) ;;
|
||
val extractor : unit -> (payload, int -> string -> 'a, 'a) t = <fun></code></pre><ul><li>A pattern to extract a list of integers from an extension point payload, given as a tuple (of unfixed length):</li></ul><pre class="language-ocaml"><code> # let extractor () = single_expr_payload (pexp_tuple (many (eint __))) ;;
|
||
val extractor : unit -> (payload, int -> string -> 'a, 'a) t = <fun></code></pre><ul><li>A pattern to extract a list of integers from an extension point payload, given as a list:</li></ul><pre class="language-ocaml"><code> # let extractor () = single_expr_payload (elist (eint __)) ;;
|
||
val extractor : unit -> (payload, int list -> 'a, 'a) t = <fun></code></pre><ul><li>A pattern to extract the <code>pattern</code> and the <code>expression</code> in a let-binding, from a structure item:</li></ul><pre class="language-ocaml"><code> # let extractor_in_let () = pstr_value drop ((value_binding ~pat:__ ~expr:__) ^:: nil);;
|
||
val extractor_in_let : unit -> (structure_item, pattern -> expression -> 'a, 'a) t =
|
||
<fun></code></pre><ul><li>A pattern to extract the <code>pattern</code> and the <code>expression</code> in a let-binding, from an extension point payload:</li></ul><pre class="language-ocaml"><code> # let extractor () = pstr @@ extractor_in_let ^:: nil;;
|
||
val extractor : unit -> (payload, pattern -> expression -> 'a, 'a) t = <fun></code></pre><ul><li>A pattern to extract a core type, from an extension point payload (with a comma in the extension node, such as <code>[%ext_name: core_type]</code>):</li></ul><pre class="language-ocaml"><code> # let extractor () = ptyp __
|
||
val extractor : unit -> (payload, core_type -> 'a, 'a) t = <fun></code></pre><ul><li>A pattern to extract a string from an expression, either from an identifier or from a string. That is, it will extract the string <code>"foo"</code> from both the AST nodes <code>foo</code> and <code>"foo"</code>.</li></ul><pre class="language-ocaml"><code> # let extractor () = alt (pexp_ident (lident __)) (estring __) ;;
|
||
val extractor : unit -> (expression, string -> 'a, 'a) t = <fun></code></pre><ul><li>A pattern to extract a sequence of two idents, as strings (will extract <code>"foo"</code>, <code>"bar"</code> from <code>[%ext_name foo bar]</code>):</li></ul><pre class="language-ocaml"><code> let extractor () =
|
||
single_expr_payload @@
|
||
pexp_apply
|
||
(pexp_ident (lident __))
|
||
((no_label (pexp_ident (lident __))) ^:: nil) ;;
|
||
val extractor : unit -> (payload, string -> string -> 'a, 'a) t = <fun></code></pre><h2 id="metaquot"><a href="#metaquot" class="anchor"></a><code>Metaquot</code></h2><h3 id="metaquot-for-patterns"><a href="#metaquot-for-patterns" class="anchor"></a><code>Metaquot</code> for Patterns</h3><p>Recall that <code>ppxlib</code> provides a rewriter to generate code explained in <a href="generating-code.html#metaquot" title="metaquot">the corresponding chapter</a>. The same PPX can also generate patterns when the extension nodes are used patterns: for instance, in what follows, the extension node will be replaced by a value of <a href="Astlib/Ast_502/Parsetree/index.html#type-expression" title="Ppxlib.Parsetree.expression"><code>expression</code></a> type:</p><pre class="language-ocaml"><code> let f = [%expr 1 + 1]</code></pre><p>While in the following, it would be replaced by a pattern matching on values of <a href="Astlib/Ast_502/Parsetree/index.html#type-expression" title="Ppxlib.Parsetree.expression"><code>expression</code></a> type:</p><pre class="language-ocaml"><code> let f x = match x with
|
||
| [%expr 1 + 1] -> ...
|
||
| _ -> ...</code></pre><p>The produced pattern matches regardless of location and attributes. For the previous example, it will produce the following pattern:</p><pre class="language-ocaml"><code> {
|
||
pexp_desc =
|
||
(Pexp_apply
|
||
({
|
||
pexp_desc = (Pexp_ident { txt = (Lident "+"); loc = _ });
|
||
pexp_loc = _;
|
||
pexp_attributes = _
|
||
},
|
||
[(Nolabel,
|
||
{
|
||
pexp_desc = (Pexp_constant (Pconst_integer ("1", None)));
|
||
pexp_loc = _;
|
||
pexp_attributes = _
|
||
});
|
||
(Nolabel,
|
||
{
|
||
pexp_desc = (Pexp_constant (Pconst_integer ("1", None)));
|
||
pexp_loc = _;
|
||
pexp_attributes = _
|
||
})]));
|
||
pexp_loc = _;
|
||
pexp_attributes = _
|
||
}</code></pre><p>While being less general than <a href="Ppxlib/Ast_pattern/index.html" title="Ppxlib.Ast_pattern"><code>Ast_pattern</code></a>, this allows users to write patterns in a more natural way. Due to the OCaml AST, <a href="Astlib/Ast_502/Parsetree/index.html#type-payload" title="Ppxlib.Parsetree.payload">payloads</a> can only take the form of a <a href="Astlib/Ast_502/Parsetree/index.html#type-structure" title="Ppxlib.Parsetree.structure"><code>structure</code></a>, a <a href="Astlib/Ast_502/Parsetree/index.html#type-signature" title="Ppxlib.Parsetree.signature"><code>signature</code></a>, a <a href="Astlib/Ast_502/Parsetree/index.html#type-core_type" title="Ppxlib.Parsetree.core_type"><code>core type</code></a>, or a <a href="Astlib/Ast_502/Parsetree/index.html#type-pattern" title="Ppxlib.Parsetree.pattern"><code>pattern</code></a>. We might want to generate pattern matching for other kinds of nodes, such as expressions or structure item. The same extension nodes that <code>Metaquot</code> provides for building can be used for matching:</p><ul><li><p>The <code>expr</code> extension node to match on <a href="Astlib/Ast_502/Parsetree/index.html#type-expression" title="Ppxlib.Parsetree.expression"><code>expressions</code></a>:</p><pre class="language-ocaml"><code>match expr with [%expr 1 + 1] -> ...</code></pre></li><li><p>The <code>pat</code> extension node to match on <a href="Astlib/Ast_502/Parsetree/index.html#type-pattern" title="Ppxlib.Parsetree.pattern"><code>patterns</code></a>:</p><pre class="language-ocaml"><code>match pattern with [%pat? ("", _)] -> ...</code></pre></li><li><p>The <code>type</code> extension node to match on for <a href="Astlib/Ast_502/Parsetree/index.html#type-core_type" title="Ppxlib.Parsetree.core_type"><code>core types</code></a>:</p><pre class="language-ocaml"><code>match typ with [%type: int -> string] -> ...</code></pre></li><li><p>The <code>stri</code> and <code>sigi</code> extension nodes to match on <a href="Astlib/Ast_502/Parsetree/index.html#type-structure_item" title="Ppxlib.Parsetree.structure_item"><code>structure_item</code></a> and <a href="Astlib/Ast_502/Parsetree/index.html#type-signature_item" title="Ppxlib.Parsetree.signature_item"><code>signature_item</code></a>:</p><pre class="language-ocaml"><code>match stri with [%stri let a = 1] -> ...
|
||
match sigi with [%sigi: val a : int] -> ...</code></pre></li><li><p>The <code>str</code> and <code>sig</code> extension nodes to match on <a href="Astlib/Ast_502/Parsetree/index.html#type-structure" title="Ppxlib.Parsetree.structure"><code>structure</code></a> and <a href="Astlib/Ast_502/Parsetree/index.html#type-signature" title="Ppxlib.Parsetree.signature"><code>signature</code></a>.</p><pre class="language-ocaml"><code>let _ =
|
||
match str with
|
||
| [%str
|
||
let a = 1
|
||
let b = 2.1] ->
|
||
()
|
||
|
||
let _ =
|
||
match sigi with
|
||
| [%sigi:
|
||
val a : int
|
||
val b : float] ->
|
||
()
|
||
</code></pre></li></ul><h3 id="antiquotations"><a href="#antiquotations" class="anchor"></a>Anti-Quotations</h3><p><a href="generating-code.html#antiquotations" title="antiquotations">Similarly</a> to the <code>expression</code> context, these extension nodes have a limitation: when using these extensions alone, you can't bind variables. <code>Metaquot</code> also solves this problem using anti-quotation. In the <code>pattern</code> context, anti-quotation is not used to insert values but to insert patterns. That way you can include a wildcard or variable-binding pattern.</p><p>Consider the following example, which matches expression nodes corresponding to the sum of three expressions: starting with the constant 1, followed by anything, followed by anything bound to the <code>third</code> variable, which has type <code>expression</code>:</p><pre class="language-ocaml"><code> match some_expr_node with
|
||
| [%expr 1 + [%e? _] + [%e? third]] -> do_something_with third</code></pre><p>The syntax for anti-quotation depends on the type of the node you wish to insert (which must also correspond to the context of the anti-quotation extension node):</p><ul><li><p>The extension point <code>e</code> is used to anti-quote values of type <a href="Astlib/Ast_502/Parsetree/index.html#type-expression" title="Ppxlib.Parsetree.expression"><code>expression</code></a>:</p><pre class="language-ocaml"><code>match e with [%expr 1 + [%e? some_expr_pattern]] -> ...</code></pre></li><li><p>The extension point <code>p</code> is used to anti-quote values of type <a href="Astlib/Ast_502/Parsetree/index.html#type-pattern" title="Ppxlib.Parsetree.pattern"><code>pattern</code></a>:</p><pre class="language-ocaml"><code>match pat with [%stri let [%p? x] = [%e? y]] -> do_something_with x y</code></pre></li><li><p>The extension point <code>t</code> is used to anti-quote values of type <a href="Astlib/Ast_502/Parsetree/index.html#type-core_type" title="Ppxlib.Parsetree.core_type"><code>core_type</code></a>:</p><pre class="language-ocaml"><code>match t with [%type: int -> [%t? _]] -> ...</code></pre></li><li><p>The extension point <code>m</code> is used to anti-quote values of type <a href="Astlib/Ast_502/Parsetree/index.html#type-module_expr" title="Ppxlib.Parsetree.module_expr"><code>module_expr</code></a> or <a href="Astlib/Ast_502/Parsetree/index.html#type-module_type" title="Ppxlib.Parsetree.module_type"><code>module_type</code></a>:</p><pre class="language-ocaml"><code>let [%expr
|
||
let module M = [%m? extracted_m] in
|
||
M.x] =
|
||
some_expr
|
||
in
|
||
do_something_with extracted_m
|
||
|
||
let _ = fun [%sigi: module M : [%m? input]] -> do_something_with input</code></pre></li><li><p>The extension point <code>i</code> is used to anti-quote values of type <a href="Astlib/Ast_502/Parsetree/index.html#type-structure_item" title="Ppxlib.Parsetree.structure_item"><code>structure_item</code></a> or <a href="Astlib/Ast_502/Parsetree/index.html#type-signature_item" title="Ppxlib.Parsetree.signature_item"><code>signature_item</code></a>:</p><pre class="language-ocaml"><code>let [%str
|
||
let a = 1
|
||
|
||
[%%i? stri2]] =
|
||
e
|
||
in
|
||
do_something_with stri2
|
||
;;
|
||
|
||
let [%sig:
|
||
val a : int
|
||
|
||
[%%i? sigi2]] =
|
||
s
|
||
in
|
||
do_something_with sigi2</code></pre></li></ul><p>Remember, since we are inserting patterns (and not expressions), we always use patterns as payload, as in <code>[%e? x]</code>.</p><p>If an anti-quote extension node is in the wrong context, it won't be rewritten by <code>Metaquot</code>. For instance, in <code>fun [%expr 1 + [%p? x]] -> x</code> the anti-quote extension node for the expression is put in a pattern context, and it won't be rewritten. On the contrary, you should use anti-quotes whose kind (<code>[%e ...]</code>, <code>[%p ...]</code>) match the context. For example, you should write:</p><pre class="language-ocaml"><code>fun [%stri let ([%p pat] : [%t type_]) = [%e expr]] ->
|
||
do_something_with pat type_ expr</code></pre><p> <div style="display: flex; justify-content:space-between"><div><a href="generating-code.html" title="generating-code">< Generating AST nodes</a> </div><div><a href="ast-traversal.html" title="ast-traversal">Traversing the AST ></a> </div></div></p></div></body></html>
|