Skip to content

[RFC] Type-directed array literal disambiguation - #13340

Merged
gasche merged 15 commits into
ocaml:trunkfrom
nojb:type_directed_array_literals
Sep 27, 2024
Merged

gasche merged 15 commits into
ocaml:trunkfrom
nojb:type_directed_array_literals

Conversation

@nojb

@nojb nojb commented Jul 30, 2024

Copy link
Copy Markdown
Contributor

See ocaml/RFCs#46.

The patch modifies the typechecking of array expressions and patterns: if the "expected type" is known to be a floatarray (eg because a suitable type annotation has been given by the programmer), then the array literal is taken to denote a constant of that type (how does this interact with principality?). Note that translation into Lambda does not need any adaptations because the code already has logic to translate arrays in a way that handles both normal arrays and flat float arrays:

| Texp_array expr_list ->

When preparing this PR, I realized that a similar patch had already been discussed in the past, which I had completely forgotten: #9952. However, the approach was slightly different, and the approach here seems to be closer to the one suggested in #9952 (comment).

In any case, I suspect many of the points that were raised in #9952 will again be relevant here. So I consider this PR more of an invitation to (re)open a discussion than a concrete proposal for integration.

An example of the patch in action:

OCaml version 5.3.0+dev0-2023-12-22
Enter #help;; for help.

# let x = [|1.3; 4.5|];;
val x : float array = [|1.3; 4.5|]
# x.(1);;
- : float = 4.5
# let x : floatarray = [|1.3; 4.5|];;
val x : floatarray = <abstr>
# Float.Array.get x 1;;
- : float = 4.5
# let f = function [|a; b|] -> a + b;;
val f : int array -> int = <fun>
# f [|1;3|];;
- : int = 4
# let f = function [|a; b|] -> a +. b;;
val f : float array -> float = <fun>
# f [|1.;3.|];;
- : float = 4.
# let f : floatarray -> _ = function [|a; b|] -> a +. b;;
val f : floatarray -> float = <fun>
# f [|1.;3.|];;
- : float = 4.

@goldfirere

Copy link
Copy Markdown
Contributor

The code is delightfully simple. Thank you! I think there are a few ways in which it could be improved -- notably, by checking whether an expected type is principally known. Also, I worry about the use of Typeopt here. That looks through private and [@@unboxed] types, which might mean we e.g. construct a value of a synonym of a floatarray that maintains an invariant without checking the invariant.

I'm confident the above issues can be resolved. So the bigger question is: once the implementation has settled, should we merge? I'd like to, but we should form some consensus on this point.

In the meantime, do you think you could add some tests to show this in action? That might help to crystallize our understanding. Or, if your interest in this was just as a small mockup, let me know and we can look into taking this over.

@nojb

nojb commented Aug 2, 2024

Copy link
Copy Markdown
Contributor Author

notably, by checking whether an expected type is principally known.

I gave it a try, but could not figure out how to do it (I am not sure what this means exactly, in fact). Do you have any pointers?

In the meantime, do you think you could add some tests to show this in action?

Yes, I will add some tests soon. Thanks!

@goldfirere

Copy link
Copy Markdown
Contributor

A type is known principally if the knowledge of that type is completely predictable. Maybe it would be better to say "known predictably" or "specified by the user". A type annotation can cause a type to be known principally, or being an argument to a function whose argument type is known principally.

The good news is that it's very easy to check this property: just use is_principal (from Ctype). And it seems we still allow disambiguation even with not-principally-known types, but we warn when doing so. Use warn_non_principal.

And instead of Typeopt, I recommend expand_head, which should have the behavior you're looking for.

Thanks!

@nojb

nojb commented Aug 3, 2024

Copy link
Copy Markdown
Contributor Author

Thanks for the pointers @goldfirere!

just use is_principal (from Ctype).

For future reference, this is apparently referencing the following function of the JS fork:

https://github.com/ocaml-flambda/flambda-backend/blob/bca81e9f87b7833089d16bbfd694fc8be36dacf5/ocaml/typing/ctype.mli#L631-L633

which I cherry-picked to this PR.

And instead of Typeopt, I recommend expand_head, which should have the behavior you're looking for.

