Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Auto-unwrap options when accessing record fields. #1

Closed
wants to merge 2 commits into from

Conversation

cristianoc
Copy link
Owner

Extend the type checker to auto-unwrap options when accessing record fields.

Example interactive session.

./ocaml
# type t = { a: int; b: t option};;
type t = { a : int; b : t option; }

# let testoa (x:t option) = x.a;;
val testoa : t option -> int option = <fun>

# let testb x = x.b;;
val testb : t -> t option = <fun>

# let testbb x = x.b.b;;
val testbb : t -> t option = <fun>

# let testbba x = x.b.b.a;;
val testbba : t -> int option = <fun>

Properties.

  • Every program typeable before this extension, is still typeable, and has the same type.
  • No new operators.
  • Double options are flattened when accessing an optional field of an optional value.
  • Ad-hoc polymorphism, just as with record disambiguation in stock ocaml. This means that some local record accesses cannot be moved into generic functions.

How to build.

./configure --prefix `pwd`
make world install

Tests.

./ocaml test.ml

Test the developer experience one would have when auto unwrapping options in field access.

When `exp` is of option type, or of option option type, accessing `exp.field` type checks and wraps the result into an option type.
If `field` itself has type option, flatten the double option.

This is just intended to play with the toplevel and type inference.
Actually running the code will lead to segfaults.

To try, build and start an interactive session:
 ```
 ./configure --prefix `pwd`
 make world install
 ./ocaml
 ```

Then:
```ocaml
#   type t = { a: int; b: t option};;
  let testoa (x:t option) = x.a;;
  let testb x = x.b;;
  let testbb x = x.b.b;;
  let testbba x = x.b.b.a;;

type t = { a : int; b : t option; }
# val testoa : t option -> int option = <fun>
# val testb : t -> t option = <fun>
# val testbb : t -> t option = <fun>
# val testbba : t -> int option = <fun>
```
… fields.

At type-checking time, also generate code to auto-unwrap values.
Now examples can be executed in the toplevel.

Added a test file `test.ml` which ran be run like this:

```
make world install
./ocaml test.ml
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant