landmarks icon indicating copy to clipboard operation
landmarks copied to clipboard

A example of typechecking failure in generated code

Open mlasson opened this issue 3 years ago • 0 comments

How to reproduce:

Run the ppx in automatic mode on :

  module M = struct
    type t = A | B
  end

  class a =
    object
      method f = M.A
    end

  class b =
    object
      inherit a

      method! f = B
    end

What happens ?

Class b get translated into:

    class b =
      object
        inherit  a
        method! f =
          Landmark.enter __generated_landmark;
          let r = try B with e -> (Landmark.exit  __generated_landmark; Landmark.raise e) in
          Landmark.exit  __generated_landmark;
          r
   end

which triggers "Error: Unbound constructor B" because the typechecker does not know at this point that the B has the same type as the method's returned type.

Proposed Solution

We could add type annotations ("'a") to guide the inference (we have to make sure that 'a is fresh of course).

    class b =
      object
        inherit  a
        method! f : 'a =
          Landmark.enter __generated_landmark;
          let r = try (B : 'a) with e -> (Landmark.exit  __generated_landmark; Landmark.raise e) in
          Landmark.exit  __generated_landmark;
          r
   end

If there's an annotation on the returned type we probably should copy it around the body in a similar fashion.

mlasson avatar Aug 19 '21 10:08 mlasson