Avoid using decl_class_type wherever possible
[hiphop-php.git] / hphp / hack / src / typing / tast_check / string_cast_check.ml
blob66cfe5b376c33602611ef0769bc802631357dafd
1 (**
2 * Copyright (c) 2018, Facebook, Inc.
3 * All rights reserved.
5 * This source code is licensed under the MIT license found in the
6 * LICENSE file in the "hack" directory of this source tree.
8 *)
10 open Tast
12 module Env = Tast_env
13 module TCO = TypecheckerOptions
14 module SN = Naming_special_names
16 let should_enforce env =
17 TCO.disallow_stringish_magic (Env.get_tcopt env)
19 (** Produce an error on (string) casts of objects. Currently it is allowed in HHVM to
20 cast an object if it is Stringish (i.e., has a __toString() method), but all
21 (string) casts of objects will be banned in the future. Eventually,
22 __toString/(string) casts of objects will be removed from HHVM entirely. *)
24 let check__toString m is_static =
25 let (pos, name) = m.m_name in
26 if name = SN.Members.__toString
27 then begin
28 if m.m_visibility <> Public || is_static
29 then Errors.toString_visibility pos;
30 match m.m_ret with
31 | Some (_, Hprim Tstring) -> ()
32 | Some (p, _) -> Errors.toString_returns_string p
33 | None -> ()
34 end
36 let handler = object
37 inherit Tast_visitor.handler_base
39 method! at_expr env ((p, _), expr) =
40 match expr with
41 | Cast ((_, Hprim Tstring), te) when should_enforce env ->
42 let ((_, ty), _) = te in
43 (* Whitelist mixed/nonnull *)
44 if not (Env.is_stringish env ty ~allow_mixed:true)
45 then Errors.string_cast p (Env.print_ty env ty)
46 | _ -> ()
48 method! at_static_method _ m = check__toString m true
50 method! at_method_ _ m = check__toString m false
52 method! at_constructor _ m = check__toString m true
53 end