Thanks, I did that. I am not sure if the way I check whether the expected type "is" floatarray is the most adequate one, though.

In the meantime, do you think you could add some tests to show this in action?

Yes, I will add some tests soon. Thanks!

I added a few tests to get started (including one that exercises the principality aspect).

@gasche

gasche commented Aug 3, 2024

Copy link
Copy Markdown
Member

is_principal is available in trunk, but it is in Typecore. You can move it to Ctype as in the JS fork, but then you should remove the one in Typecore.

@nojb

nojb commented Aug 3, 2024

Copy link
Copy Markdown
Contributor Author

is_principal is available in trunk, but it is in Typecore. You can move it to Ctype as in the JS fork, but then you should remove the one in Typecore.

Thanks, I had missed it; I removed the one I had added to Ctype.

@goldfirere goldfirere left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Implementation looks pretty good to me, modulo some suggestions I've made here.

But do we want this patch? I'm not the one to decide such things.

Also, this would need a user's manual update before merging.

Comment thread typing/typecore.ml Resolved
Comment thread typing/typecore.ml Outdated
| Tconstr (path, [], _) -> Path.same path Predef.path_floatarray
| _ -> false
then
Predef.type_float, Predef.type_floatarray

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Someone more expert in these matters than me may say otherwise, but I think you want generic_instance Predef.type_float for the element type. This seems to match the fact that the general case calls newgenvar.

Generally speaking, you don't want to use types from Predef directly; you usually want to take an instance or generic_instance of them. Using the type directly (without instance) means taking the master copy and putting it in a structure. If we then learn more about the type (say by a GADT pattern-match), we might influence that master copy.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I ended up using instance Predef.type_float (I guess that for parameter-less types there is no difference). This matches what is done elsewhere in Typecore, eg type_constant.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It surprised me, too, but there is a difference, actually. Both instance and generic_instance copy the type. instance additionally changes all levels that are generic_level to be the current level (that is, the result of get_current_level ()). We consider a type whose level is generic_level to be principally known: either this type came from a user-written type annotation, or inference on the type has been completed (for the type of a let-bound x) and the type has been generalized. So instance Predef.type_float produces a float that is not principally known (and couldn't be used in type-directed disambiguation, say) while generic_instance Predef.type_float can be used for type-directed disambiguation.

I see Typecore.type_constant uses instance. I'm not actually sure why that is: If I see that something is 1, its type is definitely int; saying (1 : int) shouldn't be different from 1. So I'm not exactly sure what's best here; we should wait for @garrigue.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK, I left instance for now until the issue is clarified. Thanks for the explanation by the way, it is appreciated!

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@goldfirere Type synthesized by type_exp are supposed to have a level no higher than current_level, which reflects the fact than syntax-directed rules for Hindley-Milner have only monotypes on the right-hand side. To make easier to follow this invariant, most functions return type nodes at current_level. Of course, one could start from generic_level and then use update_level to get back to current_level, but this introduces extra costs.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see what you're saying here, but the existence of generic_level is additionally used to affect principality of type inference. If I have an expression 5, I would expect its type int to be principally known. This would suggest using generic_instance instead of instance. But now that I think about it, I can't find a way in which this would change any user-facing behavior, so maybe this isn't a point that needs debating...

Comment thread typing/typecore.ml Resolved
Comment thread typing/typecore.ml Resolved
@nojb

nojb commented Aug 6, 2024

Copy link
Copy Markdown
Contributor Author

modulo some suggestions I've made here.

Thanks for the review @goldfirere! I will tweak the patch as suggested shortly.

But do we want this patch? I'm not the one to decide such things.

Some names off the top of my head whose opinion would be welcome: @yallop @garrigue @lpw25 @gasche

this would need a user's manual update before merging.

Indeed. However, I will wait to see if the discussion advances a bit more before doing this part.

@garrigue

garrigue commented Aug 6, 2024

Copy link
Copy Markdown
Contributor

I do want to look into this, in particular the principality part, but I see that I can be slow. So in the end you don't need to wait for me too long.

Comment thread typing/typecore.ml Resolved
@goldfirere

Copy link
Copy Markdown
Contributor

I don't think this is particularly pressing, so I'm happy to wait for @garrigue. I will bring this up at our next meeting, if you don't get a chance to get to it beforehand.

