Skip to content
This repository has been archived by the owner on Feb 2, 2023. It is now read-only.

Add a "with" syntax for patterns

Leo White edited this page Feb 18, 2014 · 13 revisions

Git branch: with-patterns

Outline

This project is to add a "with" syntax for pattern guards to OCaml. This has previously been implemented in the ocaml-patterns preprocessor.

A with guard is similar to a when guard except that instead of matching an expression against true it can match an expression against any pattern. This also allows with guards to bind variables for use in the case's expression.

Examples

The following example calls lookup on the matched x and then checks that the result matches Some v. This v can then be used in the case expression.

match e with
  Var x with Some v = lookup x env -> v
| Var x -> failwith ("Unbound variable " ^ x)
| Const v -> v

With guards can also be used with or-patterns to bind variables:

match x with
  Foo(y, z)
| Bar y with z = 3 -> y + z

or similarly:

let f (Some x | None with x = 0) = x

Things to do

Add with guards to the parser and parsetree

  • Expertise: ★★☆☆☆
  • Time: ★★☆☆☆
  • Mantis: None
  • Mentor: Leo/Jeremy
  • Who is working on this: ???
  • What needs to be done: Add a with <pattern> = <expression> production to the parser. This should be placed wherever a when guard is allowed. This will require adding a constructor for with guards to the parsetree.

Add with guards to or-patterns in the parser

  • Expertise: ★★☆☆☆
  • Time: ★★☆☆☆
  • Mantis: None
  • Mentor: Leo/Jeremy
  • Who is working on this: ???
  • What needs to be done: with guards should also be allowed on or-patterns, even though when guards are not allowed on them . We will only (for now) allow exhaustive patterns for with guards on or-patterns, so the reasons for not allowing when guards on them do not apply.

Add translations for with guards to typecore.ml

  • Expertise: ★★★☆☆
  • Time: ★★★☆☆
  • Mantis: None
  • Mentor: Leo/Jeremy
  • Who is working on this: ???
  • What needs to be done: The guards must be typechecked and translated into the typedtree in typecore.ml.

Add check for exhaustivity of or-pattern with guards

  • Expertise: ★★★☆☆
  • Time: ★★☆☆☆
  • Mantis: None
  • Mentor: Leo/Jeremy
  • Who is working on this: ???
  • What needs to be done: The exhaustivity checker (parmatch.ml) should be used to check that with guards on or-patterns are exhaustive.

Add with guards to the pattern matching engine

  • Expertise: ★★★★☆
  • Time: ★★★★☆
  • Mantis: None
  • Mentor: Leo/Jeremy
  • Who is working on this: ???
  • What needs to be done: The actual compilation of with guards would be done in bytecomp/matching.ml. This file is complicated, and it helps to read the paper that is referenced in the comments at the top of the file.