|
| 1 | +(* |
| 2 | + * Copyright (c) 2021, Facebook, Inc. |
| 3 | + * All rights reserved. |
| 4 | + * |
| 5 | + * This source code is licensed under the MIT license found in the |
| 6 | + * LICENSE file in the "hack" directory of this source tree. |
| 7 | + * |
| 8 | + *) |
| 9 | + |
| 10 | +open Hh_prelude |
| 11 | +open Aast |
| 12 | +open Typing_defs |
| 13 | +module Env = Tast_env |
| 14 | +module Cls = Decl_provider.Class |
| 15 | + |
| 16 | +let get_name dty = |
| 17 | + match get_node dty with |
| 18 | + | Tapply ((_, name), []) -> Some name |
| 19 | + | _ -> None |
| 20 | + |
| 21 | +(* Check that the base type of an enum or (enum class) is not an alias |
| 22 | + * to the enum being defined: |
| 23 | + * |
| 24 | + * enum Foo : Foo {} |
| 25 | + * enum Bar0 : Bar1 {} |
| 26 | + * enum Bar1 : Bar0 {} |
| 27 | + * |
| 28 | + * Such code would make HHVM fatal. |
| 29 | + * |
| 30 | + * Note that we have a similar check for enum/class constants themselves in |
| 31 | + * Cyclic_class_constant but it doesn't take into account the empty enums. |
| 32 | + *) |
| 33 | +let find_cycle env class_name = |
| 34 | + (* Note w.r.t. Cyclic_class_constant: |
| 35 | + * Since `self` is not allowed (parsing error) in this position, we just |
| 36 | + * keep track of the hints we see. |
| 37 | + *) |
| 38 | + let rec spot_target seen current = |
| 39 | + let open Option in |
| 40 | + let enum_def = Env.get_enum env current in |
| 41 | + let enum_info = enum_def >>= Cls.enum_type in |
| 42 | + let te_base = enum_info >>= fun info -> get_name info.te_base in |
| 43 | + match te_base with |
| 44 | + | None -> None |
| 45 | + | Some base -> |
| 46 | + if SSet.mem base seen then |
| 47 | + Some seen |
| 48 | + else |
| 49 | + spot_target (SSet.add base seen) base |
| 50 | + in |
| 51 | + spot_target SSet.empty class_name |
| 52 | + |
| 53 | +let handler = |
| 54 | + object |
| 55 | + inherit Tast_visitor.handler_base |
| 56 | + |
| 57 | + method! at_class_ env c = |
| 58 | + let (pos, c_name) = c.c_name in |
| 59 | + match find_cycle env c_name with |
| 60 | + | Some stack -> |
| 61 | + Errors.add_typing_error |
| 62 | + Typing_error.(primary @@ Primary.Cyclic_class_def { pos; stack }) |
| 63 | + | None -> () |
| 64 | + end |
0 commit comments