@goldfirere

Copy link
Copy Markdown
Contributor

I'm happy with the implementation, pending more expert review, which we understand may take some time to get.

@goldfirere

Copy link
Copy Markdown
Contributor

And I forgot to say: Thanks, @nojb for doing this!

@yallop

yallop commented Aug 7, 2024 •

Copy link
Copy Markdown
Member

This looks good to me, but I think we should also add top-level printing support, so that we see

# let x : floatarray = [| 3.; 4. |];;
val x : floatarray = [|3.; 4.|]

rather than

# let x : floatarray = [| 3.; 4. |];;
val x : floatarray = <abstr>

I've proposed an implementation here: nojb#13

@nojb

nojb commented Aug 7, 2024

Copy link
Copy Markdown
Contributor Author

I've proposed an implementation here: nojb#13

This is now merged into the PR. Thanks again!

Comment thread typing/typecore.ml Outdated
disambiguation of an array literal. *)
let disambiguate_array_literal env expected_ty =
if is_principal expected_ty then
if is_floatarray_type env expected_ty then

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I assume this is written like that (and not if is_principal expected_ty && is_floatarray_type env expected_ty then Some ... else None) to support, later, other kinds of arrays. Is that right?

In particular, it could already be useful to support bytes (and possibly string) literals. Would that require a lot of extra changes in the backend?

@alainfrisch

Copy link
Copy Markdown
Contributor

I like the feature!

I believe that disambiguating get/set operations would be even more useful (and coherent with records). Do we foresee extra difficulties, compared to this PR, both in terms of implementation and acceptability of the feature?

@garrigue

Copy link
Copy Markdown
Contributor

I see no problem on the principality side.
To follow-up on the discussion in #9952, which I did not attend, (local) ambiguity and principality are two different problems. Local ambiguity says that there is a subexpression that could be given two different meanings, ignoring the context. Principality says that there exists a type system such that all programs have at most one principal type, or no type at all.
What you do here is fine for principality, since either there is positive information that this is a floatarray, that should be available in any derivation, or there is none, and you just revert to the default case, which is incompatible with floatarray. If there is partial information, you fail, which is again ok, since the same type system could be made to not accept such cases.

This said, in ocaml we usual try to make the principal mode compatible with the default mode, i.e. if the default mode succeeds, the principal mode should ideally succeed with a principality warning. So I believe the order of the checks should be inverted: you should first check whether it is a floatarray, and if it is, then check for principality and emit a warning if needed. This would be more helpful to programmers.

Note that the above comment on principality assumes that expected types only come from type annotations and constructors. In practice ocaml also propagates expected types from function to their arguments, which is not strictly principal, but only principal modulo the maximality of derivations, i.e. we need to disallow taking derivations which instantiate types more than needed, as they could end up being more "informative". Some people call this "restriction to principal derivations", which I find rather strange, as it makes the definition cyclic.

@nojb
nojb force-pushed the type_directed_array_literals branch from 9acf83d to ce706fb Compare August 16, 2024 16:13
@nojb

nojb commented Aug 16, 2024

Copy link
Copy Markdown
Contributor Author

So I believe the order of the checks should be inverted:

Thanks for the review @garrigue! I committed your suggestion in ce706fb (the effect can be seen in the one of the tests).

@gasche

gasche commented Sep 20, 2024

Copy link
Copy Markdown
Member

We now have a consensus among language maintainers to merge this feature, and the implementation has been reviewed for correctness. Great! But before I click "merge", I would like to ask about documentation: how are users supposed to find out about this feature? I think it would be nice if you could add some documentation for the PR, either in the user manual (if you find a good place to put it) or, at least, in the header documentation of the Float.Array module.

(It would be nice if the documentation included examples where type inference works as intended, and also examples where it does not and adding an annotation is useful.)

@gasche

gasche commented Sep 20, 2024

Copy link
Copy Markdown
Member

(Also check-typo: no Changes, and line too long at ./typing/typecore.ml:3903.81)

@nojb

nojb commented Sep 20, 2024 •

Copy link
Copy Markdown
Contributor Author

Thanks @gasche for working to achieve consensus around this feature!

I think it would be nice if you could add some documentation for the PR, either in the user manual (if you find a good place to put it) or, at least, in the header documentation of the Float.Array module.

I will see to add something to the manual.

(Also check-typo:

Will fix, thanks.

@nojb

nojb commented Sep 21, 2024

Copy link
Copy Markdown
Contributor Author

I pushed some documentation in a new section of the "Language extensions" chapter (comments welcome), updated Changes and fixed the check-typo warnings.

@goldfirere goldfirere left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I’m not experienced with the usual formatting, etc., of the manual, but I’ve read the text and offered a few small comments. As always, thanks for this!

let x = [|42.|];;
\end{caml_example}

The compiler will exploit the knowledge it gleans from the context of the array

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This sentence is redundant to me — I would just drop it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, thanks.


\begin{caml_example}{verbatim}
let x = [|42.|];;
\end{caml_example}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would explicitly say that x gets the type float array here.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not sure if this is needed since the caml_example environment will show the toplevel output:

val x : float array = [|42.|]

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Even though it is contained in the evaluation output, I still added the sentence to the documentation; the repetition did not feel superfluous.

[@@expect error];;
\end{caml_example}

Indeed, here the information learned from the use of "a" as a "floatarray"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Drop “Indeed” here

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, thanks.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would say somewhere that the rules here are exactly the same as for constructor disambiguation.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree that the description should mention type-directed disambiguation for constructors and records.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added a mention of this, with a reference to the section in question.

(Introduced in OCaml 5.4)

Since OCaml 5.4, array literal syntax @"[|" e1 ';' e2 ';' ... ';' eN "|]"@ can
be used to denote values of type "'a array" as well as "floatarray", both in

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would reverse the enumeration:

Since OCaml 5.4 ... can be used to denote values of type "floatarray" as well as "'a array", both in

to put the 5.4 novelty first.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, thanks.


\begin{caml_example}{verbatim}
let x = [|42.|];;
\end{caml_example}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not sure if this is needed since the caml_example environment will show the toplevel output:

val x : float array = [|42.|]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree that the description should mention type-directed disambiguation for constructors and records.


The compiler will use contextual information to infer the type of the array
literal. However, in the absence of any specific contextual information, it will
be assumed that the array literal is of type "'a array":

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since the "contextual information" that the typechecker is using is the expected type, I find this description a bit too circular.

Maybe

The compiler matches the expected type of the expression or pattern with the type of the literal. In the absence of an expected type, array literals are assumed to be of type "'a array":

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Amended as suggested, thanks.


The compiler will exploit the knowledge it gleans from the context of the array
literal to decide which type to assign to it. In the following examples,
the array literal is assigned type "floatarray":

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have the impression that this sentence is redundant once we state clearly that the compiler is using the expected type. I would keep the examples but move them before the "defaulting to 'a array".

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I removed the sentence (as suggested by @goldfirere as well).

information that it learns from the context of the array literal to disambiguate
it. In the next example, the use of "Float.Array.get" tells the compiler that
"a" must be of type "floatarray" and the array literal pattern is interpreted
accordingly:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not sure we need this section, and the term any type information that it learns from the context is too imprecise and is contradicted by your next example.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I removed this paragraph. Thanks.


However, the order matters. In the following example, type disambiguation works
because the type information learned in the "then" branch of the conditional is
propagated to the "else" branch.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This would be the right place to mention the non-principal-disambiguation warning.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added a mention of the warning just after the example.

@@ -0,0 +1,74 @@
(Introduced in OCaml 5.4)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are missing the forward links in expr.etex and patterns.etex.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed, thanks.

@nojb

nojb commented Sep 24, 2024

Copy link
Copy Markdown
Contributor Author

Thanks @goldfirere and @Octachron for your suggestions concerning the documentation. I pushed a new commit that should address all points; I also reworded a bit the last paragraph which illustrates the non-principal case. I would appreciate any further comments you may have. Thanks!

@goldfirere

Copy link
Copy Markdown
Contributor

Looks good to me!

@gasche gasche left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving based on the existing reviews, consensus on the feature, and documentation. Thanks!

I am planning to let it float for a day or two, forget about it, then merge.

@gasche
gasche merged commit 33d2e76 into ocaml:trunk Sep 27, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants