language
stringlengths 0
24
| filename
stringlengths 9
214
| code
stringlengths 99
9.93M
|
---|---|---|
OCaml | hhvm/hphp/hack/src/facts/ffi/rust_facts_ffi.ml | external extract_as_json_ffi :
int ->
(string * string) list ->
Relative_path.t ->
string ->
bool ->
string option = "extract_as_json_ffi" |
Rust | hhvm/hphp/hack/src/facts/rust_facts_ffi/rust_facts_ffi.rs | // Copyright (c) 2019, Facebook, Inc.
// All rights reserved.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use direct_decl_parser::DeclParserOptions;
use hhbc_string_utils::without_xhp_mangling;
use ocamlrep::bytes_from_ocamlrep;
use ocamlrep::ptr::UnsafeOcamlPtr;
use ocamlrep_ocamlpool::ocaml_ffi;
use relative_path::RelativePath;
ocaml_ffi! {
fn extract_as_json_ffi(
flags: i32,
auto_namespace_map: Vec<(String, String)>,
filename: RelativePath,
text_ptr: UnsafeOcamlPtr,
mangle_xhp: bool,
) -> Option<String> {
// Safety: the OCaml garbage collector must not run as long as text_ptr
// and text_value exist. We don't call into OCaml here, so it won't.
let text_value = unsafe { text_ptr.as_value() };
let text = bytes_from_ocamlrep(text_value).expect("expected string");
extract_facts_as_json_ffi(
((1 << 0) & flags) != 0, // php5_compat_mode
((1 << 1) & flags) != 0, // hhvm_compat_mode
((1 << 2) & flags) != 0, // allow_new_attribute_syntax
((1 << 3) & flags) != 0, // enable_xhp_class_modifier
((1 << 4) & flags) != 0, // disable_xhp_element_mangling
auto_namespace_map,
filename,
text,
mangle_xhp,
)
}
}
fn extract_facts_as_json_ffi(
php5_compat_mode: bool,
hhvm_compat_mode: bool,
allow_new_attribute_syntax: bool,
enable_xhp_class_modifier: bool,
disable_xhp_element_mangling: bool,
auto_namespace_map: Vec<(String, String)>,
filename: RelativePath,
text: &[u8],
mangle_xhp: bool,
) -> Option<String> {
let opts = DeclParserOptions {
auto_namespace_map,
hhvm_compat_mode,
php5_compat_mode,
allow_new_attribute_syntax,
enable_xhp_class_modifier,
disable_xhp_element_mangling,
keep_user_attributes: false, // Not needed for any OCaml Facts use cases
..Default::default()
};
let arena = bumpalo::Bump::new();
let parsed_file = direct_decl_parser::parse_decls_for_bytecode(&opts, filename, text, &arena);
if parsed_file.has_first_pass_parse_errors {
None
} else if mangle_xhp {
Some(facts_rust::decls_to_facts_json(&parsed_file, false))
} else {
without_xhp_mangling(|| Some(facts_rust::decls_to_facts_json(&parsed_file, false)))
}
} |
hhvm/hphp/hack/src/facts/symbols/dune | (library
(name index_builder)
(wrapped false)
(libraries
core_kernel
facts
folly_stubs
heap_shared_mem_hash
hhi
parser
parser_options
process
process_types
procs_entry_point
search_utils
server_env
sqlite_utils
utils_hash)) |
|
OCaml | hhvm/hphp/hack/src/facts/symbols/indexBuilder.ml | (*
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the "hack" directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*)
open Hh_prelude
open IndexBuilderTypes
open SearchUtils
open SearchTypes
open Facts
(* Keep track of all references yet to scan *)
let files_scanned = ref 0
let error_count = ref 0
(* Extract kind, abstract, and final flags *)
let get_details_from_info (info_opt : Facts.type_facts option) :
si_kind * bool * bool =
Facts_parser.(
match info_opt with
| None -> (SI_Unknown, false, false)
| Some info ->
let k =
match info.kind with
| TKClass -> SI_Class
| TKInterface -> SI_Interface
| TKEnum -> SI_Enum
| TKTrait -> SI_Trait
| TKMixed -> SI_Mixed
| TKTypeAlias -> SI_Typedef
| _ -> SI_Unknown
in
let is_abstract = info.flags land flags_abstract > 0 in
let is_final = info.flags land flags_final > 0 in
(k, is_abstract, is_final))
let convert_facts ~(path : Relative_path.t) ~(facts : Facts.facts) : si_capture
=
let relative_path_str = Relative_path.suffix path in
(* Identify all classes in the file *)
let class_keys = InvSMap.keys facts.types in
let classes_mapped =
List.map class_keys ~f:(fun key ->
let info_opt = InvSMap.find_opt key facts.types in
let (kind, is_abstract, is_final) = get_details_from_info info_opt in
{
(* We need to strip away the preceding backslash for hack classes
* but leave intact the : for xhp classes. The preceding : symbol
* is needed to distinguish which type of a class you want. *)
sif_name = Utils.strip_ns key;
sif_kind = kind;
sif_filepath = relative_path_str;
sif_is_abstract = is_abstract;
sif_is_final = is_final;
})
in
(* Identify all functions in the file *)
let functions_mapped =
List.map facts.functions ~f:(fun funcname ->
{
sif_name = funcname;
sif_kind = SI_Function;
sif_filepath = relative_path_str;
sif_is_abstract = false;
sif_is_final = false;
})
in
(* Handle constants *)
let constants_mapped =
List.map facts.constants ~f:(fun constantname ->
{
sif_name = constantname;
sif_kind = SI_GlobalConstant;
sif_filepath = relative_path_str;
sif_is_abstract = false;
sif_is_final = false;
})
in
(* Return unified results *)
List.append classes_mapped functions_mapped |> List.append constants_mapped
(* Parse one single file and capture information about it *)
let parse_one_file
~(namespace_map : (string * string) list) ~(path : Relative_path.t) :
si_capture =
let filename = Relative_path.to_absolute path in
let text = In_channel.read_all filename in
(* Just the facts ma'am *)
let fact_opt =
Facts_parser.from_text
~php5_compat_mode:false
~hhvm_compat_mode:true
~disable_legacy_soft_typehints:false
~allow_new_attribute_syntax:false
~disable_legacy_attribute_syntax:false
~enable_xhp_class_modifier:false
~disable_xhp_element_mangling:false
~mangle_xhp_mode:false
~auto_namespace_map:namespace_map
~filename:path
~text
in
(* Iterate through facts and print them out *)
let result =
match fact_opt with
| Some facts -> convert_facts ~path ~facts
| None -> []
in
files_scanned := !files_scanned + 1;
result
(* Parse the file using the existing context*)
let parse_file (ctxt : index_builder_context) (path : Relative_path.t) :
si_capture =
parse_one_file ~path ~namespace_map:ctxt.namespace_map
(* Parse a batch of files *)
let parse_batch
(ctxt : index_builder_context)
(acc : si_capture)
(files : Relative_path.t list) : si_capture =
List.fold files ~init:acc ~f:(fun acc file ->
try
let res = (parse_file ctxt) file in
List.append res acc
with
| exn ->
error_count := !error_count + 1;
Hh_logger.log
"IndexBuilder exception: %s. Failed to parse [%s]"
(Caml.Printexc.to_string exn)
(Relative_path.to_absolute file);
acc)
let parallel_parse
~(workers : MultiWorker.worker list option)
(files : Relative_path.t list)
(ctxt : index_builder_context) : si_capture =
MultiWorker.call
workers
~job:(parse_batch ctxt)
~neutral:[]
~merge:List.append
~next:(MultiWorker.next workers files)
let entry =
WorkerControllerEntryPoint.register ~restore:(fun () ~(worker_id : int) ->
Hh_logger.set_id (Printf.sprintf "indexBuilder %d" worker_id))
let gather_file_list (path : string) : Relative_path.t list =
Find.find ~file_only:true ~filter:FindUtils.file_filter [Path.make path]
|> List.map ~f:(fun path -> Relative_path.create_detect_prefix path)
(* Run something and measure its duration *)
let measure_time ~(silent : bool) ~f ~(name : string) =
let start_time = Unix.gettimeofday () in
let result = f () in
let end_time = Unix.gettimeofday () in
if not silent then
Hh_logger.log "%s [%0.1f secs]" name (end_time -. start_time);
result
(* All data is ready. Identify unique namespaces and filepaths *)
let convert_capture (incoming : si_capture) : si_scan_result =
let result =
{
sisr_capture = incoming;
sisr_namespaces = Caml.Hashtbl.create 0;
sisr_filepaths = Caml.Hashtbl.create 0;
}
in
let ns_id = ref 1 in
List.iter incoming ~f:(fun s ->
(* Find / add namespace *)
let (namespace, _name) = Utils.split_ns_from_name s.sif_name in
if not (Caml.Hashtbl.mem result.sisr_namespaces namespace) then (
Caml.Hashtbl.add result.sisr_namespaces namespace !ns_id;
incr ns_id
);
(* Find / add filepath hashes *)
if not (Caml.Hashtbl.mem result.sisr_filepaths s.sif_filepath) then
let path_hash = SharedMemHash.hash_string s.sif_filepath in
Caml.Hashtbl.add result.sisr_filepaths s.sif_filepath path_hash);
result
(* Run the index builder project *)
let go (ctxt : index_builder_context) (workers : MultiWorker.worker list option)
: unit =
(* Gather list of files *)
let name =
Printf.sprintf "Scanned repository folder [%s] in " ctxt.repo_folder
in
let hhconfig_path = Path.concat (Path.make ctxt.repo_folder) ".hhconfig" in
let files =
(* Sanity test. If the folder does not have an .hhconfig file, this is probably
* an integration test that's using a fake repository. Don't do anything! *)
if Disk.file_exists (Path.to_string hhconfig_path) then
let options = ServerArgs.default_options ~root:ctxt.repo_folder in
let (hhconfig, _) = ServerConfig.load ~silent:ctxt.silent options in
let popt = ServerConfig.parser_options hhconfig in
let ctxt =
{ ctxt with namespace_map = ParserOptions.auto_namespace_map popt }
in
measure_time
~silent:ctxt.silent
~f:(fun () -> gather_file_list ctxt.repo_folder)
~name
else (
if not ctxt.silent then
Hh_logger.log
"The repository [%s] lacks an .hhconfig file. Skipping index of repository."
ctxt.repo_folder;
[]
)
in
(* If desired, get the HHI root folder and add all HHI files from there *)
let files =
if Option.is_some ctxt.hhi_root_folder then
let hhi_root_folder_path =
Path.to_string (Option.value_exn ctxt.hhi_root_folder)
in
let name =
Printf.sprintf "Scanned HHI folder [%s] in " hhi_root_folder_path
in
let hhi_files =
measure_time
~silent:ctxt.silent
~f:(fun () -> gather_file_list hhi_root_folder_path)
~name
in
(* Merge lists *)
List.append files hhi_files
else
files
in
(* Spawn the parallel parser *)
let name = Printf.sprintf "Parsed %d files in " (List.length files) in
let capture =
measure_time
~silent:ctxt.silent
~f:(fun () -> parallel_parse ~workers files ctxt)
~name
in
(* Convert the raw capture into results *)
let results = convert_capture capture in
(* Are we exporting a sqlite file? *)
match ctxt.sqlite_filename with
| None -> ()
| Some filename ->
let name =
Printf.sprintf
"Wrote %d symbols to sqlite in "
(List.length results.sisr_capture)
in
measure_time
~silent:ctxt.silent
~f:(fun () -> SqliteSymbolIndexWriter.record_in_db filename results)
~name |
OCaml | hhvm/hphp/hack/src/facts/symbols/indexBuilderTypes.ml | (*
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the "hack" directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*)
type index_builder_context = {
repo_folder: string;
sqlite_filename: string option;
hhi_root_folder: Path.t option;
silent: bool;
namespace_map: (string * string) list;
}
(* Fully parsed data structure *)
type si_scan_result = {
sisr_capture: SearchUtils.si_capture;
sisr_namespaces: (string, int) Caml.Hashtbl.t;
sisr_filepaths: (string, int64) Caml.Hashtbl.t;
} |
OCaml | hhvm/hphp/hack/src/facts/symbols/sqliteSymbolIndexWriter.ml | (*
* Copyright (c) 2019, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open IndexBuilderTypes
open SearchUtils
open Sqlite_utils
(* Some SQL commands we'll need *)
let sql_begin_transaction = "BEGIN TRANSACTION"
let sql_commit_transaction = "COMMIT TRANSACTION"
let sql_create_symbols_table =
"CREATE TABLE IF NOT EXISTS symbols ( "
^ " namespace_id INTEGER NOT NULL, "
^ " filename_hash INTEGER NOT NULL, "
^ " name TEXT NOT NULL, "
^ " kind INTEGER NOT NULL, "
^ " valid_for_acid INTEGER NOT NULL, "
^ " valid_for_acnew INTEGER NOT NULL, "
^ " valid_for_actype INTEGER NOT NULL, "
^ " is_abstract INTEGER NOT NULL, "
^ " is_final INTEGER NOT NULL "
^ ");"
let sql_create_kinds_table =
"CREATE TABLE IF NOT EXISTS kinds ( "
^ " id INTEGER NOT NULL PRIMARY KEY, "
^ " description TEXT NOT NULL "
^ ");"
let sql_create_namespaces_table =
"CREATE TABLE IF NOT EXISTS namespaces ( "
^ " namespace_id INTEGER NOT NULL PRIMARY KEY, "
^ " namespace TEXT NOT NULL "
^ ");"
let sql_insert_kinds =
"INSERT OR IGNORE INTO kinds (id, description) VALUES (1, 'Class');"
^ "INSERT OR IGNORE INTO kinds (id, description) VALUES (2, 'Interface');"
^ "INSERT OR IGNORE INTO kinds (id, description) VALUES (3, 'Enum');"
^ "INSERT OR IGNORE INTO kinds (id, description) VALUES (4, 'Trait');"
^ "INSERT OR IGNORE INTO kinds (id, description) VALUES (5, 'Unknown');"
^ "INSERT OR IGNORE INTO kinds (id, description) VALUES (6, 'Mixed');"
^ "INSERT OR IGNORE INTO kinds (id, description) VALUES (7, 'Function');"
^ "INSERT OR IGNORE INTO kinds (id, description) VALUES (8, 'Typedef');"
^ "INSERT OR IGNORE INTO kinds (id, description) VALUES (9, 'Constant');"
^ "INSERT OR IGNORE INTO kinds (id, description) VALUES (10, 'XHP Class');"
let sql_insert_symbol =
"INSERT INTO symbols "
^ " (namespace_id, filename_hash, name, kind, valid_for_acid, "
^ " valid_for_acnew, valid_for_actype, is_abstract, is_final)"
^ " VALUES"
^ " (?, ?, ?, ?, ?, ?, ?, ?, ?);"
let sql_insert_namespace =
"INSERT INTO namespaces "
^ " (namespace_id, namespace)"
^ " VALUES"
^ " (?, ?);"
(*
* TS 2019-06-17 - Based on testing, creating ANY indexes slows down
* the performance of sqlite autocomplete. By eliminating all indexes,
* we get average query time down to ~20 ms.
*
* This certainly isn't what we expected, but please be careful and run
* performance tests before you add indexes back.
*
* CREATE INDEX IF NOT EXISTS ix_symbols_name ON symbols (name);
*)
let sql_create_indexes = ""
(* Begin the work of creating an SQLite index DB *)
let record_in_db (filename : string) (symbols : si_scan_result) : unit =
(* If the file exists, remove it before starting over *)
if Sys.file_exists filename then Unix.unlink filename;
(* Open the database and do basic prep *)
let db = Sqlite3.db_open filename in
Sqlite3.exec db "PRAGMA synchronous = OFF;" |> check_rc db;
Sqlite3.exec db "PRAGMA journal_mode = MEMORY;" |> check_rc db;
Sqlite3.exec db sql_create_symbols_table |> check_rc db;
Sqlite3.exec db sql_create_indexes |> check_rc db;
Sqlite3.exec db sql_create_kinds_table |> check_rc db;
Sqlite3.exec db sql_create_namespaces_table |> check_rc db;
Sqlite3.exec db sql_insert_kinds |> check_rc db;
Sqlite3.exec db sql_begin_transaction |> check_rc db;
(* Insert symbols and link them to namespaces *)
begin
let stmt = Sqlite3.prepare db sql_insert_symbol in
List.iter symbols.sisr_capture ~f:(fun symbol ->
(* Find nsid and filehash *)
let (ns, _) = Utils.split_ns_from_name symbol.sif_name in
let nsid = Caml.Hashtbl.find symbols.sisr_namespaces ns in
let file_hash =
Caml.Hashtbl.find symbols.sisr_filepaths symbol.sif_filepath
in
(* Insert this symbol *)
Sqlite3.reset stmt |> check_rc db;
Sqlite3.bind stmt 1 (Sqlite3.Data.INT (Int64.of_int nsid))
|> check_rc db;
Sqlite3.bind stmt 2 (Sqlite3.Data.INT file_hash) |> check_rc db;
Sqlite3.bind stmt 3 (Sqlite3.Data.TEXT symbol.sif_name) |> check_rc db;
Sqlite3.bind
stmt
4
(Sqlite3.Data.INT
(Int64.of_int (SearchTypes.kind_to_int symbol.sif_kind)))
|> check_rc db;
Sqlite3.bind
stmt
5
(bool_to_sqlite
(SearchTypes.valid_for_acid symbol.SearchUtils.sif_kind))
|> check_rc db;
Sqlite3.bind
stmt
6
(bool_to_sqlite
(SearchTypes.valid_for_acnew symbol.SearchUtils.sif_kind
&& not symbol.SearchUtils.sif_is_abstract))
|> check_rc db;
Sqlite3.bind
stmt
7
(bool_to_sqlite
(SearchTypes.valid_for_actype symbol.SearchUtils.sif_kind))
|> check_rc db;
Sqlite3.bind stmt 8 (bool_to_sqlite symbol.sif_is_abstract)
|> check_rc db;
Sqlite3.bind stmt 9 (bool_to_sqlite symbol.sif_is_final) |> check_rc db;
Sqlite3.step stmt |> check_rc db);
Sqlite3.finalize stmt |> check_rc db
end;
(* We've seen all namespaces, now insert them and their IDs *)
begin
let stmt = Sqlite3.prepare db sql_insert_namespace in
Caml.Hashtbl.iter
(fun ns id ->
Sqlite3.reset stmt |> check_rc db;
Sqlite3.bind stmt 1 (Sqlite3.Data.INT (Int64.of_int id)) |> check_rc db;
Sqlite3.bind stmt 2 (Sqlite3.Data.TEXT ns) |> check_rc db;
Sqlite3.step stmt |> check_rc db)
symbols.sisr_namespaces;
Sqlite3.finalize stmt |> check_rc db
end;
(* Finish up *)
Sqlite3.exec db sql_commit_transaction |> check_rc db;
(* Reduces database size by 10% even when we have only one transaction *)
Sqlite3.exec db "VACUUM;" |> check_rc db;
(* We are done *)
if not (Sqlite3.db_close db) then
failwith ("Unable to close database " ^ filename) |
hhvm/hphp/hack/src/find/dune | (library
(name find_libc)
(wrapped false)
(modules)
(foreign_stubs
(language c)
(names hh_readdir)))
(library
(name find)
(wrapped false)
(libraries sys_utils find_libc)) |
|
OCaml | hhvm/hphp/hack/src/find/find.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(*****************************************************************************)
(* Prelude *)
(*****************************************************************************)
open Hh_prelude
let lstat_kind file =
Unix.(
try Some (lstat file).st_kind with
| Unix_error (ENOENT, _, _) ->
prerr_endline ("File not found: " ^ file);
None)
external native_hh_readdir : string -> (string * int) list = "hh_readdir"
type dt_kind =
| DT_REG
| DT_DIR
| DT_LNK
(* Sys.readdir only returns `string list`, but we need to know if we have files
* or directories, so if we use Sys.readdir we need to do an lstat on every
* file/subdirectory. The C readdir function gives us both the name and kind,
* so this version does 1 syscall per directory, instead of 1 syscall per file
* and 2 per directory.
*)
let hh_readdir path : (string * dt_kind) list =
List.filter_map (native_hh_readdir path) ~f:(fun (name, kind) ->
match (name, kind) with
| (".", _) -> None
| ("..", _) -> None
| (".git", _) -> None
| (".hg", _) -> None
(* values from `man dirent` *)
| (_, 4) -> Some (name, DT_DIR)
| (_, 8) -> Some (name, DT_REG)
| (_, 10) -> Some (name, DT_LNK)
| (_, 0) ->
Unix.(
(* DT_UNKNOWN - filesystem does not give us the type; do it slow *)
(match lstat_kind (Filename.concat path name) with
| Some S_DIR -> Some (name, DT_DIR)
| Some S_REG -> Some (name, DT_REG)
| Some S_LNK -> Some (name, DT_LNK)
| _ -> None))
| _ -> None)
let fold_files
(type t)
?max_depth
?(filter = (fun _ -> true))
?(file_only = false)
(paths : Path.t list)
(action : string -> t -> t)
(init : t) =
let rec fold depth acc dir =
let acc =
if (not file_only) && filter dir then
action dir acc
else
acc
in
match max_depth with
| Some d when d = depth -> acc
| _ ->
let files = hh_readdir dir in
List.fold_left
~f:(fun acc (file, kind) ->
let file = Filename.concat dir file in
match kind with
| DT_REG when filter file -> action file acc
| DT_DIR -> fold (depth + 1) acc file
| _ -> acc)
~init:acc
files
in
let paths = List.map paths ~f:Path.to_string in
List.fold_left paths ~init ~f:(fold 0)
let iter_files ?max_depth ?filter ?file_only paths action =
fold_files ?max_depth ?filter ?file_only paths (fun file _ -> action file) ()
let find ?max_depth ?filter ?file_only paths =
List.rev @@ fold_files ?max_depth ?filter ?file_only paths List.cons []
let find_with_name ?max_depth ?file_only paths name =
find ?max_depth ?file_only ~filter:(fun x -> String.equal x name) paths
(*****************************************************************************)
(* Main entry point *)
(*****************************************************************************)
type stack =
| Nil
| Dir of (string * dt_kind) list * string * stack
let max_files = 1000
let make_next_files
?(include_symlinks = false)
?name:_
?(filter = (fun _ -> true))
?(others = [])
root =
let rec process
sz (acc : string list) (files : (string * dt_kind) list) dir stack =
if sz >= max_files then
(acc, Dir (files, dir, stack))
else
match files with
| [] -> process_stack sz acc stack
| (name, kind) :: files ->
let name =
if String.equal dir "" then
name
else
Filename.concat dir name
in
(match kind with
| DT_REG when filter name ->
process (sz + 1) (name :: acc) files dir stack
| DT_LNK when include_symlinks && filter name ->
process (sz + 1) (name :: acc) files dir stack
| DT_DIR ->
let dirfiles = hh_readdir name in
process sz acc dirfiles name (Dir (files, dir, stack))
| _ -> process sz acc files dir stack)
and process_stack sz acc = function
| Nil -> (acc, Nil)
| Dir (files, dir, stack) -> process sz acc files dir stack
in
let state =
let dirs =
Path.to_string root :: List.map ~f:Path.to_string others
|> List.filter_map ~f:(fun path ->
Unix.(
match lstat_kind path with
| Some S_REG -> Some (path, DT_REG)
| Some S_DIR -> Some (path, DT_DIR)
| Some S_LNK when include_symlinks -> Some (path, DT_LNK)
| _ -> None))
in
ref (Dir (dirs, "", Nil))
in
fun () ->
let (res, st) = process_stack 0 [] !state in
state := st;
res |
OCaml Interface | hhvm/hphp/hack/src/find/find.mli | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
val make_next_files :
?include_symlinks:bool ->
?name:string ->
?filter:(string -> bool) ->
?others:Path.t list ->
Path.t ->
unit ->
string list
val find :
?max_depth:int ->
?filter:(string -> bool) ->
?file_only:bool ->
Path.t list ->
string list
val find_with_name :
?max_depth:int -> ?file_only:bool -> Path.t list -> string -> string list
val iter_files :
?max_depth:int ->
?filter:(string -> bool) ->
?file_only:bool ->
Path.t list ->
(string -> unit) ->
unit |
C | hhvm/hphp/hack/src/find/hh_readdir.c | /**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*/
#include "hh_readdir.h"
#include <dirent.h>
#include <errno.h>
#include <caml/callback.h>
#include <caml/memory.h>
#include <caml/alloc.h>
#include <caml/fail.h>
#include <caml/unixsupport.h>
#ifdef __APPLE__
/* On glibc platforms (including mingw32) this is conditionally defined
* as appropriate; MacOS doesn't have glibc, but does have d_type, so just
* define a macro with the same name.
*
* If d_type is not available, 0 is returned.
*/
#define _DIRENT_HAVE_D_TYPE
#endif
CAMLprim value hh_readdir(value path) {
CAMLparam1(path);
CAMLlocal3(head, tail, list);
if (Tag_val(path) != String_tag) {
caml_invalid_argument(
"Path must be a string"
);
}
DIR* dir = opendir(String_val(path));
if (!dir) {
/* from caml/unixsupport.h */
unix_error(errno, "opendir", path);
}
list = Val_emptylist;
struct dirent* ent;
while (1) {
errno = 0;
ent = readdir(dir);
if (!ent) {
if (errno) {
unix_error(errno, "readdir", path);
}
break;
}
head = caml_alloc_tuple(2);
#ifdef __APPLE__
Store_field(head, 0, caml_alloc_initialized_string(ent->d_namlen, ent->d_name));
#else
Store_field(head, 0, caml_copy_string(ent->d_name));
#endif
#ifdef _DIRENT_HAVE_D_TYPE
Store_field(head, 1, Val_int(ent->d_type));
#else
// 0 is DT_UNKNOWN
Store_field(head, 1, Val_int(0));
#endif
tail = list;
list = caml_alloc(2, 0);
Store_field(list, 0, head);
Store_field(list, 1, tail);
}
closedir(dir);
CAMLreturn(list);
} |
C/C++ | hhvm/hphp/hack/src/find/hh_readdir.h | /**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*/
#pragma once
#define CAML_NAME_SPACE
#include <caml/mlvalues.h>
/* Like `Sys.readdir`, but returns name * type list instead of name array */
CAMLprim value hh_readdir(value path); |
OCaml | hhvm/hphp/hack/src/fsnotify/fsnotify.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
module List = Core.List
exception Error of string * Unix.error
let wrap f () =
try f () with
| Unix.Unix_error (err, func, msg) ->
let reason =
Printf.sprintf "%s: %s: %s" func msg (Unix.error_message err)
in
raise (Error (reason, err))
| exn ->
let e = Exception.wrap exn in
Exception.reraise e
type watch = Inotify.watch
(* A watch in this case refers to an inotify watch. Inotify watches are used
* to subscribe to events on files in linux kernel.
* Once a watch has been added to a file, the kernel notifies us every time
* the file changes (by sending an event to a pipe, cf env.inotify).
* We need to be able to compare watches because there could be multiple
* paths that lead to the same watch (because of symlinks).
*)
module WMap = Map.Make (struct
type t = watch
let compare = compare
end)
type env = {
fd: Unix.file_descr;
mutable wpaths: string WMap.t;
}
type event = {
path: string;
(* The full path for the file/directory that changed *)
wpath: string; (* The watched path that triggered this event *)
}
let init _roots = { fd = wrap Inotify.create (); wpaths = WMap.empty }
let select_events =
Inotify.
[
S_Create;
S_Delete;
S_Delete_self;
S_Modify;
S_Move_self;
S_Moved_from;
S_Moved_to;
S_Attrib;
]
(* Returns None if we're already watching that path and Some watch otherwise *)
let add_watch env path =
let watch = wrap (fun () -> Inotify.add_watch env.fd path select_events) () in
if WMap.mem watch env.wpaths && WMap.find watch env.wpaths = path then
None
else (
env.wpaths <- WMap.add watch path env.wpaths;
Some watch
)
let check_event_type = function
| Inotify.Access
| Inotify.Attrib
| Inotify.Close_write
| Inotify.Close_nowrite
| Inotify.Create
| Inotify.Delete
| Inotify.Delete_self
| Inotify.Move_self
| Inotify.Moved_from
| Inotify.Moved_to
| Inotify.Open
| Inotify.Ignored
| Inotify.Modify
| Inotify.Isdir ->
()
| Inotify.Q_overflow ->
Printf.printf "INOTIFY OVERFLOW!!!\n";
exit 5
| Inotify.Unmount ->
Printf.printf "UNMOUNT EVENT!!!\n";
exit 5
let process_event env events event =
match event with
| (_, _, _, None) -> events
| (watch, type_list, _, Some filename) ->
List.iter type_list ~f:check_event_type;
let wpath =
try WMap.find watch env.wpaths with
| _ -> assert false
in
let path = Filename.concat wpath filename in
{ path; wpath } :: events
let read env =
let inotify_events = wrap (fun () -> Inotify.read env.fd) () in
List.fold_left inotify_events ~f:(process_event env) ~init:[]
module FDMap = Map.Make (struct
type t = Unix.file_descr
let compare = compare
end)
type fd_select = Unix.file_descr * (unit -> unit)
let make_callback fdmap (fd, callback) = FDMap.add fd callback fdmap
let invoke_callback fdmap fd = (FDMap.find fd fdmap) ()
let select env ?(read_fdl = []) ?(write_fdl = []) ~timeout callback =
let callback () = callback (Unix.handle_unix_error read env) in
let read_fdl = (env.fd, callback) :: read_fdl in
let read_callbacks =
List.fold_left read_fdl ~f:make_callback ~init:FDMap.empty
in
let write_callbacks =
List.fold_left write_fdl ~f:make_callback ~init:FDMap.empty
in
let (read_ready, write_ready, _) =
Unix.select
(List.map read_fdl ~f:fst)
(List.map write_fdl ~f:fst)
[]
timeout
in
List.iter write_ready ~f:(invoke_callback write_callbacks);
List.iter read_ready ~f:(invoke_callback read_callbacks)
(********** DEBUGGING ****************)
(* Can be useful to see what the event actually is, for debugging *)
let _string_of inotify_ev =
let (wd, mask, cookie, s) = inotify_ev in
let mask = String.concat ":" (List.map mask ~f:Inotify.string_of_event) in
let s =
match s with
| Some s -> s
| None -> "\"\""
in
Printf.sprintf
"wd [%u] mask[%s] cookie[%ld] %s"
(Inotify.int_of_watch wd)
mask
cookie
s |
OCaml Interface | hhvm/hphp/hack/src/fsnotify/fsnotify.mli | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
exception Error of string * Unix.error
(* Contains all the inotify context *)
type env
(* A subscription to events for a directory *)
type watch
type event = {
path: string;
(* The full path for the file/directory that changed *)
wpath: string; (* The watched path that triggered this event *)
}
val init : string list -> env
(* Returns None if we're already watching that path and Some watch otherwise *)
val add_watch : env -> string -> watch option
(* A file descriptor and what to do when it is selected *)
type fd_select = Unix.file_descr * (unit -> unit)
val select :
(* The inotify context *)
env ->
?read_fdl:(* Additional file descriptor to select for reading *)
fd_select list ->
?write_fdl:
(* Additional file descriptor to select for writing *)
fd_select list ->
timeout:(* Timeout...like Unix.select *)
float ->
((* The callback for file system events *)
event list -> unit) ->
unit |
Rust | hhvm/hphp/hack/src/generate_hhi/generate_hhi.rs | // Copyright (c) Meta Platforms, Inc. and affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::path::PathBuf;
/// Convert a Hack source file to an HHI interface definition file by removing
/// all function and method bodies.
#[derive(clap::Parser, Debug)]
struct Opts {
/// The Hack source file to generate an HHI file for.
filename: PathBuf,
}
fn main() -> anyhow::Result<()> {
let opts = <Opts as clap::Parser>::parse();
let mut stdout = std::io::BufWriter::new(std::io::stdout().lock());
generate_hhi_lib::run(&mut stdout, &opts.filename)
} |
Rust | hhvm/hphp/hack/src/generate_hhi/generate_hhi_lib.rs | // Copyright (c) Meta Platforms, Inc. and affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::ops::ControlFlow;
use std::path::Path;
use std::sync::Arc;
use parser_core_types::positioned_token::PositionedToken as Token;
use parser_core_types::source_text::SourceText;
use parser_core_types::syntax::Syntax;
use parser_core_types::syntax::SyntaxTypeBase;
use parser_core_types::syntax::SyntaxVariant;
use parser_core_types::token_factory::SimpleTokenFactory;
use parser_core_types::token_kind::TokenKind;
use relative_path::Prefix;
use relative_path::RelativePath;
pub fn run(out: &mut impl std::io::Write, filename: &Path) -> anyhow::Result<()> {
let text = std::fs::read(filename)?;
let source_text = SourceText::make(
Arc::new(RelativePath::make(Prefix::Dummy, filename.to_path_buf())),
&text,
);
let (mut root, _, state) = positioned_parser::parse_script(&source_text, Default::default());
root.rewrite_pre_and_stop(|node| {
match &mut node.syntax {
// remove `<?hh` line if present
SyntaxVariant::MarkupSuffix(..) => {
*node = Syntax::make_missing(&state, 0);
ControlFlow::Break(())
}
// remove function bodies
SyntaxVariant::FunctionDeclaration(f) => {
f.function_body =
Syntax::make_token(Token::make(TokenKind::Semicolon, 0, 0, vec![], vec![]));
ControlFlow::Break(())
}
// remove method bodies
SyntaxVariant::MethodishDeclaration(m) => {
// no body
m.methodish_function_body = Syntax::make_missing(&state, 0);
// always have a semicolon, even if not abstract
m.methodish_semicolon =
Syntax::make_token(Token::make(TokenKind::Semicolon, 0, 0, vec![], vec![]));
ControlFlow::Break(())
}
// remove constant values
SyntaxVariant::ConstantDeclarator(c) => {
// no value
c.constant_declarator_initializer = Syntax::make_missing(&state, 0);
ControlFlow::Break(())
}
_ => ControlFlow::Continue(()),
}
});
out.write_all(b"<?hh\n// @")?;
out.write_all(b"generated from implementation\n\n")?;
root.write_text_from_edited_tree(&source_text, out)?;
out.write_all(b"\n")?;
out.flush()?;
Ok(())
} |
TOML | hhvm/hphp/hack/src/generate_hhi/cargo/generate_hhi/Cargo.toml | # @generated by autocargo
[package]
name = "generate_hhi"
version = "0.0.0"
edition = "2021"
[[bin]]
name = "generate_hhi"
path = "../../generate_hhi.rs"
[dependencies]
anyhow = "1.0.71"
clap = { version = "3.2.25", features = ["derive", "env", "regex", "unicode", "wrap_help"] }
generate_hhi_lib = { version = "0.0.0", path = "../generate_hhi_lib" } |
TOML | hhvm/hphp/hack/src/generate_hhi/cargo/generate_hhi_lib/Cargo.toml | # @generated by autocargo
[package]
name = "generate_hhi_lib"
version = "0.0.0"
edition = "2021"
[lib]
path = "../../generate_hhi_lib.rs"
[dependencies]
anyhow = "1.0.71"
parser_core_types = { version = "0.0.0", path = "../../../parser/cargo/core_types" }
positioned_parser = { version = "0.0.0", path = "../../../parser/api/cargo/positioned_parser" }
relative_path = { version = "0.0.0", path = "../../../utils/rust/relative_path" } |
hhvm/hphp/hack/src/gen_deps/dune | (library
(name gen_deps)
(wrapped false)
(libraries ast naming full_fidelity parser_options procs_procs typing_deps)) |
|
hhvm/hphp/hack/src/globals/dune | (library
(name global_config)
(wrapped false)
(modules globalConfig)
(libraries core_kernel find sys_utils)) |
|
OCaml | hhvm/hphp/hack/src/globals/globalConfig.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
(*****************************************************************************)
(* Configuration file *)
(*****************************************************************************)
let program_name = "hh_server"
(* Configures only the workers. Workers can have more relaxed GC configs as
* they are short-lived processes *)
let gc_control = Gc.get ()
let scuba_table_name =
try Sys.getenv "HH_SCUBA_TABLE" with
| _ -> "hh_server_events"
(* Where to write temp files *)
let tmp_dir = Tmp.hh_server_tmp_dir
let shm_dir =
try Sys.getenv "HH_SHMDIR" with
| _ -> "/dev/shm" |
hhvm/hphp/hack/src/hackc/.clang-format | # The primary clang-format config file.
# TODO(afuller): Set these settings when they aren't broken:
# - AllowShortBlocksOnASingleLine: Empty
---
AccessModifierOffset: -1
AlignAfterOpenBracket: AlwaysBreak
AlignConsecutiveMacros: false
AlignConsecutiveAssignments: false
AlignConsecutiveBitFields: false
AlignConsecutiveDeclarations: false
AlignEscapedNewlines: Left
AlignOperands: DontAlign
AlignTrailingComments: false
AllowAllArgumentsOnNextLine: true
AllowAllConstructorInitializersOnNextLine: true
AllowAllParametersOfDeclarationOnNextLine: false
AllowShortEnumsOnASingleLine: true
AllowShortBlocksOnASingleLine: Never
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: Empty
AllowShortLambdasOnASingleLine: All
AllowShortIfStatementsOnASingleLine: Never
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: true
AlwaysBreakTemplateDeclarations: Yes
BinPackArguments: false
BinPackParameters: false
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Attach
BreakInheritanceList: BeforeColon
BreakBeforeTernaryOperators: true
BreakConstructorInitializers: BeforeColon
BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: false
ColumnLimit: 80
CommentPragmas: '^ IWYU pragma:'
CompactNamespaces: false
ConstructorInitializerAllOnOneLineOrOnePerLine: true
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DeriveLineEnding: true
DerivePointerAlignment: false
DisableFormat: false
FixNamespaceComments: true
ForEachMacros:
- FOR_EACH
- FOR_EACH_R
- FOR_EACH_RANGE
IncludeBlocks: Preserve
IncludeCategories:
- Regex: '^<.*\.h(pp)?>'
Priority: 1
- Regex: '^<.*'
Priority: 2
- Regex: '.*'
Priority: 3
IndentCaseLabels: true
IndentCaseBlocks: false
IndentGotoLabels: true
IndentPPDirectives: None
IndentExternBlock: AfterExternBlock
IndentWidth: 2
IndentWrappedFunctionNames: false
InsertTrailingCommas: None
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: false
MacroBlockBegin: ''
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
ObjCBinPackProtocolList: Auto
ObjCBlockIndentWidth: 2
ObjCBreakBeforeNestedBlockParam: true
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: false
PenaltyBreakAssignment: 2
PenaltyBreakBeforeFirstCallParameter: 1
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakString: 1000
PenaltyBreakTemplateDeclaration: 10
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 200
PointerAlignment: Left
ReflowComments: true
SortIncludes: true
SortUsingDeclarations: true
SpaceAfterCStyleCast: false
SpaceAfterLogicalNot: false
SpaceAfterTemplateKeyword: true
SpaceBeforeAssignmentOperators: true
SpaceBeforeCpp11BracedList: false
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true
SpaceBeforeParens: ControlStatements
SpaceBeforeRangeBasedForLoopColon: true
SpaceInEmptyBlock: false
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 1
SpacesInAngles: false
SpacesInConditionalStatement: false
SpacesInContainerLiterals: true
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
SpaceBeforeSquareBrackets: false
Standard: Latest
TabWidth: 8
UseCRLF: false
UseTab: Never
... |
|
TOML | hhvm/hphp/hack/src/hackc/Cargo.toml | # @generated by autocargo
[package]
name = "hackc"
version = "0.0.0"
edition = "2021"
[[bin]]
name = "hackc"
path = "cli/hackc.rs"
[dependencies]
aast_parser = { version = "0.0.0", path = "../parser/cargo/aast_parser" }
anyhow = "1.0.71"
assemble = { version = "0.0.0", path = "cargo/assemble" }
bc_to_ir = { version = "0.0.0", path = "ir/conversions/bc_to_ir" }
bumpalo = { version = "3.11.1", features = ["collections"] }
byte-unit = "4.0.14"
bytecode_printer = { version = "0.0.0", path = "bytecode_printer" }
clap = { version = "4.3.5", features = ["derive", "env", "string", "unicode", "wrap_help"] }
compile = { version = "0.0.0", path = "compile/cargo/compile" }
decl_parser = { version = "0.0.0", path = "../hackrs/decl_parser/cargo/decl_parser" }
decl_provider = { version = "0.0.0", path = "decl_provider" }
direct_decl_parser = { version = "0.0.0", path = "../parser/api/cargo/direct_decl_parser" }
elab = { version = "0.0.0", path = "../elab" }
env_logger = "0.10"
facts = { version = "0.0.0", path = "facts/cargo/facts_rust" }
ffi = { version = "0.0.0", path = "../utils/ffi" }
file_provider = { version = "0.0.0", path = "../hackrs/file_provider/cargo/file_provider" }
hackrs_test_utils = { version = "0.0.0", path = "../hackrs/hackrs_test_utils/cargo/hackrs_test_utils" }
hash = { version = "0.0.0", path = "../utils/hash" }
hdrhistogram = "6.3"
hhbc = { version = "0.0.0", path = "hhbc/cargo/hhbc" }
hhi = { version = "0.0.0", path = "../hhi/rust" }
hhvm_config = { version = "0.0.0", path = "hhvm_config/cargo/options" }
hhvm_options = { version = "0.0.0", path = "../utils/hhvm_options" }
hhvm_types_ffi = { version = "0.0.0", path = "hhvm_cxx/hhvm_types" }
ir = { version = "0.0.0", path = "ir" }
ir_to_bc = { version = "0.0.0", path = "ir/conversions/ir_to_bc" }
itertools = "0.10.3"
jwalk = "0.6"
log = { version = "0.4.17", features = ["kv_unstable", "kv_unstable_std"] }
multifile_rust = { version = "0.0.0", path = "../utils/multifile" }
naming_provider = { version = "0.0.0", path = "../hackrs/naming_provider/cargo/naming_provider" }
naming_special_names_rust = { version = "0.0.0", path = "../naming" }
once_cell = "1.12"
options = { version = "0.0.0", path = "compile/cargo/options" }
oxidized = { version = "0.0.0", path = "../oxidized" }
panic-message = "0.3"
parking_lot = { version = "0.12.1", features = ["send_guard"] }
parser_core_types = { version = "0.0.0", path = "../parser/cargo/core_types" }
pos = { version = "0.0.0", path = "../hackrs/pos/cargo/pos" }
positioned_by_ref_parser = { version = "0.0.0", path = "../parser/api/cargo/positioned_by_ref_parser" }
positioned_full_trivia_parser = { version = "0.0.0", path = "../parser/api/cargo/positioned_full_trivia_parser" }
positioned_parser = { version = "0.0.0", path = "../parser/api/cargo/positioned_parser" }
profile_rust = { version = "0.0.0", path = "../utils/perf/cargo/profile" }
rayon = "1.2"
regex = "1.9.2"
relative_path = { version = "0.0.0", path = "../utils/rust/relative_path" }
sem_diff = { version = "0.0.0", path = "sem_diff" }
serde_json = { version = "1.0.100", features = ["float_roundtrip", "unbounded_depth"] }
shallow_decl_provider = { version = "0.0.0", path = "../hackrs/shallow_decl_provider/cargo/shallow_decl_provider" }
strum = { version = "0.24", features = ["derive"] }
tempdir = "0.3"
textual = { version = "0.0.0", path = "ir/conversions/textual/cargo/textual" }
thiserror = "1.0.43"
tracing = { features = ["log"] }
ty = { version = "0.0.0", path = "../hackrs/ty/cargo/ty" } |
Rust | hhvm/hphp/hack/src/hackc/assemble/assemble.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::ffi::OsStr;
use std::fs;
use std::os::unix::ffi::OsStrExt;
use std::path::Path;
use std::path::PathBuf;
use anyhow::anyhow;
use anyhow::bail;
use anyhow::ensure;
use anyhow::Context;
use anyhow::Result;
use bumpalo::Bump;
use ffi::Maybe;
use ffi::Slice;
use ffi::Str;
use hash::HashMap;
use hhvm_types_ffi::Attr;
use log::trace;
use naming_special_names_rust::coeffects::Ctx;
use parse_macro::parse;
use crate::assemble_imm::AssembleImm;
use crate::lexer::Lexer;
use crate::token::Line;
use crate::token::Token;
pub(crate) type DeclMap<'a> = HashMap<Str<'a>, u32>;
/// Assembles the hhas within f to a hhbc::Unit
pub fn assemble<'arena>(alloc: &'arena Bump, f: &Path) -> Result<(hhbc::Unit<'arena>, PathBuf)> {
let s: Vec<u8> = fs::read(f)?;
assemble_from_bytes(alloc, &s)
}
/// Assembles the hhas represented by the slice of bytes input
pub fn assemble_from_bytes<'arena>(
alloc: &'arena Bump,
s: &[u8],
) -> Result<(hhbc::Unit<'arena>, PathBuf)> {
let mut lex = Lexer::from_slice(s, Line(1));
let unit = assemble_from_toks(alloc, &mut lex)?;
trace!("ASM UNIT: {unit:?}");
Ok(unit)
}
/// Assembles a single bytecode. This is useful for dynamic analysis,
/// where we want to assemble each bytecode as it is being executed.
pub fn assemble_single_instruction<'arena>(
alloc: &'arena Bump,
decl_map: &mut DeclMap<'arena>,
s: &[u8],
) -> Result<hhbc::Instruct<'arena>> {
let mut lex = Lexer::from_slice(s, Line(1));
let mut tcb_count = 0;
assemble_instr(alloc, &mut lex, decl_map, &mut tcb_count)
}
/// Assembles the HCU. Parses over the top level of the .hhas file
/// File is either empty OR looks like:
/// .filepath <str_literal>
/// (.function <...>)+
/// (.function_refs <...>)+
fn assemble_from_toks<'arena>(
alloc: &'arena Bump,
token_iter: &mut Lexer<'_>,
) -> Result<(hhbc::Unit<'arena>, PathBuf)> {
// First token should be the filepath
let fp = assemble_filepath(token_iter)?;
let mut unit = UnitBuilder::default();
while !token_iter.is_empty() {
unit.assemble_decl(alloc, token_iter)?;
}
Ok((unit.into_unit(alloc), fp))
}
#[derive(Default)]
struct UnitBuilder<'a> {
adatas: Vec<hhbc::Adata<'a>>,
class_refs: Option<Slice<'a, hhbc::ClassName<'a>>>,
classes: Vec<hhbc::Class<'a>>,
constant_refs: Option<Slice<'a, hhbc::ConstName<'a>>>,
constants: Vec<hhbc::Constant<'a>>,
fatal: Option<hhbc::Fatal<'a>>,
file_attributes: Vec<hhbc::Attribute<'a>>,
func_refs: Option<Slice<'a, hhbc::FunctionName<'a>>>,
funcs: Vec<hhbc::Function<'a>>,
include_refs: Option<Slice<'a, hhbc::IncludePath<'a>>>,
module_use: Option<Str<'a>>,
modules: Vec<hhbc::Module<'a>>,
type_constants: Vec<hhbc::TypeConstant<'a>>,
typedefs: Vec<hhbc::Typedef<'a>>,
}
impl<'a> UnitBuilder<'a> {
fn into_unit(self, alloc: &'a Bump) -> hhbc::Unit<'a> {
hhbc::Unit {
adata: Slice::fill_iter(alloc, self.adatas.into_iter()),
functions: Slice::fill_iter(alloc, self.funcs.into_iter()),
classes: Slice::fill_iter(alloc, self.classes.into_iter()),
typedefs: Slice::fill_iter(alloc, self.typedefs.into_iter()),
file_attributes: Slice::fill_iter(alloc, self.file_attributes.into_iter()),
modules: Slice::from_vec(alloc, self.modules),
module_use: self.module_use.into(),
symbol_refs: hhbc::SymbolRefs {
functions: self.func_refs.unwrap_or_default(),
classes: self.class_refs.unwrap_or_default(),
constants: self.constant_refs.unwrap_or_default(),
includes: self.include_refs.unwrap_or_default(),
},
constants: Slice::fill_iter(alloc, self.constants.into_iter()),
fatal: self.fatal.into(),
missing_symbols: Default::default(),
error_symbols: Default::default(),
}
}
fn assemble_decl(&mut self, alloc: &'a Bump, token_iter: &mut Lexer<'_>) -> Result<()> {
let tok = token_iter.peek().unwrap();
if !tok.is_decl() {
return Err(tok.error("Declaration expected"))?;
}
match tok.as_bytes() {
b".fatal" => {
self.fatal = Some(assemble_fatal(alloc, token_iter)?);
}
b".adata" => {
self.adatas.push(assemble_adata(alloc, token_iter)?);
}
b".function" => {
self.funcs.push(assemble_function(alloc, token_iter)?);
}
b".class" => {
self.classes.push(assemble_class(alloc, token_iter)?);
}
b".function_refs" => {
ensure_single_defn(&self.func_refs, tok)?;
self.func_refs = Some(assemble_refs(
alloc,
token_iter,
".function_refs",
assemble_function_name,
)?);
}
b".class_refs" => {
ensure_single_defn(&self.class_refs, tok)?;
self.class_refs = Some(assemble_refs(
alloc,
token_iter,
".class_refs",
assemble_class_name,
)?);
}
b".constant_refs" => {
ensure_single_defn(&self.constant_refs, tok)?;
self.constant_refs = Some(assemble_refs(
alloc,
token_iter,
".constant_refs",
assemble_const_name,
)?);
}
b".includes" => {
ensure_single_defn(&self.include_refs, tok)?;
self.include_refs = Some(assemble_refs(
alloc,
token_iter,
".includes",
|t, alloc| {
let path_str = if t.peek_is(Token::is_decl) {
t.expect(Token::is_decl)?.into_ffi_str(alloc)
} else {
t.expect(Token::is_identifier)?.into_ffi_str(alloc)
};
Ok(hhbc::IncludePath::Absolute(path_str))
},
)?)
}
b".alias" => {
self.typedefs
.push(assemble_typedef(alloc, token_iter, false)?);
}
b".case_type" => {
self.typedefs
.push(assemble_typedef(alloc, token_iter, true)?);
}
b".const" => {
assemble_const_or_type_const(
alloc,
token_iter,
&mut self.constants,
&mut self.type_constants,
)?;
ensure!(
self.type_constants.is_empty(),
"Type constants defined outside of a class"
);
}
b".file_attributes" => {
assemble_file_attributes(alloc, token_iter, &mut self.file_attributes)?;
}
b".module_use" => {
self.module_use = Some(assemble_module_use(alloc, token_iter)?);
}
b".module" => {
self.modules.push(assemble_module(alloc, token_iter)?);
}
_ => {
return Err(tok.error("Unknown top level declarationr"))?;
}
}
Ok(())
}
}
fn ensure_single_defn<T>(v: &Option<T>, tok: &Token<'_>) -> Result<()> {
if v.is_none() {
Ok(())
} else {
let what = std::str::from_utf8(tok.as_bytes()).unwrap();
Err(tok.error(format!("'{what} defined multiple times")))
}
}
/// Ex:
/// .module m0 (64, 64) {
/// }
fn assemble_module<'arena>(
alloc: &'arena Bump,
token_iter: &mut Lexer<'_>,
) -> Result<hhbc::Module<'arena>> {
parse!(token_iter,
".module"
<attr:assemble_special_and_user_attrs(alloc)>
<name:assemble_class_name(alloc)>
<span:assemble_span>
"{"
<doc_comment:assemble_doc_comment(alloc)>
"}");
let (attr, attributes) = attr;
ensure!(
attr == hhvm_types_ffi::ffi::Attr::AttrNone,
"Unexpected HHVM attrs in module definition"
);
Ok(hhbc::Module {
attributes,
name,
span,
doc_comment,
exports: Maybe::Nothing, // TODO: Add parsing
imports: Maybe::Nothing, // TODO: Add parsing
})
}
/// Ex:
/// .module_use "(module_use)";
fn assemble_module_use<'arena>(
alloc: &'arena Bump,
token_iter: &mut Lexer<'_>,
) -> Result<Str<'arena>> {
parse!(token_iter, ".module_use" <name:string> ";");
let name = Str::new_slice(alloc, escaper::unquote_slice(name.as_bytes()));
Ok(name)
}
/// Ex:
/// .file_attributes ["__EnableUnstableFeatures"("""v:1:{s:8:\"readonly\";}""")] ;
fn assemble_file_attributes<'arena>(
alloc: &'arena Bump,
token_iter: &mut Lexer<'_>,
file_attributes: &mut Vec<hhbc::Attribute<'arena>>,
) -> Result<()> {
parse!(token_iter, ".file_attributes" "[" <attrs:assemble_user_attr(alloc),*> "]" ";");
file_attributes.extend(attrs);
Ok(())
}
/// Ex:
/// .alias ShapeKeyEscaping = <"HH\\darray"> (3,6) """D:2:{s:4:\"kind\";i:14;s:6:\"fields\";D:2:{s:11:\"Whomst'd've\";D:1:{s:5:\"value\";D:1:{s:4:\"kind\";i:1;}}s:25:\"Whomst\\u{0027}d\\u{0027}ve\";D:1:{s:5:\"value\";D:1:{s:4:\"kind\";i:4;}}}}""";
/// Note that in BCP, TypeDef's typeinfo's user_type is not printed. What's between <> is the typeinfo's constraint's name.
fn assemble_typedef<'arena>(
alloc: &'arena Bump,
token_iter: &mut Lexer<'_>,
case_type: bool,
) -> Result<hhbc::Typedef<'arena>> {
if case_type {
parse!(token_iter, ".case_type");
} else {
parse!(token_iter, ".alias");
}
parse!(token_iter,
<attrs:assemble_special_and_user_attrs(alloc)>
<name:assemble_class_name(alloc)>
"="
<type_info_union:assemble_type_info_union(alloc)>
<span:assemble_span>
<type_structure:assemble_triple_quoted_typed_value(alloc)>
";");
let (attrs, attributes) = attrs;
Ok(hhbc::Typedef {
name,
attributes,
type_info_union,
type_structure,
span,
attrs,
case_type,
})
}
fn assemble_class<'arena>(
alloc: &'arena Bump,
token_iter: &mut Lexer<'_>,
) -> Result<hhbc::Class<'arena>> {
parse!(token_iter, ".class"
<upper_bounds:assemble_upper_bounds(alloc)>
<attr:assemble_special_and_user_attrs(alloc)>
<name:assemble_class_name(alloc)>
<span:assemble_span>
<base:assemble_base(alloc)>
<implements:assemble_imp_or_enum_includes(alloc, "implements")>
<enum_includes:assemble_imp_or_enum_includes(alloc, "enum_includes")>
"{"
<doc_comment:assemble_doc_comment(alloc)>
<uses:assemble_uses(alloc)>
<enum_type:assemble_enum_ty(alloc)>
);
let (flags, attributes) = attr;
let mut requirements = Vec::new();
let mut ctx_constants = Vec::new();
let mut properties = Vec::new();
let mut methods = Vec::new();
let mut constants = Vec::new();
let mut type_constants = Vec::new();
while let Some(tok @ Token::Decl(txt, _)) = token_iter.peek() {
match *txt {
b".require" => requirements.push(assemble_requirement(alloc, token_iter)?),
b".ctx" => ctx_constants.push(assemble_ctx_constant(alloc, token_iter)?),
b".property" => properties.push(assemble_property(alloc, token_iter)?),
b".method" => methods.push(assemble_method(alloc, token_iter)?),
b".const" => assemble_const_or_type_const(
alloc,
token_iter,
&mut constants,
&mut type_constants,
)?,
_ => Err(tok.error("Unknown class-level identifier"))?,
}
}
parse!(token_iter, "}");
let hhas_class = hhbc::Class {
attributes,
base,
implements,
enum_includes,
name,
span,
uses,
enum_type,
methods: Slice::from_vec(alloc, methods),
properties: Slice::from_vec(alloc, properties),
constants: Slice::from_vec(alloc, constants),
type_constants: Slice::from_vec(alloc, type_constants),
ctx_constants: Slice::from_vec(alloc, ctx_constants),
requirements: Slice::from_vec(alloc, requirements),
upper_bounds,
doc_comment,
flags,
};
Ok(hhas_class)
}
/// Defined in 'hack/src/naming/naming_special_names.rs`
fn is_enforced_static_coeffect(d: &Slice<'_, u8>) -> bool {
match d.as_ref() {
b"pure" | b"defaults" | b"rx" | b"zoned" | b"write_props" | b"rx_local" | b"zoned_with"
| b"zoned_local" | b"zoned_shallow" | b"leak_safe_local" | b"leak_safe_shallow"
| b"leak_safe" | b"read_globals" | b"globals" | b"write_this_props" | b"rx_shallow" => true,
_ => false,
}
}
/// Ex:
/// .ctx C isAbstract;
/// .ctx Clazy pure;
/// .ctx Cdebug isAbstract;
fn assemble_ctx_constant<'arena>(
alloc: &'arena Bump,
token_iter: &mut Lexer<'_>,
) -> Result<hhbc::CtxConstant<'arena>> {
parse!(token_iter, ".ctx" <name:id> <is_abstract:"isAbstract"?> <tokens:id*> ";");
let name = name.into_ffi_str(alloc);
// .ctx has slice of recognized and unrecognized constants.
// Making an assumption that recognized ~~ static coeffects and
// unrecognized ~~ unenforced static coeffects
let (r, u) = tokens
.into_iter()
.map(|tok| tok.into_ffi_str(alloc))
.partition(is_enforced_static_coeffect);
Ok(hhbc::CtxConstant {
name,
recognized: Slice::from_vec(alloc, r),
unrecognized: Slice::from_vec(alloc, u),
is_abstract,
})
}
/// Ex:
/// .require extends <C>;
fn assemble_requirement<'arena>(
alloc: &'arena Bump,
token_iter: &mut Lexer<'_>,
) -> Result<hhbc::Requirement<'arena>> {
parse!(token_iter, ".require" <tok:id> "<" <name:assemble_class_name(alloc)> ">" ";");
let kind = match tok.into_identifier()? {
b"extends" => hhbc::TraitReqKind::MustExtend,
b"implements" => hhbc::TraitReqKind::MustImplement,
b"class" => hhbc::TraitReqKind::MustBeClass,
_ => return Err(tok.error("Expected TraitReqKind")),
};
Ok(hhbc::Requirement { name, kind })
}
fn assemble_const_or_type_const<'arena>(
alloc: &'arena Bump,
token_iter: &mut Lexer<'_>,
consts: &mut Vec<hhbc::Constant<'arena>>,
type_consts: &mut Vec<hhbc::TypeConstant<'arena>>,
) -> Result<()> {
token_iter.expect_str(Token::is_decl, ".const")?;
let mut attrs = Attr::AttrNone;
if token_iter.peek_is(Token::is_open_bracket) {
attrs = assemble_special_and_user_attrs(token_iter, alloc)?.0;
}
let name = token_iter.expect(Token::is_identifier)?.into_ffi_str(alloc);
if token_iter.next_is_str(Token::is_identifier, "isType") {
//type const
let is_abstract = token_iter.next_is_str(Token::is_identifier, "isAbstract");
let initializer = if token_iter.next_is(Token::is_equal) {
Maybe::Just(assemble_triple_quoted_typed_value(token_iter, alloc)?)
} else {
Maybe::Nothing
};
type_consts.push(hhbc::TypeConstant {
name,
initializer,
is_abstract,
});
} else {
//const
let name = hhbc::ConstName::new(name);
let value = if token_iter.next_is(Token::is_equal) {
if token_iter.next_is_str(Token::is_identifier, "uninit") {
Maybe::Just(hhbc::TypedValue::Uninit)
} else {
Maybe::Just(assemble_triple_quoted_typed_value(token_iter, alloc)?)
}
} else {
Maybe::Nothing
};
consts.push(hhbc::Constant { name, value, attrs });
}
token_iter.expect(Token::is_semicolon)?;
Ok(())
}
/// Ex:
/// .method {}{} [public abstract] (15,15) <"" N > a(<"?HH\\varray" "HH\\varray" nullable extended_hint display_nullable> $a1 = DV1("""NULL"""), <"HH\\varray" "HH\\varray" > $a2 = DV2("""varray[]""")) {
/// ...
/// }
fn assemble_method<'arena>(
alloc: &'arena Bump,
token_iter: &mut Lexer<'_>,
) -> Result<hhbc::Method<'arena>> {
let method_tok = token_iter.peek().copied();
token_iter.expect_str(Token::is_decl, ".method")?;
let shadowed_tparams = assemble_shadowed_tparams(alloc, token_iter)?;
let upper_bounds = assemble_upper_bounds(token_iter, alloc)?;
let (attrs, attributes) = assemble_special_and_user_attrs(token_iter, alloc)?;
let span = assemble_span(token_iter)?;
let return_type_info =
assemble_type_info_opt(token_iter, alloc, TypeInfoKind::NotEnumOrTypeDef)?;
let name = assemble_method_name(alloc, token_iter)?;
let mut decl_map = HashMap::default();
let params = assemble_params(alloc, token_iter, &mut decl_map)?;
let flags = assemble_method_flags(token_iter)?;
let (body, coeffects) = assemble_body(
alloc,
token_iter,
&mut decl_map,
params,
return_type_info,
shadowed_tparams,
upper_bounds,
)?;
// the visibility is printed in the attrs
// confusion: Visibility::Internal is a mix of AttrInternal and AttrPublic?
let visibility =
determine_visibility(&attrs).map_err(|e| method_tok.unwrap().error(e.to_string()))?;
let met = hhbc::Method {
attributes,
visibility,
name,
body,
span,
coeffects,
flags,
attrs,
};
Ok(met)
}
fn assemble_shadowed_tparams<'arena>(
alloc: &'arena Bump,
token_iter: &mut Lexer<'_>,
) -> Result<Slice<'arena, Str<'arena>>> {
token_iter.expect(Token::is_open_curly)?;
let mut stp = Vec::new();
while token_iter.peek_is(Token::is_identifier) {
stp.push(token_iter.expect(Token::is_identifier)?.into_ffi_str(alloc));
if !token_iter.peek_is(Token::is_close_curly) {
token_iter.expect(Token::is_comma)?;
}
}
token_iter.expect(Token::is_close_curly)?;
Ok(Slice::from_vec(alloc, stp))
}
fn assemble_method_flags(token_iter: &mut Lexer<'_>) -> Result<hhbc::MethodFlags> {
let mut flag = hhbc::MethodFlags::empty();
while token_iter.peek_is(Token::is_identifier) {
let tok = token_iter.expect_token()?;
match tok.into_identifier()? {
b"isPairGenerator" => flag |= hhbc::MethodFlags::IS_PAIR_GENERATOR,
b"isAsync" => flag |= hhbc::MethodFlags::IS_ASYNC,
b"isGenerator" => flag |= hhbc::MethodFlags::IS_GENERATOR,
b"isClosureBody" => flag |= hhbc::MethodFlags::IS_CLOSURE_BODY,
_ => return Err(tok.error("Unknown function flag")),
}
}
Ok(flag)
}
fn assemble_property<'arena>(
alloc: &'arena Bump,
token_iter: &mut Lexer<'_>,
) -> Result<hhbc::Property<'arena>> {
let prop_tok = token_iter.peek().copied();
// A doc comment is just a triple string literal : """{}"""
let mut doc_comment = Maybe::Nothing;
parse!(token_iter,
".property"
<attrs:assemble_special_and_user_attrs(alloc)>
[triple_string: <dc:assemble_unescaped_unquoted_triple_str(alloc)> { doc_comment = Maybe::Just(dc); } ;
else: { } ;
]
<type_info:assemble_type_info(alloc, TypeInfoKind::NotEnumOrTypeDef)>
<name:assemble_prop_name(alloc)>
"="
<initial_value:assemble_property_initial_value(alloc)>
";"
);
let (flags, attributes) = attrs;
let visibility =
determine_visibility(&flags).map_err(|e| prop_tok.unwrap().error(e.to_string()))?;
Ok(hhbc::Property {
name,
flags,
attributes,
visibility,
initial_value,
type_info,
doc_comment,
})
}
fn determine_visibility(attr: &hhvm_types_ffi::ffi::Attr) -> Result<hhbc::Visibility> {
let v = if attr.is_internal() && attr.is_public() {
hhbc::Visibility::Internal
} else if attr.is_public() {
hhbc::Visibility::Public
} else if attr.is_private() {
hhbc::Visibility::Private
} else if attr.is_protected() {
hhbc::Visibility::Protected
} else {
bail!("No visibility specified")
};
Ok(v)
}
/// Initial values are printed slightly differently from typed values:
/// while a TV prints uninit as "uninit", initial value is printed as "uninit;""
/// for all other typed values, initial_value is printed nested in triple quotes.
fn assemble_property_initial_value<'arena>(
token_iter: &mut Lexer<'_>,
alloc: &'arena Bump,
) -> Result<Maybe<hhbc::TypedValue<'arena>>> {
Ok(parse!(token_iter,
[
"uninit": "uninit" { Maybe::Just(hhbc::TypedValue::Uninit) } ;
"\"\"\"N;\"\"\"": "\"\"\"N;\"\"\"" { Maybe::Nothing } ;
else: <v:assemble_triple_quoted_typed_value(alloc)> { Maybe::Just(v) } ;
]))
}
fn assemble_class_name<'arena>(
token_iter: &mut Lexer<'_>,
alloc: &'arena Bump,
) -> Result<hhbc::ClassName<'arena>> {
parse!(token_iter, <id:id>);
Ok(hhbc::ClassName::new(id.into_ffi_str(alloc)))
}
pub(crate) fn assemble_prop_name_from_str<'arena>(
alloc: &'arena Bump,
token_iter: &mut Lexer<'_>,
) -> Result<hhbc::PropName<'arena>> {
Ok(hhbc::PropName::new(assemble_unescaped_unquoted_str(
alloc, token_iter,
)?))
}
fn assemble_prop_name<'arena>(
token_iter: &mut Lexer<'_>,
alloc: &'arena Bump,
) -> Result<hhbc::PropName<'arena>> {
// Only properties that can start with #s start with 0 or
// 86 and are compiler added ones
let nm = if token_iter.peek_is_str(Token::is_number, "86")
|| token_iter.peek_is_str(Token::is_number, "0")
{
let num_prefix = token_iter.expect_with(Token::into_number)?;
let name = token_iter.expect_with(Token::into_identifier)?;
let mut num_prefix = num_prefix.to_vec();
num_prefix.extend_from_slice(name);
Str::new_slice(alloc, &num_prefix)
} else {
token_iter.expect(Token::is_identifier)?.into_ffi_str(alloc)
};
Ok(hhbc::PropName::new(nm))
}
fn assemble_method_name<'arena>(
alloc: &'arena Bump,
token_iter: &mut Lexer<'_>,
) -> Result<hhbc::MethodName<'arena>> {
let nm = if token_iter.peek_is_str(Token::is_number, "86") {
// Only methods that can start with #s start with
// 86 and are compiler added ones
let under86 = token_iter.expect_with(Token::into_number)?;
let name = token_iter.expect_with(Token::into_identifier)?;
let mut under86 = under86.to_vec();
under86.extend_from_slice(name);
Str::new_slice(alloc, &under86)
} else {
token_iter.expect(Token::is_identifier)?.into_ffi_str(alloc)
};
Ok(hhbc::MethodName::new(nm))
}
fn assemble_const_name<'arena>(
token_iter: &mut Lexer<'_>,
alloc: &'arena Bump,
) -> Result<hhbc::ConstName<'arena>> {
parse!(token_iter, <id:id>);
Ok(hhbc::ConstName::new(id.into_ffi_str(alloc)))
}
fn assemble_function_name<'arena>(
token_iter: &mut Lexer<'_>,
alloc: &'arena Bump,
) -> Result<hhbc::FunctionName<'arena>> {
let nm = if token_iter.peek_is_str(Token::is_number, "86") {
// Only functions that can start with #s start with
// 86 and are compiler added ones
let under86 = token_iter.expect_with(Token::into_number)?;
let name = token_iter.expect_with(Token::into_identifier)?;
let mut under86 = under86.to_vec();
under86.extend_from_slice(name);
Str::new_slice(alloc, &under86)
} else {
token_iter.expect(Token::is_identifier)?.into_ffi_str(alloc)
};
Ok(hhbc::FunctionName::new(nm))
}
/// Ex:
/// extends C
/// There is only one base per Class
fn assemble_base<'arena>(
token_iter: &mut Lexer<'_>,
alloc: &'arena Bump,
) -> Result<Maybe<hhbc::ClassName<'arena>>> {
Ok(parse!(token_iter, [
"extends": "extends" <cn:assemble_class_name(alloc)> { Maybe::Just(cn) } ;
else: { Maybe::Nothing } ;
]))
}
/// Ex:
/// implements (Fooable Barable)
/// enum_includes (Fooable Barable)
fn assemble_imp_or_enum_includes<'arena>(
token_iter: &mut Lexer<'_>,
alloc: &'arena Bump,
imp_or_inc: &str,
) -> Result<Slice<'arena, hhbc::ClassName<'arena>>> {
let mut classes = Vec::new();
if token_iter.next_is_str(Token::is_identifier, imp_or_inc) {
token_iter.expect(Token::is_open_paren)?;
while !token_iter.peek_is(Token::is_close_paren) {
classes.push(assemble_class_name(token_iter, alloc)?);
}
token_iter.expect(Token::is_close_paren)?;
}
Ok(Slice::from_vec(alloc, classes))
}
/// Ex: .doc """doc""";
fn assemble_doc_comment<'arena>(
token_iter: &mut Lexer<'_>,
alloc: &'arena Bump,
) -> Result<Maybe<Str<'arena>>> {
Ok(parse!(token_iter, [
".doc": ".doc" <com:assemble_unescaped_unquoted_triple_str(alloc)> ";" { Maybe::Just(com) } ;
else: { Maybe::Nothing } ;
]))
}
/// Ex: .use TNonScalar;
fn assemble_uses<'arena>(
token_iter: &mut Lexer<'_>,
alloc: &'arena Bump,
) -> Result<Slice<'arena, hhbc::ClassName<'arena>>> {
let classes = parse!(token_iter, [
".use": ".use" <classes:assemble_class_name(alloc)*> ";" { classes } ;
else: { Vec::new() } ;
]);
Ok(Slice::from_vec(alloc, classes))
}
/// Ex: .enum_ty <type_info>
fn assemble_enum_ty<'arena>(
token_iter: &mut Lexer<'_>,
alloc: &'arena Bump,
) -> Result<Maybe<hhbc::TypeInfo<'arena>>> {
parse!(token_iter, [
".enum_ty": ".enum_ty" <ti:assemble_type_info_opt(alloc, TypeInfoKind::Enum)> ";" { Ok(ti) } ;
else: { Ok(Maybe::Nothing) } ;
])
}
/// Ex: .fatal 2:63,2:63 Parse "A right parenthesis `)` is expected here.";
fn assemble_fatal<'arena>(
alloc: &'arena Bump,
token_iter: &mut Lexer<'_>,
) -> Result<hhbc::Fatal<'arena>> {
parse!(token_iter, ".fatal"
<line_begin:numeric> ":" <col_begin:numeric> ","
<line_end:numeric> ":" <col_end:numeric>
<op:id>
<msg:token>
";"
);
let loc = hhbc::SrcLoc {
line_begin,
col_begin,
line_end,
col_end,
};
let op = match op.as_bytes() {
b"Parse" => hhbc::FatalOp::Parse,
b"Runtime" => hhbc::FatalOp::Runtime,
b"RuntimeOmitFrame" => hhbc::FatalOp::RuntimeOmitFrame,
_ => return Err(op.error("Unknown fatal op")),
};
let msg = escaper::unescape_literal_bytes_into_vec_bytes(msg.into_unquoted_str_literal()?)?;
let message = Str::new_slice(alloc, &msg);
Ok(hhbc::Fatal { op, loc, message })
}
/// A line of adata looks like:
/// .adata id = """<tv>"""
/// with tv being a typed value; see `assemble_typed_value` doc for what <tv> looks like.
fn assemble_adata<'arena>(
alloc: &'arena Bump,
token_iter: &mut Lexer<'_>,
) -> Result<hhbc::Adata<'arena>> {
parse!(token_iter, ".adata" <id:id> "=" <value:assemble_triple_quoted_typed_value(alloc)> ";");
let id = hhbc::AdataId::new(id.into_ffi_str(alloc));
Ok(hhbc::Adata { id, value })
}
/// For use by initial value
fn assemble_triple_quoted_typed_value<'arena>(
token_iter: &mut Lexer<'_>,
alloc: &'arena Bump,
) -> Result<hhbc::TypedValue<'arena>> {
let (st, line) = token_iter.expect_with(Token::into_triple_str_literal_and_line)?;
// Guaranteed st is encased by """ """
let st = &st[3..st.len() - 3];
let st = escaper::unescape_literal_bytes_into_vec_bytes(st)?;
assemble_typed_value(alloc, &st, line)
}
/// tv can look like:
/// uninit | N; | s:s.len():"(escaped s)"; | l:s.len():"(escaped s)"; | d:#; | i:#; | b:0; | b:1; | D:dict.len():{((tv1);(tv2);)*}
/// | v:vec.len():{(tv;)*} | k:keyset.len():{(tv;)*}
fn assemble_typed_value<'arena>(
alloc: &'arena Bump,
src: &[u8],
line: Line,
) -> Result<hhbc::TypedValue<'arena>> {
fn deserialize<'arena, 'a>(
alloc: &'arena Bump,
src: &'a [u8],
line: Line,
) -> Result<hhbc::TypedValue<'arena>> {
/// Returns s after ch if ch is the first character in s, else bails.
fn expect<'a>(s: &'a [u8], ch: &'_ [u8]) -> Result<&'a [u8]> {
s.strip_prefix(ch)
.ok_or_else(|| anyhow!("Expected {:?} in src {:?}", ch, s))
}
/// Returns the usize (if exists) at the head of the string and the remainder of the string.
fn expect_usize(src: &[u8]) -> Result<(usize, &[u8])> {
let (us, rest) = read_while_matches(src, |c| c.is_ascii_digit());
Ok((std::str::from_utf8(us)?.parse()?, rest))
}
/// Advances and consumes the start of s until f is no longer true on the
/// first character of s. Returns (characters consumed, rest of src)
fn read_while_matches(s: &[u8], f: impl Fn(u8) -> bool) -> (&[u8], &[u8]) {
let stake = s.iter().position(|c| !f(*c)).unwrap_or(s.len());
s.split_at(stake)
}
/// A read_while_matches that also expects c at the end.
/// Note that s != first_return + second_return.
/// s = first_return + c + second_return
fn read_until<'a>(
s: &'a [u8],
f: impl Fn(u8) -> bool,
c: &'_ [u8],
) -> Result<(&'a [u8], &'a [u8])> {
let (fst, snd) = read_while_matches(s, f);
Ok((fst, expect(snd, c)?))
}
/// i:#;
fn deserialize_int<'arena>(src: &[u8]) -> Result<(&[u8], hhbc::TypedValue<'arena>)> {
let src = expect(src, b"i")?;
let src = expect(src, b":")?;
let (num, src) =
read_until(src, |c| c.is_ascii_digit() || c == b'-' || c == b'+', b";")?;
ensure!(!num.is_empty(), "No # specified for int TV");
let num = std::str::from_utf8(num)?.parse::<i64>()?;
Ok((src, hhbc::TypedValue::Int(num)))
}
// r"d:[-+]?(NAN|INF|([0-9]+\.?[0-9]*([eE][-+]?[0-9]+\.?[0-9]*)?))"
/// d:#;
fn deserialize_float<'arena>(src: &[u8]) -> Result<(&[u8], hhbc::TypedValue<'arena>)> {
let src = expect(src, b"d")?;
let src = expect(src, b":")?;
let (num, src) = read_until(src, |c| c != b';', b";")?;
let num = std::str::from_utf8(num)?.parse()?;
Ok((src, hhbc::TypedValue::Float(hhbc::FloatBits(num))))
}
/// b:0;
fn deserialize_bool<'arena>(src: &[u8]) -> Result<(&[u8], hhbc::TypedValue<'arena>)> {
let src = expect(src, b"b")?;
let src = expect(src, b":")?;
let val = src[0] == b'1';
let src = expect(&src[1..], b";")?;
Ok((src, hhbc::TypedValue::Bool(val)))
}
/// N;
fn deserialize_null<'arena>(src: &[u8]) -> Result<(&[u8], hhbc::TypedValue<'arena>)> {
let src = expect(src, b"N")?;
let src = expect(src, b";")?;
Ok((src, hhbc::TypedValue::Null))
}
/// uninit
fn deserialize_uninit<'arena>(src: &[u8]) -> Result<(&[u8], hhbc::TypedValue<'arena>)> {
Ok((
src.strip_prefix(b"uninit")
.ok_or_else(|| anyhow!("Expected uninit in src {:?}", src))?,
hhbc::TypedValue::Uninit,
))
}
/// s:s.len():"(escaped s)"; or l:s.len():"(escaped s)";
fn deserialize_string_or_lazyclass<'arena, 'a>(
alloc: &'arena Bump,
src: &'a [u8],
s_or_l: StringOrLazyClass,
) -> Result<(&'a [u8], hhbc::TypedValue<'arena>)> {
let src = expect(src, s_or_l.prefix())?;
let src = expect(src, b":")?;
let (len, src) = expect_usize(src)?;
let src = expect(src, b":")?;
let src = expect(src, b"\"")?;
ensure!(
src.len() >= len,
"Length specified greater than source length: {} vs {}",
len,
src.len()
);
let s = &src[0..len];
let src = &src[len..];
let src = expect(src, b"\"")?;
let src = expect(src, b";")?;
Ok((src, s_or_l.build(Str::new_slice(alloc, s))))
}
#[derive(PartialEq)]
pub enum StringOrLazyClass {
String,
LazyClass,
}
impl StringOrLazyClass {
pub fn prefix(&self) -> &[u8] {
match self {
StringOrLazyClass::String => b"s",
StringOrLazyClass::LazyClass => b"l",
}
}
pub fn build<'arena>(&self, content: Str<'arena>) -> hhbc::TypedValue<'arena> {
match self {
StringOrLazyClass::String => hhbc::TypedValue::String(content),
StringOrLazyClass::LazyClass => hhbc::TypedValue::LazyClass(content),
}
}
}
#[derive(PartialEq)]
pub enum VecOrKeyset {
Vec,
Keyset,
}
impl VecOrKeyset {
pub fn prefix(&self) -> &[u8] {
match self {
VecOrKeyset::Vec => b"v",
VecOrKeyset::Keyset => b"k",
}
}
pub fn build<'arena>(
&self,
content: Slice<'arena, hhbc::TypedValue<'arena>>,
) -> hhbc::TypedValue<'arena> {
match self {
VecOrKeyset::Vec => hhbc::TypedValue::Vec(content),
VecOrKeyset::Keyset => hhbc::TypedValue::Keyset(content),
}
}
}
/// v:vec.len():{(tv;)*} or k:keyset.len():{(tv;)*}
fn deserialize_vec_or_keyset<'arena, 'a>(
alloc: &'arena Bump,
src: &'a [u8],
v_or_k: VecOrKeyset,
) -> Result<(&'a [u8], hhbc::TypedValue<'arena>)> {
let src = expect(src, v_or_k.prefix())?;
let src = expect(src, b":")?;
let (len, src) = expect_usize(src)?;
let src = expect(src, b":")?;
let mut src = expect(src, b"{")?;
let mut tv;
let mut tv_vec = Vec::new();
for _ in 0..len {
(src, tv) = deserialize_tv(alloc, src)?;
tv_vec.push(tv);
}
let src = expect(src, b"}")?;
let slice = Slice::from_vec(alloc, tv_vec);
Ok((src, v_or_k.build(slice)))
}
/// D:(D.len):{p1_0; p1_1; ...; pD.len_0; pD.len_1}
fn deserialize_dict<'arena, 'a>(
alloc: &'arena Bump,
src: &'a [u8],
) -> Result<(&'a [u8], hhbc::TypedValue<'arena>)> {
let src = expect(src, b"D")?;
let src = expect(src, b":")?;
let (len, src) = expect_usize(src)?;
let src = expect(src, b":")?;
let mut src = expect(src, b"{")?;
let mut key;
let mut value;
let mut tv_vec = Vec::new();
for _ in 0..len {
(src, key) = deserialize_tv(alloc, src)?;
(src, value) = deserialize_tv(alloc, src)?;
tv_vec.push(hhbc::DictEntry { key, value })
}
let src = expect(src, b"}")?;
Ok((src, hhbc::TypedValue::Dict(Slice::from_vec(alloc, tv_vec))))
}
fn deserialize_tv<'arena, 'a>(
alloc: &'arena Bump,
src: &'a [u8],
) -> Result<(&'a [u8], hhbc::TypedValue<'arena>)> {
let (src, tr) = match src[0] {
b'i' => deserialize_int(src).context("Assembling a TV int")?,
b'b' => deserialize_bool(src).context("Assembling a TV bool")?,
b'd' => deserialize_float(src).context("Assembling a TV float")?,
b'N' => deserialize_null(src).context("Assembling a TV Null")?,
b'u' => deserialize_uninit(src).context("Assembling a uninit")?,
b's' => deserialize_string_or_lazyclass(alloc, src, StringOrLazyClass::String)
.context("Assembling a TV string")?,
b'v' => deserialize_vec_or_keyset(alloc, src, VecOrKeyset::Vec)
.context("Assembling a TV vec")?,
b'k' => deserialize_vec_or_keyset(alloc, src, VecOrKeyset::Keyset)
.context("Assembling a TV keyset")?,
b'D' => deserialize_dict(alloc, src).context("Assembling a TV dict")?,
b'l' => deserialize_string_or_lazyclass(alloc, src, StringOrLazyClass::LazyClass)
.context("Assembling a LazyClass")?,
_ => bail!("Unknown tv: {}", src[0]),
};
Ok((src, tr))
}
ensure!(!src.is_empty(), "Empty typed value. Line {}", line);
let (src, tv) = deserialize_tv(alloc, src).context(format!("Line {}", line))?;
ensure!(
src.is_empty(),
"Unassemble-able TV. Unassembled: {:?}. Line {}",
src,
line
);
Ok(tv)
}
deserialize(alloc, src, line)
}
/// Class refs look like:
/// .class_refs {
/// (identifier)+
/// }
/// Function ref looks like:
/// .functionrefs {
/// (identifier)+
/// }
///
fn assemble_refs<'arena, 'a, T: 'arena, F>(
alloc: &'arena Bump,
token_iter: &mut Lexer<'_>,
name_str: &str,
assemble_name: F,
) -> Result<Slice<'arena, T>>
where
F: Fn(&mut Lexer<'_>, &'arena Bump) -> Result<T>,
{
token_iter.expect_str(Token::is_decl, name_str)?;
token_iter.expect(Token::is_open_curly)?;
let mut names = Vec::new();
while !token_iter.peek_is(Token::is_close_curly) {
names.push(assemble_name(token_iter, alloc)?);
}
token_iter.expect(Token::is_close_curly)?;
Ok(Slice::from_vec(alloc, names))
}
/// A function def is composed of the following:
/// .function {upper bounds} [special_and_user_attrs] (span) <type_info> name (params) flags? {body}
fn assemble_function<'arena>(
alloc: &'arena Bump,
token_iter: &mut Lexer<'_>,
) -> Result<hhbc::Function<'arena>> {
token_iter.expect_str(Token::is_decl, ".function")?;
let upper_bounds = assemble_upper_bounds(token_iter, alloc)?;
// Special and user attrs may or may not be specified. If not specified, no [] printed
let (attr, attributes) = assemble_special_and_user_attrs(token_iter, alloc)?;
let span = assemble_span(token_iter)?;
// Body may not have return type info, so check if next token is a < or not
// Specifically if body doesn't have a return type info bytecode printer doesn't print anything
// (doesn't print <>)
let return_type_info =
assemble_type_info_opt(token_iter, alloc, TypeInfoKind::NotEnumOrTypeDef)?;
// Assemble_name
let name = assemble_function_name(token_iter, alloc)?;
// Will store decls in this order: params, decl_vars, unnamed
let mut decl_map = HashMap::default();
let params = assemble_params(alloc, token_iter, &mut decl_map)?;
let flags = assemble_function_flags(name, token_iter)?;
let shadowed_tparams = Default::default();
let (body, coeffects) = assemble_body(
alloc,
token_iter,
&mut decl_map,
params,
return_type_info,
shadowed_tparams,
upper_bounds,
)?;
let hhas_func = hhbc::Function {
attributes,
name,
body,
span,
coeffects,
flags,
attrs: attr,
};
Ok(hhas_func)
}
/// Have to parse flags which may or may not appear: isGenerator isAsync isPairGenerator
/// Also, MEMOIZE_IMPL appears in the function name. Example:
/// .function {} [ "__Memoize"("""v:1:{s:9:\"KeyedByIC\";}""") "__Reified"("""v:4:{i:1;i:0;i:0;i:0;}""")] (4,10) <"" N > memo$memoize_impl($a, $b)
fn assemble_function_flags(
name: hhbc::FunctionName<'_>,
token_iter: &mut Lexer<'_>,
) -> Result<hhbc::FunctionFlags> {
let mut flag = hhbc::FunctionFlags::empty();
while token_iter.peek_is(Token::is_identifier) {
let tok = token_iter.expect_token()?;
match tok.into_identifier()? {
b"isPairGenerator" => flag |= hhbc::FunctionFlags::PAIR_GENERATOR,
b"isAsync" => flag |= hhbc::FunctionFlags::ASYNC,
b"isGenerator" => flag |= hhbc::FunctionFlags::GENERATOR,
_ => return Err(tok.error("Unknown function flag")),
}
}
if name.as_bstr().ends_with(b"$memoize_impl") {
flag |= hhbc::FunctionFlags::MEMOIZE_IMPL;
}
Ok(flag)
}
/// Parses over filepath. Note that HCU doesn't hold the filepath; filepath is in the context passed to the
/// bytecode printer. So we don't store the filepath in our HCU or anywhere, but still parse over it
/// Filepath: .filepath strliteral semicolon (.filepath already consumed in `assemble_from_toks)
fn assemble_filepath(token_iter: &mut Lexer<'_>) -> Result<PathBuf> {
// Filepath is .filepath strliteral and semicolon
parse!(token_iter, ".filepath" <fp:string> ";");
let fp = Path::new(OsStr::from_bytes(fp.into_unquoted_str_literal()?));
Ok(fp.to_path_buf())
}
/// Span ex: (2, 4)
fn assemble_span(token_iter: &mut Lexer<'_>) -> Result<hhbc::Span> {
parse!(token_iter, "(" <line_begin:numeric> "," <line_end:numeric> ")");
Ok(hhbc::Span {
line_begin,
line_end,
})
}
/// Ex: {(T as <"HH\\int" "HH\\int" upper_bound>)}
/// {(id as type_info, type_info ... ), (id as type_info, type_info ...)*}
fn assemble_upper_bounds<'arena>(
token_iter: &mut Lexer<'_>,
alloc: &'arena Bump,
) -> Result<Slice<'arena, hhbc::UpperBound<'arena>>> {
parse!(token_iter, "{" <ubs:assemble_upper_bound(alloc),*> "}");
Ok(Slice::from_vec(alloc, ubs))
}
/// Ex: (T as <"HH\\int" "HH\\int" upper_bound>)
fn assemble_upper_bound<'arena>(
token_iter: &mut Lexer<'_>,
alloc: &'arena Bump,
) -> Result<hhbc::UpperBound<'arena>> {
parse!(token_iter, "(" <id:id> "as" <tis:assemble_type_info(alloc, TypeInfoKind::NotEnumOrTypeDef),*> ")");
Ok(hhbc::UpperBound {
name: id.into_ffi_str(alloc),
bounds: Slice::from_vec(alloc, tis),
})
}
/// Ex: [ "__EntryPoint"("""v:0:{}""")]. This example lacks Attrs
/// Ex: [abstract final] This example lacks Attributes
fn assemble_special_and_user_attrs<'arena>(
token_iter: &mut Lexer<'_>,
alloc: &'arena Bump,
) -> Result<(
hhvm_types_ffi::ffi::Attr,
Slice<'arena, hhbc::Attribute<'arena>>,
)> {
let mut user_atts = Vec::new();
let mut tr = hhvm_types_ffi::ffi::Attr::AttrNone;
if token_iter.next_is(Token::is_open_bracket) {
while !token_iter.peek_is(Token::is_close_bracket) {
if token_iter.peek_is(Token::is_str_literal) {
user_atts.push(assemble_user_attr(token_iter, alloc)?)
} else if token_iter.peek_is(Token::is_identifier) {
tr.add(assemble_hhvm_attr(token_iter)?);
} else {
return Err(token_iter.error("Unknown token in special and user attrs"));
}
}
token_iter.expect(Token::is_close_bracket)?;
}
// If no special and user attrs then no [] printed
let user_atts = Slice::from_vec(alloc, user_atts);
Ok((tr, user_atts))
}
fn assemble_hhvm_attr(token_iter: &mut Lexer<'_>) -> Result<hhvm_types_ffi::ffi::Attr> {
let tok = token_iter.expect_token()?;
let flag = match tok.into_identifier()? {
b"abstract" => Attr::AttrAbstract,
b"bad_redeclare" => Attr::AttrNoBadRedeclare,
b"builtin" => Attr::AttrBuiltin,
b"deep_init" => Attr::AttrDeepInit,
b"dyn_callable" => Attr::AttrDynamicallyCallable,
b"dyn_constructible" => Attr::AttrDynamicallyConstructible,
b"enum" => Attr::AttrEnum,
b"enum_class" => Attr::AttrEnumClass,
b"final" => Attr::AttrFinal,
b"has_closure_coeffects_prop" => Attr::AttrHasClosureCoeffectsProp,
b"has_coeffect_rules" => Attr::AttrHasCoeffectRules,
b"initial_satisifes_tc" => Attr::AttrInitialSatisfiesTC,
b"interceptable" => Attr::AttrInterceptable,
b"interface" => Attr::AttrInterface,
b"internal" => Attr::AttrInternal,
b"is_closure_class" => Attr::AttrIsClosureClass,
b"is_const" => Attr::AttrIsConst,
b"is_foldable" => Attr::AttrIsFoldable,
b"is_meth_caller" => Attr::AttrIsMethCaller,
b"late_init" => Attr::AttrLateInit,
b"lsb" => Attr::AttrLSB,
b"none" => Attr::AttrNone,
b"noreifiedinit" => Attr::AttrNoReifiedInit,
b"no_dynamic_props" => Attr::AttrForbidDynamicProps,
b"no_expand_trait" => Attr::AttrNoExpandTrait,
b"no_fcall_builtin" => Attr::AttrNoFCallBuiltin,
b"no_implicit_nullable" => Attr::AttrNoImplicitNullable,
b"no_injection" => Attr::AttrNoInjection,
b"no_override" => Attr::AttrNoOverride,
b"persistent" => Attr::AttrPersistent,
b"private" => Attr::AttrPrivate,
b"protected" => Attr::AttrProtected,
b"prov_skip_frame" => Attr::AttrProvenanceSkipFrame,
b"public" => Attr::AttrPublic,
b"readonly" => Attr::AttrIsReadonly,
b"readonly_return" => Attr::AttrReadonlyReturn,
b"readonly_this" => Attr::AttrReadonlyThis,
b"sealed" => Attr::AttrSealed,
b"static" => Attr::AttrStatic,
b"support_async_eager_return" => Attr::AttrSupportsAsyncEagerReturn,
b"sys_initial_val" => Attr::AttrSystemInitialValue,
b"trait" => Attr::AttrTrait,
b"unused_max_attr" => Attr::AttrUnusedMaxAttr,
b"variadic_param" => Attr::AttrVariadicParam,
_ => return Err(tok.error("Unknown attr")),
};
Ok(flag)
}
/// Attributes are printed as follows:
/// "name"("""v:args.len:{args}""") where args are typed values.
fn assemble_user_attr<'arena>(
token_iter: &mut Lexer<'_>,
alloc: &'arena Bump,
) -> Result<hhbc::Attribute<'arena>> {
let nm = escaper::unescape_literal_bytes_into_vec_bytes(
token_iter.expect_with(Token::into_unquoted_str_literal)?,
)?;
let name = Str::new_slice(alloc, &nm);
token_iter.expect(Token::is_open_paren)?;
let arguments = assemble_user_attr_args(alloc, token_iter)?;
token_iter.expect(Token::is_close_paren)?;
Ok(hhbc::Attribute { name, arguments })
}
/// Printed as follows (print_attributes in bcp)
/// "v:args.len:{args}" where args are typed values
fn assemble_user_attr_args<'arena>(
alloc: &'arena Bump,
token_iter: &mut Lexer<'_>,
) -> Result<Slice<'arena, hhbc::TypedValue<'arena>>> {
let tok = token_iter.peek().copied();
if let hhbc::TypedValue::Vec(sl) = assemble_triple_quoted_typed_value(token_iter, alloc)? {
Ok(sl)
} else {
Err(tok
.unwrap()
.error("Malformed user_attr_args -- should be a vec"))
}
}
#[derive(PartialEq)]
pub enum TypeInfoKind {
TypeDef,
Enum,
NotEnumOrTypeDef,
}
fn assemble_type_info<'arena>(
token_iter: &mut Lexer<'_>,
alloc: &'arena Bump,
tik: TypeInfoKind,
) -> Result<hhbc::TypeInfo<'arena>> {
let loc = token_iter.peek().copied();
if let Maybe::Just(ti) = assemble_type_info_opt(token_iter, alloc, tik)? {
Ok(ti)
} else if let Some(loc) = loc {
Err(loc.error("TypeInfo expected"))
} else {
Err(anyhow!("TypeInfo expected at end"))
}
}
fn assemble_type_info_union<'arena>(
token_iter: &mut Lexer<'_>,
alloc: &'arena Bump,
) -> Result<Slice<'arena, hhbc::TypeInfo<'arena>>> {
parse!(token_iter, <tis:assemble_type_info(alloc, TypeInfoKind::TypeDef),*>);
Ok(Slice::from_vec(alloc, tis))
}
/// Ex: <"HH\\void" N >
/// < "user_type" "type_constraint.name" type_constraint.flags >
/// if 'is_enum', no type_constraint name printed
/// if 'is_typedef', no user_type name printed
fn assemble_type_info_opt<'arena>(
token_iter: &mut Lexer<'_>,
alloc: &'arena Bump,
tik: TypeInfoKind,
) -> Result<Maybe<hhbc::TypeInfo<'arena>>> {
if token_iter.next_is(Token::is_lt) {
let first = token_iter.expect_with(Token::into_unquoted_str_literal)?;
let first = escaper::unescape_literal_bytes_into_vec_bytes(first)?;
let type_cons_name = if tik == TypeInfoKind::TypeDef {
if first.is_empty() {
Maybe::Nothing
} else {
Maybe::Just(Str::new_slice(alloc, &first))
}
} else if tik == TypeInfoKind::Enum || token_iter.next_is_str(Token::is_identifier, "N") {
Maybe::Nothing
} else {
Maybe::Just(Str::new_slice(
alloc,
&escaper::unescape_literal_bytes_into_vec_bytes(
token_iter.expect_with(Token::into_unquoted_str_literal)?,
)?,
))
};
let user_type = if tik != TypeInfoKind::TypeDef {
Maybe::Just(Str::new_slice(alloc, &first))
} else {
Maybe::Nothing
};
let mut tcflags = hhvm_types_ffi::ffi::TypeConstraintFlags::NoFlags;
while !token_iter.peek_is(Token::is_gt) {
tcflags = tcflags | assemble_type_constraint(token_iter)?;
}
token_iter.expect(Token::is_gt)?;
let cons = hhbc::Constraint::make(type_cons_name, tcflags);
Ok(Maybe::Just(hhbc::TypeInfo::make(user_type, cons)))
} else {
Ok(Maybe::Nothing)
}
}
fn assemble_type_constraint(
token_iter: &mut Lexer<'_>,
) -> Result<hhvm_types_ffi::ffi::TypeConstraintFlags> {
use hhvm_types_ffi::ffi::TypeConstraintFlags;
let tok = token_iter.expect_token()?;
match tok.into_identifier()? {
b"upper_bound" => Ok(TypeConstraintFlags::UpperBound),
b"display_nullable" => Ok(TypeConstraintFlags::DisplayNullable),
//no mock objects
//resolved
b"type_constant" => Ok(TypeConstraintFlags::TypeConstant),
b"soft" => Ok(TypeConstraintFlags::Soft),
b"type_var" => Ok(TypeConstraintFlags::TypeVar),
b"extended_hint" => Ok(TypeConstraintFlags::ExtendedHint),
b"nullable" => Ok(TypeConstraintFlags::Nullable),
_ => Err(tok.error("Unknown type constraint flag")),
}
}
/// ((a, )*a) | () where a is a param
fn assemble_params<'arena>(
alloc: &'arena Bump,
token_iter: &mut Lexer<'_>,
decl_map: &mut DeclMap<'arena>,
) -> Result<Slice<'arena, hhbc::Param<'arena>>> {
token_iter.expect(Token::is_open_paren)?;
let mut params = Vec::new();
while !token_iter.peek_is(Token::is_close_paren) {
params.push(assemble_param(alloc, token_iter, decl_map)?);
if !token_iter.peek_is(Token::is_close_paren) {
token_iter.expect(Token::is_comma)?;
}
}
token_iter.expect(Token::is_close_paren)?;
Ok(Slice::from_vec(alloc, params))
}
/// a: [user_attributes]? inout? readonly? ...?<type_info>?name (= default_value)?
fn assemble_param<'arena>(
alloc: &'arena Bump,
token_iter: &mut Lexer<'_>,
decl_map: &mut DeclMap<'arena>,
) -> Result<hhbc::Param<'arena>> {
let mut ua_vec = Vec::new();
let user_attributes = {
if token_iter.peek_is(Token::is_open_bracket) {
token_iter.expect(Token::is_open_bracket)?;
while !token_iter.peek_is(Token::is_close_bracket) {
ua_vec.push(assemble_user_attr(token_iter, alloc)?);
}
token_iter.expect(Token::is_close_bracket)?;
}
Slice::from_vec(alloc, ua_vec)
};
let is_inout = token_iter.next_is_str(Token::is_identifier, "inout");
let is_readonly = token_iter.next_is_str(Token::is_identifier, "readonly");
let is_variadic = token_iter.next_is(Token::is_variadic);
let type_info = assemble_type_info_opt(token_iter, alloc, TypeInfoKind::NotEnumOrTypeDef)?;
let name = token_iter.expect_with(Token::into_variable)?;
let name = Str::new_slice(alloc, name);
decl_map.insert(name, decl_map.len() as u32);
let default_value = assemble_default_value(alloc, token_iter)?;
Ok(hhbc::Param {
name,
is_variadic,
is_inout,
is_readonly,
user_attributes,
type_info,
default_value,
})
}
/// Ex: $skip_top_libcore = DV13("""true""")
/// Parsing after the variable name
fn assemble_default_value<'arena>(
alloc: &'arena Bump,
token_iter: &mut Lexer<'_>,
) -> Result<Maybe<hhbc::DefaultValue<'arena>>> {
let tr = if token_iter.next_is(Token::is_equal) {
let label = assemble_label(token_iter)?;
token_iter.expect(Token::is_open_paren)?;
let expr = assemble_unescaped_unquoted_triple_str(token_iter, alloc)?;
token_iter.expect(Token::is_close_paren)?;
Maybe::Just(hhbc::DefaultValue { label, expr })
} else {
Maybe::Nothing
};
Ok(tr)
}
/// { (.doc ...)? (.ismemoizewrapper)? (.ismemoizewrapperlsb)? (.numiters)? (.declvars)? (instructions)* }
fn assemble_body<'arena>(
alloc: &'arena Bump,
token_iter: &mut Lexer<'_>,
decl_map: &mut DeclMap<'arena>,
params: Slice<'arena, hhbc::Param<'arena>>,
return_type_info: Maybe<hhbc::TypeInfo<'arena>>,
shadowed_tparams: Slice<'arena, Str<'arena>>,
upper_bounds: Slice<'arena, hhbc::UpperBound<'arena>>,
) -> Result<(hhbc::Body<'arena>, hhbc::Coeffects<'arena>)> {
let mut doc_comment = Maybe::Nothing;
let mut instrs = Vec::new();
let mut decl_vars = Slice::default();
let mut num_iters = 0;
let mut coeff = hhbc::Coeffects::default();
let mut is_memoize_wrapper = false;
let mut is_memoize_wrapper_lsb = false;
// For now we don't parse params, so will just have decl_vars (might need to move this later)
token_iter.expect(Token::is_open_curly)?;
// In body, before instructions, are 5 possible constructs:
// only .declvars can be declared more than once
while token_iter.peek_is(Token::is_decl) {
if token_iter.peek_is_str(Token::is_decl, ".doc") {
doc_comment = assemble_doc_comment(token_iter, alloc)?;
} else if token_iter.peek_is_str(Token::is_decl, ".ismemoizewrapperlsb") {
token_iter.expect_str(Token::is_decl, ".ismemoizewrapperlsb")?;
token_iter.expect(Token::is_semicolon)?;
is_memoize_wrapper_lsb = true;
} else if token_iter.peek_is_str(Token::is_decl, ".ismemoizewrapper") {
token_iter.expect_str(Token::is_decl, ".ismemoizewrapper")?;
token_iter.expect(Token::is_semicolon)?;
is_memoize_wrapper = true;
} else if token_iter.peek_is_str(Token::is_decl, ".numiters") {
if num_iters != 0 {
token_iter.error("Cannot have more than one .numiters per function body");
}
num_iters = assemble_numiters(token_iter)?;
} else if token_iter.peek_is_str(Token::is_decl, ".declvars") {
if !decl_vars.is_empty() {
return Err(
token_iter.error("Cannot have more than one .declvars per function body")
);
}
decl_vars = assemble_decl_vars(alloc, token_iter, decl_map)?;
} else if token_iter.peek_is(is_coeffects_decl) {
coeff = assemble_coeffects(alloc, token_iter)?;
} else {
break;
}
}
// tcb_count tells how many TryCatchBegins there are that are still unclosed
// we only stop parsing instructions once we see a is_close_curly and tcb_count is 0
let mut tcb_count = 0;
while tcb_count > 0 || !token_iter.peek_is(Token::is_close_curly) {
instrs.push(assemble_instr(alloc, token_iter, decl_map, &mut tcb_count)?);
}
token_iter.expect(Token::is_close_curly)?;
let body_instrs = Slice::from_vec(alloc, instrs);
let stack_depth = stack_depth::compute_stack_depth(params.as_ref(), body_instrs.as_ref())?;
let tr = hhbc::Body {
body_instrs,
decl_vars,
num_iters,
is_memoize_wrapper,
is_memoize_wrapper_lsb,
doc_comment,
params,
return_type_info,
shadowed_tparams,
stack_depth,
upper_bounds,
};
Ok((tr, coeff))
}
fn is_coeffects_decl(tok: &Token<'_>) -> bool {
match tok {
Token::Decl(id, _) => id.starts_with(b".coeffects"),
_ => false,
}
}
/// Printed in this order (if exists)
/// static and unenforced static coeffects (.coeffects_static ... );
/// .coeffects_fun_param ..;
/// .coeffects_cc_param ..;
/// .coeffects_cc_this;
/// .coeffects_cc_reified;
/// .coeffects_closure_parent_scope;
/// .coeffects_generator_this;
/// .coeffects_caller;
fn assemble_coeffects<'arena>(
alloc: &'arena Bump,
token_iter: &mut Lexer<'_>,
) -> Result<hhbc::Coeffects<'arena>> {
let mut scs = Vec::new();
let mut uscs = Vec::new();
let mut fun_param = Vec::new();
let mut cc_param = Vec::new();
let mut cc_this = Vec::new();
let mut cc_reified = Vec::new();
let mut closure_parent_scope = false;
let mut generator_this = false;
let mut caller = false;
while token_iter.peek_is(is_coeffects_decl) {
if token_iter.peek_is_str(Token::is_decl, ".coeffects_static") {
assemble_static_coeffects(alloc, token_iter, &mut scs, &mut uscs)?;
}
if token_iter.peek_is_str(Token::is_decl, ".coeffects_fun_param") {
assemble_coeffects_fun_param(token_iter, &mut fun_param)?;
}
if token_iter.peek_is_str(Token::is_decl, ".coeffects_cc_param") {
assemble_coeffects_cc_param(alloc, token_iter, &mut cc_param)?;
}
if token_iter.peek_is_str(Token::is_decl, ".coeffects_cc_this") {
assemble_coeffects_cc_this(alloc, token_iter, &mut cc_this)?;
}
if token_iter.peek_is_str(Token::is_decl, ".coeffects_cc_reified") {
assemble_coeffects_cc_reified(alloc, token_iter, &mut cc_reified)?;
}
closure_parent_scope =
token_iter.next_is_str(Token::is_decl, ".coeffects_closure_parent_scope");
if closure_parent_scope {
token_iter.expect(Token::is_semicolon)?;
}
generator_this = token_iter.next_is_str(Token::is_decl, ".coeffects_generator_this");
if generator_this {
token_iter.expect(Token::is_semicolon)?;
}
caller = token_iter.next_is_str(Token::is_decl, ".coeffects_caller");
if caller {
token_iter.expect(Token::is_semicolon)?;
}
}
Ok(hhbc::Coeffects::new(
Slice::from_vec(alloc, scs),
Slice::from_vec(alloc, uscs),
Slice::from_vec(alloc, fun_param),
Slice::from_vec(alloc, cc_param),
Slice::from_vec(alloc, cc_this),
Slice::from_vec(alloc, cc_reified),
closure_parent_scope,
generator_this,
caller,
))
}
/// Ex: .coeffects_static pure
fn assemble_static_coeffects<'arena>(
alloc: &'arena Bump,
token_iter: &mut Lexer<'_>,
scs: &mut Vec<Ctx>,
uscs: &mut Vec<Str<'arena>>,
) -> Result<()> {
token_iter.expect_str(Token::is_decl, ".coeffects_static")?;
while !token_iter.peek_is(Token::is_semicolon) {
match token_iter.expect_with(Token::into_identifier)? {
b"pure" => scs.push(Ctx::Pure),
b"defaults" => scs.push(Ctx::Defaults),
b"rx" => scs.push(Ctx::Rx),
b"zoned" => scs.push(Ctx::Zoned),
b"write_props" => scs.push(Ctx::WriteProps),
b"rx_local" => scs.push(Ctx::RxLocal),
b"zoned_with" => scs.push(Ctx::ZonedWith),
b"zoned_local" => scs.push(Ctx::ZonedLocal),
b"zoned_shallow" => scs.push(Ctx::ZonedShallow),
b"leak_safe_local" => scs.push(Ctx::LeakSafeLocal),
b"leak_safe_shallow" => scs.push(Ctx::LeakSafeShallow),
b"leak_safe" => scs.push(Ctx::LeakSafe),
b"read_globals" => scs.push(Ctx::ReadGlobals),
b"globals" => scs.push(Ctx::Globals),
b"write_this_props" => scs.push(Ctx::WriteThisProps),
b"rx_shallow" => scs.push(Ctx::RxShallow),
d => uscs.push(Str::new_slice(alloc, d)), //If unknown Ctx, is a unenforce_static_coeffect (ex: output)
}
}
token_iter.expect(Token::is_semicolon)?;
Ok(())
}
/// Ex:
/// .coeffects_fun_param 0;
fn assemble_coeffects_fun_param(
token_iter: &mut Lexer<'_>,
fun_param: &mut Vec<u32>,
) -> Result<()> {
token_iter.expect_str(Token::is_decl, ".coeffects_fun_param")?;
while !token_iter.peek_is(Token::is_semicolon) {
fun_param.push(token_iter.expect_and_get_number()?);
}
token_iter.expect(Token::is_semicolon)?;
Ok(())
}
/// Ex:
/// .coeffects_cc_param 0 C 0 Cdebug;
fn assemble_coeffects_cc_param<'arena>(
alloc: &'arena Bump,
token_iter: &mut Lexer<'_>,
cc_param: &mut Vec<hhbc::CcParam<'arena>>,
) -> Result<()> {
token_iter.expect_str(Token::is_decl, ".coeffects_cc_param")?;
while !token_iter.peek_is(Token::is_semicolon) {
let index = token_iter.expect_and_get_number()?;
let ctx_name = token_iter.expect(Token::is_identifier)?.into_ffi_str(alloc);
cc_param.push(hhbc::CcParam { index, ctx_name });
}
token_iter.expect(Token::is_semicolon)?;
Ok(())
}
/// Ex:
/// .coeffects_cc_this Cdebug;
fn assemble_coeffects_cc_this<'arena>(
alloc: &'arena Bump,
token_iter: &mut Lexer<'_>,
cc_this: &mut Vec<hhbc::CcThis<'arena>>,
) -> Result<()> {
token_iter.expect_str(Token::is_decl, ".coeffects_cc_this")?;
let mut params = Vec::new();
while !token_iter.peek_is(Token::is_semicolon) {
params.push(token_iter.expect(Token::is_identifier)?.into_ffi_str(alloc));
}
token_iter.expect(Token::is_semicolon)?;
cc_this.push(hhbc::CcThis {
types: Slice::from_vec(alloc, params),
});
Ok(())
}
/// .coeffects_cc_reified 0 C;
fn assemble_coeffects_cc_reified<'arena>(
alloc: &'arena Bump,
token_iter: &mut Lexer<'_>,
cc_reified: &mut Vec<hhbc::CcReified<'arena>>,
) -> Result<()> {
token_iter.expect_str(Token::is_decl, ".coeffects_cc_reified")?;
let is_class = token_iter.next_is_str(Token::is_identifier, "isClass");
let index = token_iter.expect_and_get_number()?;
let mut types = Vec::new();
while !token_iter.peek_is(Token::is_semicolon) {
types.push(token_iter.expect(Token::is_identifier)?.into_ffi_str(alloc));
}
token_iter.expect(Token::is_semicolon)?;
cc_reified.push(hhbc::CcReified {
is_class,
index,
types: Slice::from_vec(alloc, types),
});
Ok(())
}
/// Expects .numiters #+;
fn assemble_numiters(token_iter: &mut Lexer<'_>) -> Result<usize> {
token_iter.expect_str(Token::is_decl, ".numiters")?;
let num = token_iter.expect_and_get_number()?;
token_iter.expect(Token::is_semicolon)?;
Ok(num)
}
/// Expects .declvars ($x)+;
fn assemble_decl_vars<'arena>(
alloc: &'arena Bump,
token_iter: &mut Lexer<'_>,
decl_map: &mut DeclMap<'arena>,
) -> Result<Slice<'arena, Str<'arena>>> {
token_iter.expect_str(Token::is_decl, ".declvars")?;
let mut var_names = Vec::new();
while !token_iter.peek_is(Token::is_semicolon) {
let var_nm = token_iter.expect_var()?;
let var_nm = Str::new_slice(alloc, &var_nm);
var_names.push(var_nm);
decl_map.insert(var_nm, decl_map.len().try_into().unwrap());
}
token_iter.expect(Token::is_semicolon)?;
Ok(Slice::from_vec(alloc, var_names))
}
#[assemble_opcode_macro::assemble_opcode]
fn assemble_opcode<'arena>(
alloc: &'arena Bump,
tok: &'_ [u8],
token_iter: &mut Lexer<'_>,
decl_map: &mut DeclMap<'arena>,
) -> Result<hhbc::Instruct<'arena>> {
// This is filled in by the macro.
}
/// Opcodes and Pseudos
fn assemble_instr<'arena>(
alloc: &'arena Bump,
token_iter: &mut Lexer<'_>,
decl_map: &mut DeclMap<'arena>,
tcb_count: &mut usize, // Increase this when get TryCatchBegin, decrease when TryCatchEnd
) -> Result<hhbc::Instruct<'arena>> {
if let Some(mut sl_lexer) = token_iter.split_at_newline() {
if sl_lexer.peek_is(Token::is_decl) {
// Not all pseudos are decls, but all instruction decls are pseudos
if sl_lexer.peek_is_str(Token::is_decl, ".srcloc") {
Ok(hhbc::Instruct::Pseudo(hhbc::Pseudo::SrcLoc(
assemble_srcloc(&mut sl_lexer)?,
)))
} else if sl_lexer.next_is_str(Token::is_decl, ".try") {
sl_lexer.expect(Token::is_open_curly)?;
*tcb_count += 1;
Ok(hhbc::Instruct::Pseudo(hhbc::Pseudo::TryCatchBegin))
} else {
todo!("{}", sl_lexer.next().unwrap());
}
} else if sl_lexer.next_is(Token::is_close_curly) {
if sl_lexer.next_is_str(Token::is_decl, ".catch") {
// Is a TCM
sl_lexer.expect(Token::is_open_curly)?;
Ok(hhbc::Instruct::Pseudo(hhbc::Pseudo::TryCatchMiddle))
} else {
// Is a TCE
debug_assert!(*tcb_count > 0);
*tcb_count -= 1;
Ok(hhbc::Instruct::Pseudo(hhbc::Pseudo::TryCatchEnd))
}
} else if sl_lexer.peek_is(Token::is_identifier) {
let tb = sl_lexer.peek().unwrap().as_bytes();
if sl_lexer.peek1().map_or(false, |tok| tok.is_colon()) {
// It's actually a label.
// DV123: or L123:
let label = assemble_label(&mut sl_lexer)?;
sl_lexer.expect(Token::is_colon)?;
return Ok(hhbc::Instruct::Pseudo(hhbc::Pseudo::Label(label)));
}
match tb {
b"MemoGetEager" => assemble_memo_get_eager(&mut sl_lexer),
b"SSwitch" => assemble_sswitch(alloc, &mut sl_lexer),
tb => assemble_opcode(alloc, tb, &mut sl_lexer, decl_map),
}
} else {
Err(sl_lexer.error("Function body line that's neither decl or identifier."))
}
} else {
bail!("Expected an additional instruction in body, reached EOF");
}
}
/// .srcloc #:#,#:#;
fn assemble_srcloc(token_iter: &mut Lexer<'_>) -> Result<hhbc::SrcLoc> {
token_iter.expect_str(Token::is_decl, ".srcloc")?;
let tr = hhbc::SrcLoc {
line_begin: token_iter.expect_and_get_number()?,
col_begin: {
token_iter.expect(Token::is_colon)?;
token_iter.expect_and_get_number()?
},
line_end: {
token_iter.expect(Token::is_comma)?;
token_iter.expect_and_get_number()?
},
col_end: {
token_iter.expect(Token::is_colon)?;
token_iter.expect_and_get_number()?
},
};
token_iter.expect(Token::is_semicolon)?;
token_iter.expect_end()?;
Ok(tr)
}
/// <(fcallargflag)*>
pub(crate) fn assemble_fcallargsflags(token_iter: &mut Lexer<'_>) -> Result<hhbc::FCallArgsFlags> {
let mut flags = hhbc::FCallArgsFlags::FCANone;
token_iter.expect(Token::is_lt)?;
while !token_iter.peek_is(Token::is_gt) {
let tok = token_iter.expect_token()?;
match tok.into_identifier()? {
b"Unpack" => flags.add(hhbc::FCallArgsFlags::HasUnpack),
b"Generics" => flags.add(hhbc::FCallArgsFlags::HasGenerics),
b"LockWhileUnwinding" => flags.add(hhbc::FCallArgsFlags::LockWhileUnwinding),
b"SkipRepack" => flags.add(hhbc::FCallArgsFlags::SkipRepack),
b"SkipCoeffectsCheck" => flags.add(hhbc::FCallArgsFlags::SkipCoeffectsCheck),
b"EnforceMutableReturn" => flags.add(hhbc::FCallArgsFlags::EnforceMutableReturn),
b"EnforceReadonlyThis" => flags.add(hhbc::FCallArgsFlags::EnforceReadonlyThis),
b"ExplicitContext" => flags.add(hhbc::FCallArgsFlags::ExplicitContext),
b"HasInOut" => flags.add(hhbc::FCallArgsFlags::HasInOut),
b"EnforceInOut" => flags.add(hhbc::FCallArgsFlags::EnforceInOut),
b"EnforceReadonly" => flags.add(hhbc::FCallArgsFlags::EnforceReadonly),
b"HasAsyncEagerOffset" => flags.add(hhbc::FCallArgsFlags::HasAsyncEagerOffset),
b"NumArgsStart" => flags.add(hhbc::FCallArgsFlags::NumArgsStart),
_ => return Err(tok.error("Unrecognized FCallArgsFlags")),
}
}
token_iter.expect(Token::is_gt)?;
Ok(flags)
}
/// "(0|1)*"
pub(crate) fn assemble_inouts_or_readonly<'arena>(
alloc: &'arena Bump,
token_iter: &mut Lexer<'_>,
) -> Result<Slice<'arena, bool>> {
let tok = token_iter.expect_token()?;
let literal = tok.into_str_literal()?;
debug_assert!(literal[0] == b'"' && literal[literal.len() - 1] == b'"');
let tr: Result<Vec<bool>, _> = literal[1..literal.len() - 1] //trims the outer "", which are guaranteed b/c of str token
.iter()
.map(|c| match *c {
b'0' => Ok(false),
b'1' => Ok(true),
_ => Err(tok.error("Non 0/1 character in inouts/readonlys")),
})
.collect();
Ok(Slice::from_vec(alloc, tr?))
}
/// - or a label
pub(crate) fn assemble_async_eager_target(
token_iter: &mut Lexer<'_>,
) -> Result<Option<hhbc::Label>> {
if token_iter.next_is(Token::is_dash) {
Ok(None)
} else {
Ok(Some(assemble_label(token_iter)?))
}
}
/// Just a string literal
pub(crate) fn assemble_fcall_context<'arena>(
alloc: &'arena Bump,
token_iter: &mut Lexer<'_>,
) -> Result<Str<'arena>> {
let st = token_iter.expect_with(Token::into_str_literal)?;
debug_assert!(st[0] == b'"' && st[st.len() - 1] == b'"');
Ok(Str::new_slice(alloc, &st[1..st.len() - 1])) // if not hugged by "", won't pass into_str_literal
}
pub(crate) fn assemble_unescaped_unquoted_str<'arena>(
alloc: &'arena Bump,
token_iter: &mut Lexer<'_>,
) -> Result<Str<'arena>> {
let st = escaper::unescape_literal_bytes_into_vec_bytes(
token_iter.expect_with(Token::into_unquoted_str_literal)?,
)?;
Ok(Str::new_slice(alloc, &st))
}
fn assemble_unescaped_unquoted_triple_str<'arena>(
token_iter: &mut Lexer<'_>,
alloc: &'arena Bump,
) -> Result<Str<'arena>> {
let st = escaper::unquote_slice(escaper::unquote_slice(escaper::unquote_slice(
token_iter.expect_with(Token::into_triple_str_literal)?,
)));
let st = escaper::unescape_literal_bytes_into_vec_bytes(st)?;
Ok(Str::new_slice(alloc, &st))
}
/// Ex:
/// SSwitch <"ARRAY7":L0 "ARRAY8":L1 "ARRAY9":L2 -:L3>
fn assemble_sswitch<'arena>(
alloc: &'arena Bump,
token_iter: &mut Lexer<'_>,
) -> Result<hhbc::Instruct<'arena>> {
let mut cases = Vec::new(); // Of Str<'arena>
let mut targets = Vec::new(); // Of Labels
token_iter.expect_str(Token::is_identifier, "SSwitch")?;
token_iter.expect(Token::is_lt)?;
// The last case is printed as '-' but interior it is "default"
while !token_iter.peek_is(Token::is_gt) {
if token_iter.peek_is(Token::is_dash) {
// Last item; printed as '-' but is "default"
token_iter.next();
cases.push(Str::new_str(alloc, "default"));
} else {
cases.push(assemble_unescaped_unquoted_str(alloc, token_iter)?);
}
token_iter.expect(Token::is_colon)?;
targets.push(assemble_label(token_iter)?);
}
token_iter.expect(Token::is_gt)?;
Ok(hhbc::Instruct::Opcode(hhbc::Opcode::SSwitch {
cases: Slice::from_vec(alloc, cases),
targets: Slice::from_vec(alloc, targets),
_0: hhbc::Dummy::DEFAULT,
}))
}
/// Ex:
/// MemoGetEager L0 L1 l:0+0
fn assemble_memo_get_eager<'arena>(token_iter: &mut Lexer<'_>) -> Result<hhbc::Instruct<'arena>> {
token_iter.expect_str(Token::is_identifier, "MemoGetEager")?;
let lbl_slice = [assemble_label(token_iter)?, assemble_label(token_iter)?];
let dum = hhbc::Dummy::DEFAULT;
let lcl_range = assemble_local_range(token_iter)?;
Ok(hhbc::Instruct::Opcode(hhbc::Opcode::MemoGetEager(
lbl_slice, dum, lcl_range,
)))
}
/// Ex:
/// MemoGet L0 L:0+0
/// last item is a local range
fn assemble_local_range(token_iter: &mut Lexer<'_>) -> Result<hhbc::LocalRange> {
token_iter.expect_str(Token::is_identifier, "L")?;
token_iter.expect(Token::is_colon)?;
let start = hhbc::Local {
idx: token_iter.expect_and_get_number()?,
};
//token_iter.expect(Token::is_plus)?; // Not sure if this exists yet
let len = token_iter.expect_and_get_number()?;
Ok(hhbc::LocalRange { start, len })
}
/// L# or DV#
pub(crate) fn assemble_label(token_iter: &mut Lexer<'_>) -> Result<hhbc::Label> {
let tok = token_iter.expect_token()?;
let lcl = tok.into_identifier()?;
let rest = if lcl.starts_with(b"DV") {
Some(&lcl[2..])
} else if lcl.starts_with(b"L") {
Some(&lcl[1..])
} else {
None
};
if let Some(rest) = rest {
let value = std::str::from_utf8(rest)?.parse::<u32>()?;
Ok(hhbc::Label(value))
} else {
Err(tok.error("Unknown label"))
}
} |
Rust | hhvm/hphp/hack/src/hackc/assemble/assemble_imm.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use anyhow::bail;
use anyhow::Result;
use assemble_opcode_macro::assemble_imm_for_enum;
use bumpalo::Bump;
use ffi::Slice;
use ffi::Str;
use crate::assemble;
use crate::assemble::DeclMap;
use crate::lexer::Lexer;
use crate::token::Token;
assemble_imm_for_enum!(
hhbc::BareThisOp,
[
BareThisOp::NeverNull,
BareThisOp::NoNotice,
BareThisOp::Notice
]
);
assemble_imm_for_enum!(
hhbc::CollectionType,
[
CollectionType::ImmMap,
CollectionType::ImmSet,
CollectionType::ImmVector,
CollectionType::Map,
CollectionType::Pair,
CollectionType::Set,
CollectionType::Vector,
]
);
assemble_imm_for_enum!(
hhbc::FatalOp,
[FatalOp::Parse, FatalOp::Runtime, FatalOp::RuntimeOmitFrame,]
);
assemble_imm_for_enum!(
hhbc::IncDecOp,
[
IncDecOp::PostDec,
IncDecOp::PostInc,
IncDecOp::PreDec,
IncDecOp::PreInc,
]
);
assemble_imm_for_enum!(
hhbc::InitPropOp,
[InitPropOp::NonStatic, InitPropOp::Static]
);
assemble_imm_for_enum!(
hhbc::IsLogAsDynamicCallOp,
[
IsLogAsDynamicCallOp::DontLogAsDynamicCall,
IsLogAsDynamicCallOp::LogAsDynamicCall,
]
);
assemble_imm_for_enum!(
hhbc::IsTypeOp,
[
IsTypeOp::ArrLike,
IsTypeOp::Bool,
IsTypeOp::Class,
IsTypeOp::ClsMeth,
IsTypeOp::Dbl,
IsTypeOp::Dict,
IsTypeOp::Func,
IsTypeOp::Int,
IsTypeOp::Keyset,
IsTypeOp::LegacyArrLike,
IsTypeOp::Null,
IsTypeOp::Obj,
IsTypeOp::Res,
IsTypeOp::Scalar,
IsTypeOp::Str,
IsTypeOp::Vec,
]
);
assemble_imm_for_enum!(
hhbc::MOpMode,
[
MOpMode::Define,
MOpMode::InOut,
MOpMode::None,
MOpMode::Unset,
MOpMode::Warn,
]
);
assemble_imm_for_enum!(
hhbc::ObjMethodOp,
[ObjMethodOp::NullSafe, ObjMethodOp::NullThrows,]
);
assemble_imm_for_enum!(
hhbc::OODeclExistsOp,
[
OODeclExistsOp::Class,
OODeclExistsOp::Interface,
OODeclExistsOp::Trait,
]
);
assemble_imm_for_enum!(
hhbc::QueryMOp,
[
QueryMOp::CGet,
QueryMOp::CGetQuiet,
QueryMOp::InOut,
QueryMOp::Isset,
]
);
assemble_imm_for_enum!(
hhbc::ReadonlyOp,
[
ReadonlyOp::Any,
ReadonlyOp::CheckMutROCOW,
ReadonlyOp::CheckROCOW,
ReadonlyOp::Mutable,
ReadonlyOp::Readonly,
]
);
assemble_imm_for_enum!(
hhbc::SetOpOp,
[
SetOpOp::AndEqual,
SetOpOp::ConcatEqual,
SetOpOp::DivEqual,
SetOpOp::MinusEqual,
SetOpOp::ModEqual,
SetOpOp::MulEqual,
SetOpOp::OrEqual,
SetOpOp::PlusEqual,
SetOpOp::PowEqual,
SetOpOp::SlEqual,
SetOpOp::SrEqual,
SetOpOp::XorEqual,
]
);
assemble_imm_for_enum!(hhbc::SetRangeOp, [SetRangeOp::Forward, SetRangeOp::Reverse]);
assemble_imm_for_enum!(hhbc::SilenceOp, [SilenceOp::End, SilenceOp::Start]);
assemble_imm_for_enum!(
hhbc::SpecialClsRef,
[
SpecialClsRef::LateBoundCls,
SpecialClsRef::ParentCls,
SpecialClsRef::SelfCls,
]
);
assemble_imm_for_enum!(
hhbc::TypeStructResolveOp,
[
TypeStructResolveOp::DontResolve,
TypeStructResolveOp::Resolve,
]
);
pub(crate) trait AssembleImm<'arena, T> {
fn assemble_imm(&mut self, alloc: &'arena Bump, decl_map: &DeclMap<'arena>) -> Result<T>;
}
impl AssembleImm<'_, i64> for Lexer<'_> {
fn assemble_imm(&mut self, _: &'_ Bump, _: &DeclMap<'_>) -> Result<i64> {
self.expect_and_get_number()
}
}
impl<'arena> AssembleImm<'arena, hhbc::AdataId<'arena>> for Lexer<'_> {
fn assemble_imm(
&mut self,
alloc: &'arena Bump,
_: &DeclMap<'arena>,
) -> Result<hhbc::AdataId<'arena>> {
let adata_id = self.expect_with(Token::into_global)?;
debug_assert!(adata_id[0] == b'@');
Ok(hhbc::AdataId::new(Str::new_slice(alloc, &adata_id[1..])))
}
}
impl<'arena> AssembleImm<'arena, hhbc::ClassName<'arena>> for Lexer<'_> {
fn assemble_imm(
&mut self,
alloc: &'arena Bump,
_: &DeclMap<'arena>,
) -> Result<hhbc::ClassName<'arena>> {
Ok(hhbc::ClassName::new(
assemble::assemble_unescaped_unquoted_str(alloc, self)?,
))
}
}
impl<'arena> AssembleImm<'arena, hhbc::ConstName<'arena>> for Lexer<'_> {
fn assemble_imm(
&mut self,
alloc: &'arena Bump,
_: &DeclMap<'arena>,
) -> Result<hhbc::ConstName<'arena>> {
Ok(hhbc::ConstName::new(
assemble::assemble_unescaped_unquoted_str(alloc, self)?,
))
}
}
impl AssembleImm<'_, hhbc::ContCheckOp> for Lexer<'_> {
fn assemble_imm(&mut self, _: &'_ Bump, _: &DeclMap<'_>) -> Result<hhbc::ContCheckOp> {
todo!();
}
}
impl<'arena> AssembleImm<'arena, hhbc::FCallArgs<'arena>> for Lexer<'_> {
fn assemble_imm(
&mut self,
alloc: &'arena Bump,
_: &DeclMap<'arena>,
) -> Result<hhbc::FCallArgs<'arena>> {
// <(fcargflags)*> numargs numrets inouts readonly async_eager_target context
let fcargflags = assemble::assemble_fcallargsflags(self)?;
let num_args = self.expect_and_get_number()?;
let num_rets = self.expect_and_get_number()?;
let inouts = assemble::assemble_inouts_or_readonly(alloc, self)?;
let readonly = assemble::assemble_inouts_or_readonly(alloc, self)?;
let async_eager_target = assemble::assemble_async_eager_target(self)?;
let context = assemble::assemble_fcall_context(alloc, self)?;
let fcargs = hhbc::FCallArgs::new(
fcargflags,
num_rets,
num_args,
inouts,
readonly,
async_eager_target,
None,
);
Ok(hhbc::FCallArgs { context, ..fcargs })
}
}
impl AssembleImm<'_, hhbc::FloatBits> for Lexer<'_> {
fn assemble_imm(&mut self, _: &'_ Bump, _: &DeclMap<'_>) -> Result<hhbc::FloatBits> {
Ok(hhbc::FloatBits(self.expect_and_get_number()?))
}
}
impl<'arena> AssembleImm<'arena, hhbc::FunctionName<'arena>> for Lexer<'_> {
fn assemble_imm(
&mut self,
alloc: &'arena Bump,
_: &DeclMap<'arena>,
) -> Result<hhbc::FunctionName<'arena>> {
Ok(hhbc::FunctionName::new(
assemble::assemble_unescaped_unquoted_str(alloc, self)?,
))
}
}
impl AssembleImm<'_, hhbc::IterArgs> for Lexer<'_> {
fn assemble_imm(&mut self, alloc: &'_ Bump, decl_map: &DeclMap<'_>) -> Result<hhbc::IterArgs> {
// IterArg { iter_id: IterId (~u32), key_id: Local, val_id: Local}
// Ex: 0 NK V:$v
let idx: u32 = self.expect_and_get_number()?;
let tok = self.expect_token()?;
let key_id: hhbc::Local = match tok.into_identifier()? {
b"NK" => hhbc::Local::INVALID,
b"K" => {
self.expect(Token::is_colon)?;
self.assemble_imm(alloc, decl_map)?
}
_ => return Err(tok.error("Invalid key_id given as iter args to IterArg")),
};
self.expect_str(Token::is_identifier, "V")?;
self.expect(Token::is_colon)?;
let iter_id = hhbc::IterId { idx };
let val_id = self.assemble_imm(alloc, decl_map)?;
Ok(hhbc::IterArgs {
iter_id,
key_id,
val_id,
})
}
}
impl AssembleImm<'_, hhbc::IterId> for Lexer<'_> {
fn assemble_imm(&mut self, _: &'_ Bump, _: &DeclMap<'_>) -> Result<hhbc::IterId> {
Ok(hhbc::IterId {
idx: self.expect_and_get_number()?,
})
}
}
impl AssembleImm<'_, hhbc::Label> for Lexer<'_> {
fn assemble_imm(&mut self, _: &'_ Bump, _: &DeclMap<'_>) -> Result<hhbc::Label> {
assemble::assemble_label(self)
}
}
impl AssembleImm<'_, hhbc::Local> for Lexer<'_> {
fn assemble_imm(&mut self, _: &'_ Bump, decl_map: &DeclMap<'_>) -> Result<hhbc::Local> {
// Returns the local (u32 idx) a var or unnamed corresponds to.
// This information is based on the position of the var in parameters of a function/.declvars
// or, if an unnamed, just the idx referenced (_1 -> idx 1)
// $a -> idx where $a is stored in hcu body
// _3 -> 3
match self.next() {
Some(Token::Variable(v, p)) => {
if let Some(idx) = decl_map.get(v) {
Ok(hhbc::Local { idx: *idx })
} else {
bail!("Unknown local var: {:?} at {:?}", v, p);
}
}
Some(Token::Identifier(i, _)) => {
debug_assert!(i[0] == b'_');
Ok(hhbc::Local {
idx: std::str::from_utf8(&i[1..i.len()])?.parse()?,
})
}
Some(tok) => Err(tok.error("Unknown local")),
None => Err(self.error("Expected local")),
}
}
}
impl AssembleImm<'_, hhbc::LocalRange> for Lexer<'_> {
fn assemble_imm(&mut self, _: &'_ Bump, _: &DeclMap<'_>) -> Result<hhbc::LocalRange> {
self.expect_str(Token::is_identifier, "L")?;
self.expect(Token::is_colon)?;
let start = hhbc::Local {
idx: self.expect_and_get_number()?,
};
//self.expect(Token::is_plus)?; // Not sure if this exists yet
let len = self.expect_and_get_number()?;
Ok(hhbc::LocalRange { start, len })
}
}
impl<'arena> AssembleImm<'arena, hhbc::MemberKey<'arena>> for Lexer<'_> {
fn assemble_imm(
&mut self,
alloc: &'arena Bump,
decl_map: &DeclMap<'arena>,
) -> Result<hhbc::MemberKey<'arena>> {
// EC: stackIndex readOnlyOp | EL: local readOnlyOp | ET: string readOnlyOp | EI: int readOnlyOp
// PC: stackIndex readOnlyOp | PL: local readOnlyOp | PT: propName readOnlyOp | QT: propName readOnlyOp
let tok = self.expect_token()?;
match tok.into_identifier()? {
b"EC" => {
self.expect(Token::is_colon)?;
Ok(hhbc::MemberKey::EC(
self.assemble_imm(alloc, decl_map)?,
self.assemble_imm(alloc, decl_map)?,
))
}
b"EL" => {
self.expect(Token::is_colon)?;
Ok(hhbc::MemberKey::EL(
self.assemble_imm(alloc, decl_map)?,
self.assemble_imm(alloc, decl_map)?,
))
}
b"ET" => {
self.expect(Token::is_colon)?;
Ok(hhbc::MemberKey::ET(
Str::new_slice(
alloc,
&escaper::unescape_literal_bytes_into_vec_bytes(
// In bp, print_quoted_str also escapes the string
escaper::unquote_slice(self.expect_with(Token::into_str_literal)?),
)?,
),
self.assemble_imm(alloc, decl_map)?,
))
}
b"EI" => {
self.expect(Token::is_colon)?;
Ok(hhbc::MemberKey::EI(
self.expect_and_get_number()?,
self.assemble_imm(alloc, decl_map)?,
))
}
b"PC" => {
self.expect(Token::is_colon)?;
Ok(hhbc::MemberKey::PC(
self.assemble_imm(alloc, decl_map)?,
self.assemble_imm(alloc, decl_map)?,
))
}
b"PL" => {
self.expect(Token::is_colon)?;
Ok(hhbc::MemberKey::PL(
self.assemble_imm(alloc, decl_map)?,
self.assemble_imm(alloc, decl_map)?,
))
}
b"PT" => {
self.expect(Token::is_colon)?;
Ok(hhbc::MemberKey::PT(
assemble::assemble_prop_name_from_str(alloc, self)?,
self.assemble_imm(alloc, decl_map)?,
))
}
b"QT" => {
self.expect(Token::is_colon)?;
Ok(hhbc::MemberKey::QT(
assemble::assemble_prop_name_from_str(alloc, self)?,
self.assemble_imm(alloc, decl_map)?,
))
}
b"W" => Ok(hhbc::MemberKey::W),
_ => Err(tok.error("Expected a MemberKey")),
}
}
}
impl<'arena> AssembleImm<'arena, hhbc::MethodName<'arena>> for Lexer<'_> {
fn assemble_imm(
&mut self,
alloc: &'arena Bump,
_: &DeclMap<'arena>,
) -> Result<hhbc::MethodName<'arena>> {
Ok(hhbc::MethodName::new(
assemble::assemble_unescaped_unquoted_str(alloc, self)?,
))
}
}
impl<'arena> AssembleImm<'arena, hhbc::PropName<'arena>> for Lexer<'_> {
fn assemble_imm(
&mut self,
alloc: &'arena Bump,
_: &DeclMap<'arena>,
) -> Result<hhbc::PropName<'arena>> {
Ok(hhbc::PropName::new(
assemble::assemble_unescaped_unquoted_str(alloc, self)?,
))
}
}
impl<'arena> AssembleImm<'arena, Slice<'arena, hhbc::Label>> for Lexer<'_> {
fn assemble_imm(
&mut self,
alloc: &'arena Bump,
_: &DeclMap<'arena>,
) -> Result<Slice<'arena, hhbc::Label>> {
let mut labels = Vec::new();
self.expect(Token::is_lt)?;
while !self.peek_is(Token::is_gt) {
labels.push(assemble::assemble_label(self)?)
}
self.expect(Token::is_gt)?;
Ok(Slice::from_vec(alloc, labels))
}
}
impl<'arena> AssembleImm<'arena, Slice<'arena, Str<'arena>>> for Lexer<'_> {
fn assemble_imm(
&mut self,
alloc: &'arena Bump,
_: &DeclMap<'arena>,
) -> Result<Slice<'arena, Str<'arena>>> {
self.expect(Token::is_lt)?;
let mut d = Vec::new();
while !self.peek_is(Token::is_gt) {
d.push(assemble::assemble_unescaped_unquoted_str(alloc, self)?);
}
self.expect(Token::is_gt)?;
Ok(Slice::from_vec(alloc, d))
}
}
impl AssembleImm<'_, hhbc::StackIndex> for Lexer<'_> {
fn assemble_imm(&mut self, _: &'_ Bump, _: &DeclMap<'_>) -> Result<hhbc::StackIndex> {
// StackIndex : u32
self.expect_and_get_number()
}
}
impl<'arena> AssembleImm<'arena, Str<'arena>> for Lexer<'_> {
fn assemble_imm(&mut self, alloc: &'arena Bump, _: &DeclMap<'arena>) -> Result<Str<'arena>> {
assemble::assemble_unescaped_unquoted_str(alloc, self)
}
}
impl AssembleImm<'_, hhbc::SwitchKind> for Lexer<'_> {
fn assemble_imm(&mut self, _: &'_ Bump, _: &DeclMap<'_>) -> Result<hhbc::SwitchKind> {
let tok = self.expect_token()?;
match tok.into_identifier()? {
b"Unbounded" => Ok(hhbc::SwitchKind::Unbounded),
b"Bounded" => Ok(hhbc::SwitchKind::Bounded),
_ => Err(tok.error("Unknown switch kind")),
}
}
} |
Rust | hhvm/hphp/hack/src/hackc/assemble/assemble_opcode_macro.rs | // Copyright (c) Meta Platforms, Inc. and affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use hhbc_gen::OpcodeData;
use itertools::Itertools;
use proc_macro2::Ident;
use proc_macro2::Span;
use proc_macro2::TokenStream;
use quote::quote;
use syn::LitByteStr;
use syn::Result;
#[proc_macro_attribute]
pub fn assemble_opcode(
_attrs: proc_macro::TokenStream,
input: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
match assemble_opcode_impl(input.into(), hhbc_gen::opcode_data()) {
Ok(res) => res.into(),
Err(err) => err.into_compile_error().into(),
}
}
fn assemble_opcode_impl(_input: TokenStream, opcodes: &[OpcodeData]) -> Result<TokenStream> {
let name = quote!(assemble_opcode);
let mut body = Vec::new();
for opcode in opcodes {
let variant_name = Ident::new(opcode.name, Span::call_site());
let name = opcode.name.to_string();
let name_bstr = LitByteStr::new(name.as_bytes(), Span::call_site());
// SSwitch and MemoGetEage both have unusual semantics and have to be
// parsed specially in the outer code block.
if name == "SSwitch" || name == "MemoGetEager" {
body.push(quote!(#name_bstr => { unreachable!(); }));
continue;
}
let imms = if opcode.immediates.is_empty() {
quote!()
} else {
let imms = opcode
.immediates
.iter()
.map(|_| quote!(token_iter.assemble_imm(alloc, decl_map)?))
.collect_vec();
quote!((#(#imms),*))
};
body.push(quote!(
#name_bstr => {
token_iter.expect_str(Token::is_identifier, #name)?;
Ok(hhbc::Instruct::Opcode(hhbc::Opcode::#variant_name #imms))
}
));
}
Ok(quote!(
fn #name<'arena>(
alloc: &'arena Bump,
tok: &'_ [u8],
token_iter: &mut Lexer<'_>,
decl_map: &HashMap<Str<'arena>, u32>,
) -> Result<hhbc::Instruct<'arena>>{
match tok {
#(#body)*
t => bail!("unknown opcode: {:?}", t),
}
}
))
}
/// Used like:
///
/// assemble_enum!(lexer, [E::A, E::B, E::C])
///
/// turns into a handler for A, B, and C that looks something like:
///
/// impl AssembleImm<'_, $ret_ty> for Lexer<'_> {
/// fn assemble_imm(&mut self, _alloc: &'_ Bump, _decl_map: &DeclMap<'_>) -> Result<$ret_ty> {
/// use $ret_ty;
/// match self.expect(Token::into_identifier)? {
/// b"A" => E::A,
/// b"B" => E::B,
/// b"C" => E::C,
/// _ => bail!(...)
/// }
/// }
/// }
///
/// This needs to be a proc-macro so it can manipulate the names (turning 'E::A'
/// into 'b"A"').
#[proc_macro]
pub fn assemble_imm_for_enum(tokens: proc_macro::TokenStream) -> proc_macro::TokenStream {
use quote::ToTokens;
use syn::Path;
use syn::Token;
use syn::Type;
#[derive(Debug)]
struct Input {
ret_ty: Type,
variants: Vec<Path>,
}
impl syn::parse::Parse for Input {
fn parse(input: syn::parse::ParseStream<'_>) -> Result<Self> {
let ret_ty = input.parse()?;
input.parse::<Token![,]>()?;
let variants_stream;
syn::bracketed!(variants_stream in input);
input.parse::<syn::parse::Nothing>()?;
let variants = variants_stream
.parse_terminated::<Path, Token![,]>(Path::parse)?
.into_iter()
.collect_vec();
Ok(Input { ret_ty, variants })
}
}
let Input { ret_ty, variants } = syn::parse_macro_input!(tokens as Input);
let mut expected = variants.first().unwrap().clone();
if expected.segments.len() > 1 {
expected.segments.pop();
// Make sure to remove any trailing punctuation.
let t = expected.segments.pop().unwrap().into_value();
expected.segments.push(t);
}
let body = variants
.into_iter()
.map(|variant| {
let ident = &variant.segments.last().unwrap().ident;
let ident_str = LitByteStr::new(ident.to_string().as_bytes(), Span::call_site());
quote!(#ident_str => #variant)
})
.collect_vec();
let msg = format!(
"Expected a '{}', got {{:?}} on line {{}}",
expected.into_token_stream()
);
// Unfortunately since most of these 'enums' aren't real Rust enums we can't
// do anything to ensure that this is exhaustive.
let output = quote! {
impl AssembleImm<'_, #ret_ty> for Lexer<'_> {
fn assemble_imm(&mut self, _: &'_ Bump, _: &DeclMap<'_>) -> Result<#ret_ty> {
use #ret_ty;
let tok = self.expect_token()?;
let id = tok.into_identifier()?;
Ok(match id {
#(#body),*,
f => return Err(tok.error(#msg)),
})
}
}
};
output.into()
} |
Rust | hhvm/hphp/hack/src/hackc/assemble/lexer.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::str::FromStr;
use anyhow::anyhow;
use anyhow::bail;
use anyhow::ensure;
use anyhow::Result;
use crate::token::Line;
use crate::token::Token;
// We initially planned on using Logos, a crate for tokenizing really fast.
// We chose not to use Logos because it doesn't support all regexes -- for instance, it can't
// tokenize based on the regex "\"\"\".*\"\"\"". Here's the git issue:
// https://github.com/maciejhirsz/logos/issues/246
#[derive(Clone)]
pub(crate) struct Lexer<'a> {
line: Line,
pending: Option<Token<'a>>, // Cached next (non-newline)
source: &'a [u8],
}
impl<'a> Iterator for Lexer<'a> {
type Item = Token<'a>;
/// Returns the next token, never returning a newline and instead advancing the lexer past them.
fn next(&mut self) -> Option<Self::Item> {
self.fill(); // If `pending` already has a token this does nothing
self.pending.take()
}
}
impl<'a> Lexer<'a> {
pub(crate) fn error(&mut self, err: impl std::fmt::Display) -> anyhow::Error {
if let Some(tok) = self.peek() {
tok.error(err)
} else {
anyhow!("Error [end of file]: {err}")
}
}
/// If `pending` is none, fills with the next non-newline token, or None of one does not exist.
fn fill(&mut self) {
if self.pending.is_none() {
loop {
(self.pending, self.source) = parse_token(self.source, self.line);
match self.pending {
None => {
// Either a whitespace or EOF
if self.source.is_empty() {
return;
}
}
Some(Token::Newline(_)) => {
self.line.0 += 1;
}
Some(_) => break,
}
}
}
}
pub(crate) fn is_empty(&mut self) -> bool {
self.fill();
self.pending.is_none()
}
fn find_next_newline(&self) -> Option<usize> {
// Find the next newline - but ignore it if it's in quotes. We handle
// triple quotes as a trick - '"""' is no different than '""' followed
// by '"'.
let mut in_quotes = false;
let mut escape = false;
self.source.iter().copied().position(|ch| {
if escape {
escape = false;
} else if !in_quotes && ch == b'\n' {
return true;
} else if ch == b'\"' {
in_quotes = !in_quotes;
} else if ch == b'\\' {
escape = true;
}
false
})
}
/// Advances the lexer past its first non-leading newline, returning a mini-lexer of the tokens up until that newline.
pub(crate) fn split_at_newline(&mut self) -> Option<Lexer<'a>> {
self.fill();
if let Some(pending) = self.pending.take() {
let idx = self.find_next_newline().unwrap_or(self.source.len());
let source;
(source, self.source) = self.source.split_at(idx);
Some(Lexer {
line: self.line,
pending: Some(pending),
source,
})
} else {
None
}
}
/// Similarly to `Lexer::next`, will not return a peek to a newline. Instead
/// this `peek` returns a view to the first token that's not a newline, and modifies the lexer in that it strips
/// it of leading newlines.
pub(crate) fn peek(&mut self) -> Option<&Token<'a>> {
self.fill();
self.pending.as_ref()
}
/// Peeks at the next token past the current one. Unlike peek() won't skip
/// newlines. Doesn't cache the token so this call can be (relatively)
/// expensive if used often.
pub(crate) fn peek1(&mut self) -> Option<Token<'a>> {
self.fill();
let (peek1, _) = parse_token(self.source, self.line);
peek1
}
pub(crate) fn expect_token(&mut self) -> Result<Token<'a>> {
self.next()
.ok_or_else(|| anyhow!("End of token stream sooner than expected"))
}
/// Returns f() applied to the next token without consuming the next token.
pub(crate) fn peek_is<F>(&mut self, f: F) -> bool
where
F: Fn(&Token<'a>) -> bool,
{
self.peek().map_or(false, f)
}
/// Applies f() to the next token and then compares the result with the
/// passed-in string.
pub(crate) fn peek_is_str<F>(&mut self, f: F, s: &str) -> bool
where
F: Fn(&Token<'a>) -> bool,
{
self.peek_is(|t| f(t) && t.as_bytes() == s.as_bytes())
}
/// Applies f() to the next token and consumes it if the predicate passes.
/// Returns Some(token) if the predicate passed.
pub(crate) fn next_if<F>(&mut self, f: F) -> Option<Token<'a>>
where
F: Fn(&Token<'a>) -> bool,
{
let tr = self.peek_is(f);
if tr { self.next() } else { None }
}
/// Applies f() to the next token and consumes it if the predicate
/// passes. Returns true if the predicate passed.
pub(crate) fn next_is<F>(&mut self, f: F) -> bool
where
F: Fn(&Token<'a>) -> bool,
{
self.next_if(f).is_some()
}
/// Applies f() to the next token and consumes it if the predicate passes
/// and matches the given string.
pub(crate) fn next_is_str<F>(&mut self, f: F, s: &str) -> bool
where
F: Fn(&Token<'a>) -> bool,
{
let tr = self.peek_is_str(f, s);
if tr {
self.next();
}
tr
}
/// Applies f() to the next token and consumes it if the predicate
/// passes. Returns Ok(Token) if the predicate passed or Err() if the
/// predicate failed.
pub(crate) fn expect<F>(&mut self, f: F) -> Result<Token<'a>>
where
F: Fn(&Token<'a>) -> bool,
{
let tok = self.expect_token()?;
if f(&tok) {
Ok(tok)
} else {
Err(tok.error("Unexpected token"))
}
}
/// Applies f() to the next token and returns the result.
/// expected token (expected token specified by f)
pub(crate) fn expect_with<T, F>(&mut self, f: F) -> Result<T>
where
F: FnOnce(Token<'a>) -> Result<T>,
{
f(self.expect_token()?)
}
/// Checks both the f() predicate and that the str matches.
pub(crate) fn expect_str<F>(&mut self, f: F, s: &str) -> Result<Token<'a>>
where
F: FnOnce(&Token<'a>) -> bool,
{
let tok = self.expect_token()?;
if f(&tok) && tok.as_bytes() == s.as_bytes() {
Ok(tok)
} else {
Err(tok.error(format!("Expected {s:?} got {:?}", tok.as_bytes())))
}
}
/// Similar to `expect` but instead of returning a Result that usually contains a slice of u8,
/// applies f to the `from_utf8 str` of the top token, bailing if the top token is not a number.
pub(crate) fn expect_and_get_number<T: FromStr>(&mut self) -> Result<T> {
let num = if self.peek_is(Token::is_dash) {
self.expect_with(Token::into_dash)? // -INF
} else if self.peek_is(Token::is_identifier) {
self.expect_with(Token::into_identifier)? // NAN, INF, etc will parse as float constants
} else {
self.expect_with(Token::into_number)?
};
// If num is a dash we expect an identifier to follow
if num == b"-" {
let mut num = num.to_vec();
num.extend_from_slice(self.expect_with(Token::into_identifier)?);
FromStr::from_str(std::str::from_utf8(&num)?).map_err(|_| {
anyhow!("Number-looking token in tokenizer that cannot be parsed into number")
})
} else {
FromStr::from_str(std::str::from_utf8(num)?).map_err(|_| {
anyhow!("Number-looking token in tokenizer that cannot be parsed into number")
}) // This std::str::from_utf8 will never bail; if it should bail, the above `expect` bails first.
}
}
/// A var can be written in HHAS as $abc or "$abc". Only valid if a $ preceeds
pub(crate) fn expect_var(&mut self) -> Result<Vec<u8>> {
if self.peek_is(Token::is_str_literal) {
let s = self.expect_with(Token::into_str_literal)?;
if s.starts_with(b"\"$") {
// Remove the "" b/c that's not part of the var name
// also unescape ("$\340\260" etc is literal bytes)
let s = escaper::unquote_slice(s);
let s = escaper::unescape_literal_bytes_into_vec_bytes(s)?;
Ok(s)
} else {
bail!("Var does not start with $: {:?}", s)
}
} else {
Ok(self.expect_with(Token::into_variable)?.to_vec())
}
}
/// Bails if lexer is not empty, message contains the next token
pub(crate) fn expect_end(&mut self) -> Result<()> {
ensure!(
self.is_empty(),
"Expected end of token stream, see: {}",
self.next().unwrap()
);
Ok(())
}
pub(crate) fn from_slice(source: &'a [u8], start_line: Line) -> Self {
Lexer {
line: start_line,
source,
pending: None,
}
}
pub(crate) fn parse_list<T, F>(&mut self, mut callback: F) -> Result<Vec<T>>
where
F: FnMut(&mut Self) -> Result<Option<T>>,
{
// a b c
let mut result = Vec::new();
while let Some(t) = callback(self)? {
result.push(t);
}
Ok(result)
}
pub(crate) fn parse_comma_list<T, F>(
&mut self,
expect_comma: bool,
mut callback: F,
) -> Result<Vec<T>>
where
F: FnMut(&mut Self) -> Result<T>,
{
// a, b, c
let mut result = Vec::new();
if !expect_comma {
result.push(callback(self)?);
}
while self.next_is(Token::is_comma) {
result.push(callback(self)?);
}
Ok(result)
}
}
fn is_identifier_lead(ch: u8) -> bool {
ch.is_ascii_alphabetic() || (ch >= 0x80) || (ch == b'_') || (ch == b'/')
}
fn is_identifier_tail(ch: u8) -> bool {
// r"(?-u)[_/a-zA-Z\x80-\xff]([_/\\a-zA-Z0-9\x80-\xff\.\$#\-]|::)*"
//
// NOTE: identifiers can include "::" but this won't match that because it's
// a multi-byte sequence.
ch.is_ascii_alphanumeric()
|| (ch >= 0x80)
|| (ch == b'.')
|| (ch == b'$')
|| (ch == b'#')
|| (ch == b'-')
|| (ch == b'_')
|| (ch == b'/')
|| (ch == b'\\')
}
fn gather_identifier(source: &[u8]) -> (&[u8], &[u8]) {
// This can't be easy because ':' isn't part of an identifier, but '::'
// is...
let mut len = 1;
loop {
len += source[len..]
.iter()
.copied()
.take_while(|&c| is_identifier_tail(c))
.count();
if !source[len..].starts_with(b"::") {
break;
}
len += 2;
}
source.split_at(len)
}
fn is_number_lead(ch: u8) -> bool {
ch.is_ascii_digit()
}
fn is_number_tail(ch: u8) -> bool {
// r"[-+]?[0-9]+\.?[0-9]*([eE][-+]?[0-9]+\.?[0-9]*)?"
ch.is_ascii_digit() || (ch == b'.')
}
fn gather_number(source: &[u8]) -> (&[u8], &[u8]) {
// The plus location (only after 'e') makes this tricky.
let mut last_e = false;
let len = source[1..]
.iter()
.copied()
.take_while(|&c| {
if is_number_tail(c) {
last_e = false;
} else if c == b'e' || c == b'E' {
last_e = true;
} else if (c == b'+' || c == b'-') && last_e {
last_e = false;
} else {
return false;
}
true
})
.count();
source.split_at(1 + len)
}
fn is_global_tail(ch: u8) -> bool {
// r"(?-u)[\.@][_a-z/A-Z\x80-\xff][_/a-zA-Z/0-9\x80-\xff\-\.]*"
ch.is_ascii_alphanumeric() || (ch >= 0x80) || (ch == b'.') || (ch == b'-') || (ch == b'_')
}
fn is_var_tail(ch: u8) -> bool {
// r"(?-u)\$[_a-zA-Z0-9$\x80-\xff][_/a-zA-Z0-9$\x80-\xff]*"
ch.is_ascii_alphanumeric() || (ch >= 0x80) || (ch == b'$') || (ch == b'_')
}
fn is_decl_tail(ch: u8) -> bool {
// r"(?-u)[\.@][_a-z/A-Z\x80-\xff][_/a-zA-Z/0-9\x80-\xff\-\.]*", // Decl, global. (?-u) turns off utf8 check
ch.is_ascii_alphanumeric() || (ch >= 0x80) || (ch == b'-') || (ch == b'.') || (ch == b'_')
}
fn is_non_newline_whitespace(ch: u8) -> bool {
ch == b' ' || ch == b'\t' || ch == b'\r'
}
fn gather_tail<F>(source: &[u8], f: F) -> (&[u8], &[u8])
where
F: Fn(u8) -> bool,
{
let len = source[1..].iter().copied().take_while(|c| f(*c)).count();
source.split_at(1 + len)
}
fn gather_quoted(source: &[u8], count: usize) -> (&[u8], &[u8]) {
let mut quotes = 0;
let mut escaped = false;
let len = source[count..]
.iter()
.copied()
.take_while(|&c| {
if quotes == count {
return false;
} else if c == b'"' && !escaped {
quotes += 1;
} else if c == b'\\' && !escaped {
escaped = true;
quotes = 0;
} else {
escaped = false;
quotes = 0;
}
true
})
.count();
source.split_at(count + len)
}
fn parse_token(mut source: &[u8], line: Line) -> (Option<Token<'_>>, &[u8]) {
let tok = if let Some(lead) = source.first() {
match *lead {
ch if is_identifier_lead(ch) => {
// Identifier
let tok;
(tok, source) = gather_identifier(source);
Some(Token::Identifier(tok, line))
}
ch if is_number_lead(ch) => {
// Number
let tok;
(tok, source) = gather_number(source);
Some(Token::Number(tok, line))
}
ch if is_non_newline_whitespace(ch) => {
(_, source) = gather_tail(source, is_non_newline_whitespace);
None
}
b'#' => {
// Don't consume the newline.
let len = source[1..]
.iter()
.copied()
.take_while(|&c| c != b'\n')
.count();
(_, source) = source.split_at(1 + len);
None
}
b'\n' => {
(_, source) = source.split_at(1);
Some(Token::Newline(line))
}
b'@' => {
if source.len() > 1 {
// Global
let tok;
(tok, source) = gather_tail(source, is_global_tail);
Some(Token::Global(tok, line))
} else {
// Error
let tok = std::mem::take(&mut source);
Some(Token::Error(tok, line))
}
}
b'$' => {
if source.len() > 1 {
// Var
let tok;
(tok, source) = gather_tail(source, is_var_tail);
Some(Token::Variable(tok, line))
} else {
// Error
let tok = std::mem::take(&mut source);
Some(Token::Error(tok, line))
}
}
b'"' => {
if source.starts_with(b"\"\"\"") {
// Triple string literal
let tok;
(tok, source) = gather_quoted(source, 3);
Some(Token::TripleStrLiteral(tok, line))
} else {
// Single string literal
let tok;
(tok, source) = gather_quoted(source, 1);
Some(Token::StrLiteral(tok, line))
}
}
b'.' => {
if source.starts_with(b"...") {
// Variadic
(_, source) = source.split_at(3);
Some(Token::Variadic(line))
} else if source.len() > 1 {
// Decl
let tok;
(tok, source) = gather_tail(source, is_decl_tail);
Some(Token::Decl(tok, line))
} else {
// Error
let tok = std::mem::take(&mut source);
Some(Token::Error(tok, line))
}
}
b'-' => {
if source.get(1).copied().map_or(false, is_number_lead) {
// Negative number
let tok;
(tok, source) = gather_number(source);
Some(Token::Number(tok, line))
} else {
// Dash
(_, source) = source.split_at(1);
Some(Token::Dash(line))
}
}
b'+' => {
// Positive number
let tok;
(tok, source) = gather_number(source);
Some(Token::Number(tok, line))
}
b';' => {
(_, source) = source.split_at(1);
Some(Token::Semicolon(line))
}
b'{' => {
(_, source) = source.split_at(1);
Some(Token::OpenCurly(line))
}
b'[' => {
(_, source) = source.split_at(1);
Some(Token::OpenBracket(line))
}
b'(' => {
(_, source) = source.split_at(1);
Some(Token::OpenParen(line))
}
b')' => {
(_, source) = source.split_at(1);
Some(Token::CloseParen(line))
}
b']' => {
(_, source) = source.split_at(1);
Some(Token::CloseBracket(line))
}
b'}' => {
(_, source) = source.split_at(1);
Some(Token::CloseCurly(line))
}
b',' => {
(_, source) = source.split_at(1);
Some(Token::Comma(line))
}
b'<' => {
(_, source) = source.split_at(1);
Some(Token::Lt(line))
}
b'>' => {
(_, source) = source.split_at(1);
Some(Token::Gt(line))
}
b'=' => {
(_, source) = source.split_at(1);
Some(Token::Equal(line))
}
b':' => {
(_, source) = source.split_at(1);
Some(Token::Colon(line))
}
_ => todo!("CH: {lead:?} ({})", *lead as char),
}
} else {
None
};
(tok, source)
}
#[cfg(test)]
mod test {
use bumpalo::Bump;
use super::*;
use crate::assemble;
#[test]
fn str_into_test() -> Result<()> {
// Want to test that only tokens surrounded by "" are str_literals
// Want to confirm the assumption that after any token_iter.expect_with(Token::into_str_literal) call, you can safely remove the first and last element in slice
let s = br#"abc "abc" """abc""""#;
let mut lex = Lexer::from_slice(s, Line(1));
assert!(lex.next_is(Token::is_identifier));
let sl = lex.expect_with(Token::into_str_literal)?;
assert!(sl[0] == b'"' && sl[sl.len() - 1] == b'"');
let tsl = lex.expect_with(Token::into_triple_str_literal)?;
assert!(
tsl[0..3] == [b'"', b'"', b'"'] && tsl[tsl.len() - 3..tsl.len()] == [b'"', b'"', b'"']
);
Ok(())
}
#[test]
fn just_nl_is_empty() {
let s = b"\n \n \n";
let mut lex = Lexer::from_slice(s, Line(1));
assert!(lex.split_at_newline().is_none());
assert!(lex.is_empty());
}
#[test]
fn splits_mult_newlines_go_away() {
// Point of this test: want to make sure that 3 mini-lexers are spawned (multiple new lines don't do anything)
let s = b"\n \n a \n \n \n b \n \n c \n";
let mut lex = Lexer::from_slice(s, Line(1));
let mut a = lex.split_at_newline().unwrap();
let mut b = lex.split_at_newline().unwrap();
let mut c = lex.split_at_newline().unwrap();
assert_eq!(lex.next(), None);
assert_eq!(a.next().unwrap().into_identifier().unwrap(), b"a");
assert_eq!(a.next(), None);
assert_eq!(b.next().unwrap().into_identifier().unwrap(), b"b");
assert_eq!(b.next(), None);
assert_eq!(c.next().unwrap().into_identifier().unwrap(), b"c");
assert_eq!(c.next(), None);
}
#[test]
fn no_trailing_newlines() {
let s = b"a \n \n \n";
let mut lex = Lexer::from_slice(s, Line(1));
assert!(lex.next().is_some());
assert!(lex.is_empty());
}
#[test]
#[allow(unused)]
fn splitting_multiple_lines() {
let s = b".try { \n .srcloc 3:7, 3:22 \n String \"I'm i\\\"n the try\n\" \n Print \n PopC \n } .catch { \n Dup \n L1: \n Throw \n }";
let mut lex = Lexer::from_slice(s, Line(1));
let mut sub = lex.split_at_newline().unwrap();
assert_eq!(sub.next().unwrap().into_decl().unwrap(), b".try");
assert!(sub.next().unwrap().is_open_curly());
assert_eq!(sub.next(), None);
let mut sub = lex.split_at_newline().unwrap();
assert_eq!(sub.next().unwrap().into_decl().unwrap(), b".srcloc");
assert_eq!(sub.next().unwrap().into_number().unwrap(), b"3");
assert!(sub.next().unwrap().is_colon());
assert_eq!(sub.next().unwrap().into_number().unwrap(), b"7");
assert!(sub.next().unwrap().is_comma());
assert_eq!(sub.next().unwrap().into_number().unwrap(), b"3");
assert!(sub.next().unwrap().is_colon());
assert_eq!(sub.next().unwrap().into_number().unwrap(), b"22");
assert_eq!(sub.next(), None);
let mut sub = lex.split_at_newline().unwrap();
assert_eq!(sub.next().unwrap().into_identifier().unwrap(), b"String");
assert_eq!(
sub.next().unwrap().into_str_literal().unwrap(),
b"\"I'm i\\\"n the try\n\""
);
assert_eq!(sub.next(), None);
let mut sub = lex.split_at_newline().unwrap();
assert_eq!(sub.next().unwrap().into_identifier().unwrap(), b"Print");
assert_eq!(sub.next(), None);
let mut sub = lex.split_at_newline().unwrap();
assert_eq!(sub.next().unwrap().into_identifier().unwrap(), b"PopC");
assert_eq!(sub.next(), None);
let mut sub = lex.split_at_newline().unwrap();
assert!(sub.next().unwrap().is_close_curly());
assert_eq!(sub.next().unwrap().into_decl().unwrap(), b".catch");
assert!(sub.next().unwrap().is_open_curly());
assert_eq!(sub.next(), None);
let mut sub = lex.split_at_newline().unwrap();
assert_eq!(sub.next().unwrap().into_identifier().unwrap(), b"Dup");
assert_eq!(sub.next(), None);
let mut sub = lex.split_at_newline().unwrap();
assert_eq!(sub.next().unwrap().into_identifier().unwrap(), b"L1");
assert!(sub.next().unwrap().is_colon());
assert_eq!(sub.next(), None);
let mut sub = lex.split_at_newline().unwrap();
assert_eq!(sub.next().unwrap().into_identifier().unwrap(), b"Throw");
assert_eq!(sub.next(), None);
let mut sub = lex.split_at_newline().unwrap();
assert!(sub.next().unwrap().is_close_curly());
assert_eq!(sub.next(), None);
assert_eq!(lex.next(), None);
}
#[test]
fn peek_next_on_newlines() {
let s = b"\n\na\n\n";
let mut lex = Lexer::from_slice(s, Line(1));
assert!(lex.peek().is_some());
assert!(lex.next().is_some());
assert!(lex.split_at_newline().is_none()); // Have consumed the a here -- "\n\n" was left and that's been consumed.
}
#[test]
#[should_panic]
fn no_top_level_shouldnt_parse() {
// Is there a better way, maybe to verify the string in the bail?
let s = b".srloc 3:7,3:22";
let alloc = Bump::default();
assert!(matches!(assemble::assemble_from_bytes(&alloc, s), Ok(_)))
}
#[test]
#[should_panic]
fn no_fpath_semicolon_shouldnt_parse() {
let s = br#".filepath "aaaa""#;
let alloc = Bump::default();
assert!(matches!(assemble::assemble_from_bytes(&alloc, s), Ok(_)))
}
#[test]
#[should_panic]
fn fpath_wo_file_shouldnt_parse() {
let s = br#".filepath aaa"#;
let alloc = Bump::default();
assert!(matches!(assemble::assemble_from_bytes(&alloc, s), Ok(_)))
}
#[test]
fn difficult_strings() {
let s = br#""\"0\""
"12345\\:2\\"
"class_meth() expects a literal class name or ::class constant, followed by a constant string that refers to a static method on that class";
"#;
let mut l: Lexer<'_> = Lexer::from_slice(s, Line(1));
// Expecting 3 string tokens
let _st1 = l.next().unwrap();
let _by1 = str::as_bytes(r#""\"0\"""#);
assert!(matches!(_st1, Token::StrLiteral(_by1, _)));
let _st2 = l.next().unwrap();
let _by2 = str::as_bytes(r#""12345\\:2\\""#);
assert!(matches!(_st1, Token::StrLiteral(_by2, _)));
let _st3 = l.next().unwrap();
let _by3 = str::as_bytes(
r#""class_meth() expects a literal class name or ::class constant, followed by a constant string that refers to a static method on that class""#,
);
assert!(matches!(_st1, Token::StrLiteral(_by3, _)));
}
#[test]
fn odd_unicode_test() {
let s: &[u8] = b".\xA9\xEF\xB8\x8E $0\xC5\xA3\xB1\xC3 \xE2\x98\xBA\xE2\x98\xBA\xE2\x98\xBA @\xE2\x99\xA1\xE2\x99\xA4$";
let mut l: Lexer<'_> = Lexer::from_slice(s, Line(1));
// We are expecting an decl, a var, an identifier a global, and an error on the last empty variable
let decl = l.next().unwrap();
assert!(matches!(decl, Token::Decl(..)));
let var = l.next().unwrap();
assert!(matches!(var, Token::Variable(..)));
let iden = l.next().unwrap();
assert!(matches!(iden, Token::Identifier(..)));
let glob = l.next().unwrap();
assert!(matches!(glob, Token::Global(..)));
let err = l.next().unwrap();
assert!(matches!(err, Token::Error(..)))
}
#[test]
fn every_token_test() {
let s = br#"@_global $0Var """tripleStrLiteral:)""" #hashtagComment
.Decl "str!Literal" ...
;-{[( )]} =98 -98 +101. 43.2 , < > : _/identifier/ /filepath id$di aa:bb aa::bb ."#;
// Expect glob var tsl decl strlit semicolon dash open_curly open_brack open_paren close_paren close_bracket
// close_curly equal number number number number , < > : identifier identifier ERROR on the last .
let mut l: Lexer<'_> = Lexer::from_slice(s, Line(1));
assert_eq!(l.next().unwrap().into_global().unwrap(), b"@_global");
assert_eq!(l.next().unwrap().into_variable().unwrap(), b"$0Var");
assert_eq!(
l.next().unwrap().into_triple_str_literal().unwrap(),
br#""""tripleStrLiteral:)""""#
);
assert_eq!(l.next().unwrap().into_decl().unwrap(), b".Decl");
assert_eq!(
l.next().unwrap().into_str_literal().unwrap(),
br#""str!Literal""#
);
assert!(l.next().unwrap().is_variadic());
assert!(l.next().unwrap().is_semicolon());
assert!(l.next().unwrap().is_dash());
assert!(l.next().unwrap().is_open_curly());
assert!(l.next().unwrap().is_open_bracket());
assert!(l.next().unwrap().is_open_paren());
assert!(l.next().unwrap().is_close_paren());
assert!(l.next().unwrap().is_close_bracket());
assert!(l.next().unwrap().is_close_curly());
assert!(l.next().unwrap().is_equal());
assert_eq!(l.next().unwrap().into_number().unwrap(), b"98");
assert_eq!(l.next().unwrap().into_number().unwrap(), b"-98");
assert_eq!(l.next().unwrap().into_number().unwrap(), b"+101.");
assert_eq!(l.next().unwrap().into_number().unwrap(), b"43.2");
assert!(l.next().unwrap().is_comma());
assert!(l.next().unwrap().is_lt());
assert!(l.next().unwrap().is_gt());
assert!(l.next().unwrap().is_colon());
assert_eq!(
l.next().unwrap().into_identifier().unwrap(),
b"_/identifier/"
);
assert_eq!(l.next().unwrap().into_identifier().unwrap(), b"/filepath");
assert_eq!(l.next().unwrap().into_identifier().unwrap(), b"id$di");
assert_eq!(l.next().unwrap().into_identifier().unwrap(), b"aa");
assert!(l.next().unwrap().is_colon());
assert_eq!(l.next().unwrap().into_identifier().unwrap(), b"bb");
assert_eq!(l.next().unwrap().into_identifier().unwrap(), b"aa::bb");
let err = l.next().unwrap();
assert!(matches!(err, Token::Error(..)), "failed to match {}", err);
}
} |
Rust | hhvm/hphp/hack/src/hackc/assemble/lib.rs | mod assemble;
mod assemble_imm;
mod lexer;
mod token;
pub use assemble::assemble;
pub use assemble::assemble_from_bytes;
pub use assemble::assemble_single_instruction; |
Rust | hhvm/hphp/hack/src/hackc/assemble/parse_macro.rs | // Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
#![feature(box_patterns)]
use proc_macro2::token_stream::IntoIter;
use proc_macro2::Delimiter;
use proc_macro2::Span;
use proc_macro2::TokenStream;
use proc_macro2::TokenTree;
use quote::quote;
use quote::quote_spanned;
use quote::ToTokens;
type TokenIter = std::iter::Peekable<IntoIter>;
/// Macro for helping parsing tokens.
///
/// General use:
/// parse!(tokenizer, pat...)
///
/// (Pattern syntax very loosely based on Lalrpop)
///
/// Basic Patterns:
/// "token" - matches tokens (like "(", "+", ",") or identiifers.
/// global - matches any global (@identifier).
/// id - matches any identifier OR string (see Token::is_any_identifier).
/// local - matches any local (%identifier).
/// num - matches any number.
/// string - matches any quoted string.
/// token - matches any token.
/// triple_string - matches any triple-quoted string.
/// numeric - result of Lexer::expect_and_get_number().
/// @<var> - Fills in 'var' with the location of the next token.
///
/// Complex Patterns:
/// pat0 pat1... - matches 'pat0' followed by 'pat1' (repeatable).
/// <e:pat> - matches 'pat' and binds the result to the new variable 'e'.
/// <mut e:pat> - matches 'pat' and binds the result to the new mut variable 'e'.
/// f - calls f(tokenizer) to parse a value.
/// f(a, b) - calls f(tokenizer, a, b) to parse a value.
/// basic_pat? - match the pattern zero or one times. The only allowable
/// patterns are the basic patterns listed above.
/// pat,+ - expects one or more comma separated list of identifiers.
/// pat,* - expects zero or more comma separated list of
/// identifiers. Note that due to macro limitations the next
/// pattern MUST be ')', '}' or ']'.
/// { xyzzy } - inject rust code xyzzy into the matcher at this point.
/// [ tok0: pat... ; tok1: pat... ; tok2: pat... ]
/// - based on the next token choose a pattern to execute. NOTE:
/// The matching token is NOT consumed!
/// [ tok0: pat... ; tok1: pat... ; else: pat... ]
/// - based on the next token choose a pattern to execute. If no
/// pattern matches then 'else' clause is executed.
///
/// See bottom of this file for tests which show examples of what code various
/// patterns translate into.
///
#[cfg(not(test))]
#[proc_macro]
#[proc_macro_error::proc_macro_error]
pub fn parse(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
use proc_macro_error::abort;
let input = TokenStream::from(input);
let res = match parse_macro(input) {
Ok(res) => res,
Err(err) => abort!(err.0, err.1),
};
res.into()
}
const DEBUG: bool = false;
#[derive(Debug)]
struct ParseError(Span, String);
type Result<T> = std::result::Result<T, ParseError>;
fn parse_macro(input: TokenStream) -> Result<TokenStream> {
if DEBUG {
eprintln!("INPUT: {}", input);
}
let mut it = input.into_iter().peekable();
let it = &mut it;
// Gather the tokenizer variable
let tokenizer = it.expect_ident()?;
it.expect_punct(',')?;
let tree = Ast::parse(it)?;
if let Some(t) = it.next() {
return Err(t.error("Unexpected input"));
}
let mut var_decl = TokenStream::new();
State::collect_var_decl(&tree, &mut var_decl);
let state = State { tokenizer };
let body = state.emit_ast(tree, Context::None);
let result = quote!(
#var_decl
#body
);
if DEBUG {
eprintln!("RESULT: {:?}\n{}", result, result);
}
Ok(result)
}
#[derive(Debug)]
enum Predicate {
Any,
AnyIdentifier,
// .0 is the identifier we're matching. .1 is only used for error messages
// from select.
Identifier(TokenStream, String),
// .0 is the decl we're matching. .1 is only used for error messages
// from select.
Decl(TokenStream, String),
// .0 is the TokenKind we're matching. .1 is only used for error messages
// from select.
Kind(TokenStream, String),
Numeric,
}
impl Predicate {
fn to_stream(&self, tokenizer: &TokenTree, context: Context) -> TokenStream {
match (context, self) {
(Context::None, Predicate::Any) => {
quote!(#tokenizer.expect_token()?)
}
(Context::None, Predicate::AnyIdentifier) => {
quote!(#tokenizer.expect(Token::is_identifier)?)
}
(Context::None, Predicate::Identifier(id, _)) => {
quote!(#tokenizer.expect_str(Token::is_identifier, #id)?)
}
(Context::None, Predicate::Decl(id, _)) => {
quote!(#tokenizer.expect_str(Token::is_decl, #id)?)
}
(Context::None, Predicate::Kind(kind, _)) => {
quote!(#tokenizer.expect(#kind)?)
}
(Context::None, Predicate::Numeric) => {
quote!(#tokenizer.expect_and_get_number()?)
}
(Context::Optional, Predicate::Any) => {
quote!(#tokenizer.peek())
}
(Context::Optional, Predicate::AnyIdentifier) => {
quote!(#tokenizer.next_if(Token::is_identifier))
}
(Context::Optional, Predicate::Identifier(id, _)) => {
quote!(#tokenizer.next_is_str(Token::is_identifier, #id))
}
(Context::Optional, Predicate::Decl(id, _)) => {
quote!(#tokenizer.next_is_str(Token::is_decl, #id))
}
(Context::Optional, Predicate::Kind(kind, _)) => {
quote!(#tokenizer.next_is(#kind))
}
(Context::Optional, Predicate::Numeric) => {
todo!();
}
(Context::Test, Predicate::Any) => {
quote!(#tokenizer.peek().is_some())
}
(Context::Test, Predicate::AnyIdentifier) => {
quote!(#tokenizer.peek_is(Token::is_identifier))
}
(Context::Test, Predicate::Identifier(id, _)) => {
quote!(#tokenizer.peek_is_str(Token::is_identifier, #id))
}
(Context::Test, Predicate::Decl(id, _)) => {
quote!(#tokenizer.peek_is_str(Token::is_decl, #id))
}
(Context::Test, Predicate::Kind(kind, _)) => {
quote!(#tokenizer.peek_is(#kind))
}
(Context::Test, Predicate::Numeric) => {
todo!();
}
}
}
fn what(&self) -> &str {
match self {
Predicate::Any => "any",
Predicate::AnyIdentifier => "id",
Predicate::Numeric => "numeric",
Predicate::Identifier(_, what)
| Predicate::Decl(_, what)
| Predicate::Kind(_, what) => what,
}
}
}
#[derive(Debug)]
struct SelectCase {
predicate: Predicate,
pattern: Ast,
}
#[derive(Debug)]
enum Ast {
Code {
code: TokenStream,
},
CommaSeparated(Box<Ast>),
FnCall {
name: TokenTree,
params: TokenStream,
},
Loc {
name: TokenTree,
},
OneOrMore(Box<Ast>),
Predicate(Predicate),
Select {
cases: Vec<SelectCase>,
else_case: Option<Box<Ast>>,
},
Sequence(Vec<Ast>),
VarBind {
// name_decl is used at the name declaration site (`let #name_decl`) -
// it includes things that the declaration wants (like 'mut').
name_decl: TokenStream,
// name_use is used at the name assignment site (`let #name_use = ...`)
// - it strips things that the assignment doesn't want (like `mut`).
name_use: TokenStream,
value: Box<Ast>,
},
ZeroOrMore(Box<Ast>),
ZeroOrOne(Box<Ast>),
}
impl Ast {
fn is_predicate(&self) -> bool {
matches!(self, Ast::Predicate(_))
}
}
impl Ast {
fn parse(it: &mut TokenIter) -> Result<Ast> {
let mut result = Vec::new();
loop {
let t = it.expect_peek()?;
if t.is_punct('<') {
result.push(Self::parse_var_assign(it)?);
} else if t.is_punct('@') {
result.push(Self::parse_loc(it)?);
} else {
result.push(Self::parse_subpattern(it)?);
};
// Parse up until the end of the stream or the first semicolon (the
// raw semicolon is used to terminate a select case).
if it.peek().map_or(true, |t| t.is_punct(';')) {
break;
}
}
if result.len() == 1 {
Ok(result.swap_remove(0))
} else {
Ok(Ast::Sequence(result))
}
}
fn parse_var_assign(it: &mut TokenIter) -> Result<Ast> {
// <e:pat>
it.expect_punct('<')?;
let mut name_decl = TokenStream::new();
let mut name_use = TokenStream::new();
loop {
let t = it.expect_tt()?;
if t.is_punct(':') {
break;
}
if !t.is_exact_ident("mut") {
t.to_tokens(&mut name_use);
}
t.to_tokens(&mut name_decl);
}
let value = Box::new(Self::parse_subpattern(it)?);
it.expect_punct('>')?;
Ok(Ast::VarBind {
name_decl,
name_use,
value,
})
}
fn parse_loc(it: &mut TokenIter) -> Result<Ast> {
// @loc
it.expect_punct('@')?;
let name = it.expect_tt()?;
Ok(Ast::Loc { name })
}
fn parse_subpattern(it: &mut TokenIter) -> Result<Ast> {
let t = it.expect_peek()?;
let pat = match t {
TokenTree::Literal(_) => {
// "("
Self::parse_literal(it)?
}
TokenTree::Ident(_) => {
// f
// id
Self::parse_ident(it)?
}
TokenTree::Group(group) if group.delimiter() == Delimiter::Brace => {
let code = group.stream();
it.next();
Ast::Code { code }
}
TokenTree::Group(group) if group.delimiter() == Delimiter::Bracket => {
Self::parse_select(it)?
}
_ => {
return Err(t.error(format!("Pattern expected, not '{}' ({:?})", t, t)));
}
};
// check for trailing comma
let pat = if it.peek().map_or(false, |t| t.is_punct(',')) {
it.next();
let count = it.expect_tt()?;
if count.is_punct('+') {
// 1+
Ast::CommaSeparated(Box::new(Ast::OneOrMore(Box::new(pat))))
} else if count.is_punct('*') {
// 0+
Ast::CommaSeparated(Box::new(Ast::ZeroOrMore(Box::new(pat))))
} else {
return Err(count.error("'*' or '+' expected"));
}
} else {
pat
};
// check for trailing +,*,?
let pat = if it.peek().map_or(false, |t| t.is_punct('+')) {
it.next();
Ast::OneOrMore(Box::new(pat))
} else {
pat
};
let pat = if it.peek().map_or(false, |t| t.is_punct('*')) {
it.next();
Ast::ZeroOrMore(Box::new(pat))
} else {
pat
};
let pat = if it.peek().map_or(false, |t| t.is_punct('?')) {
let t = it.next().unwrap();
if !pat.is_predicate() {
return Err(t.error("Error: '?' only works with basic patterns"));
}
Ast::ZeroOrOne(Box::new(pat))
} else {
pat
};
Ok(pat)
}
fn parse_literal(it: &mut TokenIter) -> Result<Ast> {
let literal = it.expect_literal()?;
let expected = literal.literal_string()?;
let what = format!("'{}'", expected);
let ast = match expected.as_str() {
"(" => Ast::Predicate(Predicate::Kind(quote!(Token::is_open_paren), what)),
")" => Ast::Predicate(Predicate::Kind(quote!(Token::is_close_paren), what)),
"," => Ast::Predicate(Predicate::Kind(quote!(Token::is_comma), what)),
":" => Ast::Predicate(Predicate::Kind(quote!(Token::is_colon), what)),
";" => Ast::Predicate(Predicate::Kind(quote!(Token::is_semicolon), what)),
"<" => Ast::Predicate(Predicate::Kind(quote!(Token::is_lt), what)),
"=" => Ast::Predicate(Predicate::Kind(quote!(Token::is_equal), what)),
">" => Ast::Predicate(Predicate::Kind(quote!(Token::is_gt), what)),
"[" => Ast::Predicate(Predicate::Kind(quote!(Token::is_open_bracket), what)),
"]" => Ast::Predicate(Predicate::Kind(quote!(Token::is_close_bracket), what)),
"{" => Ast::Predicate(Predicate::Kind(quote!(Token::is_open_curly), what)),
"}" => Ast::Predicate(Predicate::Kind(quote!(Token::is_close_curly), what)),
// "!line" => Ast::Predicate(Predicate::Kind(quote!(TokenKind::BangLine), what)),
// "!loc" => Ast::Predicate(Predicate::Kind(quote!(TokenKind::BangLoc), what)),
// "&" => Ast::Predicate(Predicate::Kind(quote!(TokenKind::And), what)),
// "+" => Ast::Predicate(Predicate::Kind(quote!(TokenKind::Plus), what)),
// "-" => Ast::Predicate(Predicate::Kind(quote!(TokenKind::Minus), what)),
// "::" => Ast::Predicate(Predicate::Kind(quote!(TokenKind::DoubleColon), what)),
// "=>" => Ast::Predicate(Predicate::Kind(quote!(TokenKind::Arrow), what)),
// "?" => Ast::Predicate(Predicate::Kind(quote!(TokenKind::Hook), what)),
// "_" => Ast::Predicate(Predicate::Identifier(quote!("_"), what)),
// "|" => Ast::Predicate(Predicate::Kind(quote!(TokenKind::Or), what)),
id => {
if id.starts_with('.') {
Ast::Predicate(Predicate::Decl(quote!(#id), what))
} else {
Ast::Predicate(Predicate::Identifier(quote!(#id), what))
}
}
};
Ok(ast)
}
fn parse_ident(it: &mut TokenIter) -> Result<Ast> {
let t = it.expect_ident()?;
let ast = if t.to_string() == "string" {
Ast::Predicate(Predicate::Kind(
quote!(Token::is_str_literal),
"string".into(),
))
} else if t.to_string() == "triple_string" {
Ast::Predicate(Predicate::Kind(
quote!(Token::is_triple_str_literal),
"triple_string".into(),
))
} else if t.to_string() == "num" {
Ast::Predicate(Predicate::Kind(quote!(Token::is_number), "num".into()))
} else if t.to_string() == "numeric" {
Ast::Predicate(Predicate::Numeric)
} else if t.to_string() == "global" {
Ast::Predicate(Predicate::Kind(quote!(TokenKind::Global), "global".into()))
} else if t.to_string() == "local" {
Ast::Predicate(Predicate::Kind(quote!(TokenKind::Local), "local".into()))
} else if t.to_string() == "token" {
Ast::Predicate(Predicate::Any)
} else if t.to_string() == "id" {
Ast::Predicate(Predicate::AnyIdentifier)
} else {
// f
// f(a, b, c)
if it.peek().map_or(false, TokenTree::is_group) {
let group = it.expect_group()?;
let stream = group.group_stream()?;
Ast::FnCall {
name: t,
params: quote!(, #stream),
}
} else {
Ast::FnCall {
name: t,
params: TokenStream::new(),
}
}
};
Ok(ast)
}
fn parse_select(it: &mut TokenIter) -> Result<Ast> {
// [ tok0: pat... ; tok1: pat... ; tok2: pat... ]
let mut it = it.expect_tt()?.group_stream()?.into_iter().peekable();
let it = &mut it;
let mut cases = Vec::new();
let mut else_case = None;
loop {
let predicate = {
let head_span = it.expect_peek()?.span();
let sub = Ast::parse_subpattern(it)?;
match sub {
Ast::Predicate(predicate) => Some(predicate),
Ast::FnCall { name, .. } if name.to_string() == "else" => None,
_ => {
return Err(ParseError(head_span, "Simple predicate expected".into()));
}
}
};
it.expect_punct(':')?;
let pattern = Ast::parse(it)?;
if let Some(predicate) = predicate {
cases.push(SelectCase { predicate, pattern });
} else {
else_case = Some(Box::new(pattern));
}
if let Some(t) = it.next() {
if !t.is_punct(';') {
return Err(t.error("';' expected"));
}
// Allow a trailing ';'
if it.peek().is_none() {
break;
}
} else {
break;
}
if else_case.is_some() {
break;
}
}
it.expect_eos()?;
Ok(Ast::Select { cases, else_case })
}
}
#[derive(Copy, Clone, Eq, PartialEq)]
enum Context {
None,
Optional,
Test,
}
struct State {
tokenizer: TokenTree,
}
impl State {
fn collect_var_decl(ast: &Ast, output: &mut TokenStream) {
match ast {
Ast::Code { .. } | Ast::FnCall { .. } | Ast::Predicate(_) => {}
Ast::CommaSeparated(sub)
| Ast::OneOrMore(sub)
| Ast::ZeroOrMore(sub)
| Ast::ZeroOrOne(sub) => {
Self::collect_var_decl(sub, output);
}
Ast::Select { .. } => {
// Select declares new vars in each case.
}
Ast::Sequence(subs) => {
for sub in subs {
Self::collect_var_decl(sub, output);
}
}
Ast::VarBind { name_decl, .. } => {
output.extend(quote!(
#[allow(clippy::needless_late_init)]
let #name_decl ;
));
}
Ast::Loc { name } => {
output.extend(quote!(
#[allow(clippy::needless_late_init)]
let #name ;
));
}
}
}
fn emit_ast(&self, ast: Ast, context: Context) -> TokenStream {
let tokenizer = &self.tokenizer;
match ast {
Ast::Code { code } => code,
Ast::CommaSeparated(box sub) => match sub {
Ast::ZeroOrMore(box sub) => {
let sub = self.emit_ast(sub, context);
quote!(
if ! #tokenizer.peek_is(Token::is_close) {
#tokenizer.parse_comma_list(false, |#tokenizer| { Ok(#sub) })?
} else {
Vec::new()
}
)
}
Ast::OneOrMore(box sub) => {
let sub = self.emit_ast(sub, context);
quote!( #tokenizer.parse_comma_list(false, |#tokenizer| { Ok(#sub) })? )
}
_ => unreachable!(),
},
Ast::FnCall { name, params } => {
let span = name.span();
let tokenizer = tokenizer.with_span(name.span());
quote_spanned!(span=> #name(#tokenizer #params)?)
}
Ast::Loc { name } => {
quote!(#name = #tokenizer.peek_loc())
}
Ast::OneOrMore(_) => {
todo!("OneOrMore");
}
Ast::Predicate(pred) => pred.to_stream(&self.tokenizer, context),
Ast::Select { cases, else_case } => {
// if tokenizer.peek_token(predicate).is_some() {
// ... pattern ...
// else if tokenizer.peek_token(predicate).is_some() {
// ... pattern ...
// else {
// complain about everything
// }
let mut result = TokenStream::new();
let mut expected = Vec::new();
for case in cases {
let predicate = case.predicate.to_stream(&self.tokenizer, Context::Test);
let what = case.predicate.what();
let mut var_decl = TokenStream::new();
Self::collect_var_decl(&case.pattern, &mut var_decl);
let pat = self.emit_ast(case.pattern, Context::None);
result.extend(quote!(if #predicate { #var_decl #pat } else));
expected.push(what.to_owned());
}
// else
if let Some(box else_case) = else_case {
let mut var_decl = TokenStream::new();
Self::collect_var_decl(&else_case, &mut var_decl);
let else_case = self.emit_ast(else_case, Context::None);
result.extend(quote!({ #var_decl #else_case }));
} else {
let expected = if expected.len() > 2 {
expected[..expected.len() - 1].join(", ")
+ " or "
+ expected.last().unwrap()
} else {
expected[0].to_owned()
};
result.extend(quote!({
let t = #tokenizer.expect_token()?;
return Err(t.error(format!("{} expected, not '{}'", #expected, t)))
}));
}
result
}
Ast::Sequence(subs) => {
let mut result = TokenStream::new();
let mut first = true;
for sub in subs {
if !first {
result.extend(quote!(;));
}
first = false;
result.extend(self.emit_ast(sub, context));
}
result
}
Ast::VarBind {
name_use,
value: box value,
..
} => {
let value = self.emit_ast(value, context);
quote!(#name_use = #value)
}
Ast::ZeroOrMore(box sub) => {
match sub {
Ast::Predicate(Predicate::AnyIdentifier) => {
// id
let sub = self.emit_ast(sub, Context::Optional);
quote!(
#tokenizer.parse_list(|#tokenizer| { Ok(#sub) })?
)
}
_ => {
let sub = self.emit_ast(sub, Context::None);
quote!(
#tokenizer.parse_list(|#tokenizer| {
if #tokenizer.peek_is(Token::is_semicolon) {
Ok(None)
} else {
Ok(Some(#sub))
}
})?
)
}
}
}
Ast::ZeroOrOne(box sub) => self.emit_ast(sub, Context::Optional),
}
}
}
// Used to extend TokenTree with some useful methods.
trait MyTokenTree {
fn error<T: Into<String>>(&self, msg: T) -> ParseError;
fn group_stream(&self) -> Result<TokenStream>;
fn is_exact_ident(&self, ident: &str) -> bool;
fn is_group(&self) -> bool;
fn is_literal(&self) -> bool;
fn is_punct(&self, expected: char) -> bool;
fn literal_string(&self) -> Result<String>;
fn with_span(&self, span: Span) -> TokenTree;
}
impl MyTokenTree for TokenTree {
fn error<T: Into<String>>(&self, msg: T) -> ParseError {
ParseError(self.span(), msg.into())
}
fn group_stream(&self) -> Result<TokenStream> {
match self {
TokenTree::Group(group) => Ok(group.stream()),
_ => Err(ParseError(self.span(), "Group expected".into())),
}
}
fn is_exact_ident(&self, ident: &str) -> bool {
matches!(self, TokenTree::Ident(_)) && self.to_string() == ident
}
fn is_group(&self) -> bool {
matches!(self, TokenTree::Group(_))
}
fn is_literal(&self) -> bool {
matches!(self, TokenTree::Literal(_))
}
fn is_punct(&self, expected: char) -> bool {
match self {
TokenTree::Punct(punct) => punct.as_char() == expected,
_ => false,
}
}
fn literal_string(&self) -> Result<String> {
let s = self.to_string();
let s = s.strip_prefix('"').and_then(|s| s.strip_suffix('"'));
s.ok_or_else(|| self.error("Quoted literal expected"))
.map(|s| s.to_owned())
}
fn with_span(&self, span: Span) -> TokenTree {
let mut tt = self.clone();
tt.set_span(span);
tt
}
}
// Used to extend TokenIter with some useful methods.
trait MyTokenIter {
fn expect_peek(&mut self) -> Result<&TokenTree>;
fn expect_tt(&mut self) -> Result<TokenTree>;
fn expect_ident(&mut self) -> Result<TokenTree>;
fn expect_token<F: FnOnce(&TokenTree) -> bool>(
&mut self,
what: &str,
f: F,
) -> Result<TokenTree>;
fn expect_literal(&mut self) -> Result<TokenTree>;
fn expect_group(&mut self) -> Result<TokenTree>;
fn expect_punct(&mut self, expected: char) -> Result<TokenTree>;
fn expect_eos(&mut self) -> Result<()>;
}
impl MyTokenIter for TokenIter {
fn expect_peek(&mut self) -> Result<&TokenTree> {
if let Some(t) = self.peek() {
Ok(t)
} else {
proc_macro_error::Diagnostic::new(
proc_macro_error::Level::Error,
"Token expected at end".into(),
)
.abort();
}
}
fn expect_tt(&mut self) -> Result<TokenTree> {
self.expect_peek()?;
Ok(self.next().unwrap())
}
fn expect_ident(&mut self) -> Result<TokenTree> {
let t = self.expect_tt()?;
if !matches!(t, TokenTree::Ident(_)) {
return Err(t.error("Identifier expected"));
}
Ok(t)
}
fn expect_token<F: FnOnce(&TokenTree) -> bool>(
&mut self,
what: &str,
f: F,
) -> Result<TokenTree> {
let t = self.expect_tt()?;
if f(&t) {
Ok(t)
} else {
Err(t.error(format!("{} expected", what)))
}
}
fn expect_literal(&mut self) -> Result<TokenTree> {
let t = self.expect_tt()?;
if t.is_literal() {
Ok(t)
} else {
Err(t.error("literal expected"))
}
}
fn expect_group(&mut self) -> Result<TokenTree> {
let t = self.expect_tt()?;
if t.is_group() {
Ok(t)
} else {
Err(t.error("Group expected"))
}
}
fn expect_punct(&mut self, expected: char) -> Result<TokenTree> {
let t = self.expect_tt()?;
if t.is_punct(expected) {
Ok(t)
} else {
Err(t.error(format!("'{}' expected", expected)))
}
}
fn expect_eos(&mut self) -> Result<()> {
if let Some(t) = self.next() {
Err(t.error("unexpected token"))
} else {
Ok(())
}
}
}
#[cfg(test)]
#[rustfmt::skip] // skip rustfmt because it tends to add unwanted tokens to our quotes.
#[allow(dead_code)]
mod test {
use crate::{parse_macro, ParseError};
use proc_macro2::{TokenStream, TokenTree};
use quote::quote;
fn mismatch(
ta: Option<TokenTree>,
tb: Option<TokenTree>,
ax: &TokenStream,
bx: &TokenStream,
) -> ! {
panic!(
"Mismatch!\nLeft: {}\nRight: {}\nwhen comparing\nLeft: {}\nRight: {}\n",
ta.map_or("None".into(), |t| t.to_string()),
tb.map_or("None".into(), |t| t.to_string()),
ax,
bx
);
}
fn assert_pat_eq(a: Result<TokenStream, ParseError>, b: TokenStream) {
let a = match a {
Err(err) => {
panic!("Unexpected error '{}'", err.1);
}
Ok(ok) => ok,
};
fn inner_cmp(a: TokenStream, b: TokenStream, ax: &TokenStream, bx: &TokenStream) {
let mut ia = a.into_iter();
let mut ib = b.into_iter();
loop {
let t_a = ia.next();
let t_b = ib.next();
if t_a.is_none() && t_b.is_none() {
break;
}
if t_a.is_none() || t_b.is_none() {
mismatch(t_a, t_b, ax, bx);
}
let t_a = t_a.unwrap();
let t_b = t_b.unwrap();
match (&t_a, &t_b) {
(TokenTree::Ident(_), TokenTree::Ident(_))
| (TokenTree::Literal(_), TokenTree::Literal(_))
| (TokenTree::Punct(_), TokenTree::Punct(_))
if t_a.to_string() == t_b.to_string() => {}
(TokenTree::Group(ga), TokenTree::Group(gb)) => {
inner_cmp(ga.stream(), gb.stream(), ax, bx);
}
(TokenTree::Group(_), _)
| (TokenTree::Ident(_), _)
| (TokenTree::Punct(_), _)
| (TokenTree::Literal(_), _) => mismatch(Some(t_a), Some(t_b), ax, bx),
}
}
}
inner_cmp(a.clone(), b.clone(), &a, &b);
}
fn assert_error(a: Result<TokenStream, ParseError>, b: &str) {
match a {
Ok(a) => panic!("Expected error but got:\n{}", a),
Err(ParseError(_, a)) => {
if a != b {
panic!("Incorrect error:\nLeft: {}\nRight: {}\n", a, b);
}
}
}
}
#[test]
fn test_basic() {
assert_pat_eq(
parse_macro(quote!(t, "(")),
quote!(t.expect(Token::is_open_paren)?),
);
assert_pat_eq(
parse_macro(quote!(t, num)),
quote!(t.expect(Token::is_number)?),
);
assert_pat_eq(
parse_macro(quote!(t, numeric)),
quote!(t.expect_and_get_number()?),
);
assert_pat_eq(
parse_macro(quote!(t, token)),
quote!(t.expect_token()?),
);
assert_pat_eq(
parse_macro(quote!(t, string)),
quote!(t.expect(Token::is_str_literal)?),
);
assert_pat_eq(
parse_macro(quote!(t, triple_string)),
quote!(t.expect(Token::is_triple_str_literal)?),
);
assert_pat_eq(
parse_macro(quote!(t, <e:string>)),
quote!(
#[allow(clippy::needless_late_init)]
let e;
e = t.expect(Token::is_str_literal)?
),
);
assert_pat_eq(
parse_macro(quote!(t, <mut e:string>)),
quote!(
#[allow(clippy::needless_late_init)]
let mut e;
e = t.expect(Token::is_str_literal)?
),
);
assert_pat_eq(
parse_macro(quote!(t, custom)),
quote!(custom(t)?)
);
assert_pat_eq(
parse_macro(quote!(t, <e:custom>)),
quote!(
#[allow(clippy::needless_late_init)]
let e;
e = custom(t)?
),
);
assert_pat_eq(
parse_macro(quote!(t, custom(param))),
quote!(custom(t, param)?),
);
assert_pat_eq(
parse_macro(quote!(t, id)),
quote!(t.expect(Token::is_identifier)?),
);
assert_pat_eq(
parse_macro(quote!(t, "xyzzy")),
quote!(t.expect_str(Token::is_identifier, "xyzzy")?),
);
assert_pat_eq(
parse_macro(quote!(t, ".xyzzy")),
quote!(t.expect_str(Token::is_decl, ".xyzzy")?),
);
assert_pat_eq(
parse_macro(quote!(t, @loc "xyzzy")),
quote!(
#[allow(clippy::needless_late_init)]
let loc;
loc = t.peek_loc();
t.expect_str(Token::is_identifier, "xyzzy")?
),
);
}
#[test]
fn test_optional() {
assert_pat_eq(
parse_macro(quote!(t, <e:"("?>)),
quote!(
#[allow(clippy::needless_late_init)]
let e;
e = t.next_is(Token::is_open_paren)
)
);
assert_pat_eq(
parse_macro(quote!(t, <e:"foo"?>)),
quote!(
#[allow(clippy::needless_late_init)]
let e;
e = t.next_is_str(Token::is_identifier, "foo")
)
);
assert_pat_eq(
parse_macro(quote!(t, <e:".foo"?>)),
quote!(
#[allow(clippy::needless_late_init)]
let e;
e = t.next_is_str(Token::is_decl, ".foo")
)
);
assert_pat_eq(
parse_macro(quote!(t, <e:token?>)),
quote!(
#[allow(clippy::needless_late_init)]
let e;
e = t.peek()
)
);
assert_error(
parse_macro(quote!(t, { foo(); }?)),
"Error: '?' only works with basic patterns"
);
}
#[test]
fn test_list() {
assert_pat_eq(
parse_macro(quote!(t, <e:id*>)),
quote!(
#[allow(clippy::needless_late_init)]
let e;
e = t.parse_list(|t| { Ok(t.next_if(Token::is_identifier)) })?
),
);
assert_pat_eq(
parse_macro(quote!(t, <e:f*>)),
quote!(
#[allow(clippy::needless_late_init)]
let e;
e = t.parse_list(|t| {
if t.peek_is(Token::is_semicolon) {
Ok(None)
} else {
Ok(Some(f(t)?))
}
})?
),
);
}
#[test]
fn test_comma() {
assert_pat_eq(
parse_macro(quote!(t, "x",+)),
quote!(t.parse_comma_list(false, |t| {
Ok(t.expect_str(Token::is_identifier, "x")?)
})?),
);
assert_pat_eq(
parse_macro(quote!(t, <e:"x",+>)),
quote!(
#[allow(clippy::needless_late_init)]
let e;
e = t.parse_comma_list(false, |t| {
Ok(t.expect_str(Token::is_identifier, "x")?)
})?
),
);
assert_pat_eq(
parse_macro(quote!(t, <e:"x",*> "]")),
quote!(
#[allow(clippy::needless_late_init)]
let e;
e = if !t.peek_is(Token::is_close) {
t.parse_comma_list(false, |t| {
Ok(t.expect_str(Token::is_identifier, "x")?)
})?
} else {
Vec::new()
};
t.expect(Token::is_close_bracket)?
),
);
}
#[test]
fn test_embedded_code() {
assert_pat_eq(
parse_macro(quote!(t, "(" { something(); } ")")),
quote!(
t.expect(Token::is_open_paren)?;
something();
/* harmless extra semicolon -> */ ;
t.expect(Token::is_close_paren)?
),
);
assert_pat_eq(
parse_macro(quote!(t, "(" <e:{ something(); }> ")")),
quote!(
#[allow(clippy::needless_late_init)]
let e;
t.expect(Token::is_open_paren)?;
e = something();
/* harmless extra semicolon -> */ ;
t.expect(Token::is_close_paren)?
),
);
}
#[test]
fn test_select() {
assert_pat_eq(
parse_macro(quote!(t, "(" [
"a": parse_a;
"b": <e:parse_b>;
"(": parse_c;
] ")")),
quote!(
t.expect(Token::is_open_paren)?;
if t.peek_is_str(Token::is_identifier, "a") {
parse_a(t)?
} else if t.peek_is_str(Token::is_identifier, "b") {
#[allow(clippy::needless_late_init)]
let e;
e = parse_b(t)?
} else if t.peek_is(Token::is_open_paren) {
parse_c(t)?
} else {
let t = t.expect_token()?;
return Err(t.error(format!("{} expected, not '{}'" , "'a', 'b' or '('" , t)))
}
/* harmless extra semi -> */ ;
t.expect(Token::is_close_paren)?
),
);
assert_pat_eq(
parse_macro(quote!(t, [
".a": parse_a;
else: parse_b;
])),
quote!(
if t.peek_is_str(Token::is_decl, ".a") {
parse_a(t)?
} else {
parse_b(t)?
}
),
);
assert_pat_eq(
parse_macro(quote!(t, [
id: parse_a;
else: parse_b;
])),
quote!(
if t.peek_is(Token::is_identifier) {
parse_a(t)?
} else {
parse_b(t)?
}
),
);
assert_pat_eq(
parse_macro(quote!(t, [
token: parse_a;
else: parse_b;
])),
quote!(
if t.peek().is_some() {
parse_a(t)?
} else {
parse_b(t)?
}
),
);
assert_pat_eq(
parse_macro(quote!(t, "(" [
"a": parse_a;
"b": parse_b;
else: parse_c;
] ")")),
quote!(
t.expect(Token::is_open_paren)?;
if t.peek_is_str(Token::is_identifier, "a") {
parse_a(t)?
} else if t.peek_is_str(Token::is_identifier, "b") {
parse_b(t)?
} else {
parse_c(t)?
}
/* harmless extra semi -> */ ;
t.expect(Token::is_close_paren)?
),
);
assert_pat_eq(
parse_macro(quote!(tokenizer, [
"as": "as" { Ok(DowncastReason::As) } ;
"native": "native" <index:num> { Ok(DowncastReason::Native { index:index.as_int()? }) } ;
"param": "param" <index:num> { Ok(DowncastReason::Param {index:index.as_int()? }) } ;
"return": "return" { Ok(DowncastReason::Return) } ;
else: <tok:token> { Err(tok.error("Unknown VerifyIs reason")) } ;
])),
quote!(
if tokenizer.peek_is_str(Token::is_identifier, "as") {
tokenizer.expect_str(Token::is_identifier, "as")?;
Ok(DowncastReason::As)
} else if tokenizer.peek_is_str(Token::is_identifier, "native") {
#[allow(clippy::needless_late_init)]
let index;
tokenizer.expect_str(Token::is_identifier, "native")?;
index = tokenizer.expect(Token::is_number)?;
Ok(DowncastReason::Native { index: index.as_int()? })
} else if tokenizer.peek_is_str(Token::is_identifier, "param") {
#[allow(clippy::needless_late_init)]
let index;
tokenizer.expect_str(Token::is_identifier, "param")?;
index = tokenizer.expect(Token::is_number)?;
Ok(DowncastReason::Param { index: index.as_int()? })
} else if tokenizer.peek_is_str(Token::is_identifier, "return") {
tokenizer.expect_str(Token::is_identifier, "return")?;
Ok(DowncastReason::Return)
} else {
#[allow(clippy::needless_late_init)]
let tok;
tok = tokenizer.expect_token()?;
Err(tok.error("Unknown VerifyIs reason"))
}
),
);
}
} |
Rust | hhvm/hphp/hack/src/hackc/assemble/token.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::fmt;
use anyhow::anyhow;
use anyhow::bail;
use anyhow::Result;
use newtype::newtype_int;
// 1-based line number.
newtype_int!(Line, u32, LineMap, LineSet);
#[derive(Debug, PartialEq, Eq, Copy, Clone, strum::IntoStaticStr)]
pub(crate) enum Token<'a> {
// See Lexer::from_slice for regex definitions
Global(&'a [u8], Line),
Variable(&'a [u8], Line),
TripleStrLiteral(&'a [u8], Line),
Decl(&'a [u8], Line),
StrLiteral(&'a [u8], Line),
Variadic(Line),
Semicolon(Line),
Dash(Line),
OpenCurly(Line),
OpenBracket(Line),
OpenParen(Line),
CloseParen(Line),
CloseBracket(Line),
CloseCurly(Line),
Equal(Line),
Number(&'a [u8], Line),
Comma(Line),
Lt(Line),
Gt(Line),
Colon(Line),
Identifier(&'a [u8], Line),
Newline(Line),
Error(&'a [u8], Line),
}
impl<'a> Token<'a> {
pub(crate) fn error(&self, err: impl std::fmt::Display) -> anyhow::Error {
anyhow!("Error [line {line}]: {err} ({self:?})", line = self.line())
}
pub(crate) fn line(&self) -> Line {
match self {
Token::CloseBracket(u)
| Token::CloseCurly(u)
| Token::CloseParen(u)
| Token::Colon(u)
| Token::Comma(u)
| Token::Dash(u)
| Token::Decl(_, u)
| Token::Equal(u)
| Token::Error(_, u)
| Token::Global(_, u)
| Token::Gt(u)
| Token::Identifier(_, u)
| Token::Lt(u)
| Token::Newline(u)
| Token::Number(_, u)
| Token::OpenBracket(u)
| Token::OpenCurly(u)
| Token::OpenParen(u)
| Token::Semicolon(u)
| Token::StrLiteral(_, u)
| Token::TripleStrLiteral(_, u)
| Token::Variable(_, u)
| Token::Variadic(u) => *u,
}
}
pub(crate) fn as_bytes(&self) -> &'a [u8] {
match self {
Token::Global(u, _)
| Token::Variable(u, _)
| Token::TripleStrLiteral(u, _)
| Token::Decl(u, _)
| Token::StrLiteral(u, _)
| Token::Number(u, _)
| Token::Identifier(u, _)
| Token::Error(u, _) => u,
Token::Semicolon(_) => b";",
Token::Dash(_) => b"-",
Token::OpenCurly(_) => b"{",
Token::OpenBracket(_) => b"[",
Token::OpenParen(_) => b"(",
Token::CloseParen(_) => b")",
Token::CloseBracket(_) => b"]",
Token::CloseCurly(_) => b"}",
Token::Equal(_) => b"=",
Token::Comma(_) => b",",
Token::Lt(_) => b"<",
Token::Gt(_) => b">",
Token::Colon(_) => b":",
Token::Variadic(_) => b"...",
Token::Newline(_) => b"\n",
}
}
pub(crate) fn into_ffi_str<'arena>(&self, alloc: &'arena bumpalo::Bump) -> ffi::Str<'arena> {
ffi::Str::new_slice(alloc, self.as_bytes())
}
/// Only str_literal and triple_str_literal can be parsed into a new tokenizer.
/// To create a new tokenizer that still has accurate error reporting, we want to pass the line
/// So `into_str_literal_and_line` and `into_triple_str_literal_and_line` return a Result of bytes rep and line # or bail
pub(crate) fn into_triple_str_literal_and_line(self) -> Result<(&'a [u8], Line)> {
match self {
Token::TripleStrLiteral(vec_u8, pos) => Ok((vec_u8, pos)),
_ => bail!("Expected a triple str literal, got: {}", self),
}
}
pub(crate) fn into_global(self) -> Result<&'a [u8]> {
match self {
Token::Global(vec_u8, _) => Ok(vec_u8),
_ => bail!("Expected a global, got: {}", self),
}
}
pub(crate) fn into_variable(self) -> Result<&'a [u8]> {
match self {
Token::Variable(vec_u8, _) => Ok(vec_u8),
_ => bail!("Expected a variable, got: {}", self),
}
}
pub(crate) fn into_triple_str_literal(self) -> Result<&'a [u8]> {
match self {
Token::TripleStrLiteral(vec_u8, _) => Ok(vec_u8),
_ => bail!("Expected a triple str literal, got: {}", self),
}
}
#[cfg(test)]
pub(crate) fn into_decl(self) -> Result<&'a [u8]> {
match self {
Token::Decl(vec_u8, _) => Ok(vec_u8),
_ => bail!("Expected a decl, got: {}", self),
}
}
pub(crate) fn into_str_literal(self) -> Result<&'a [u8]> {
match self {
Token::StrLiteral(vec_u8, _) => Ok(vec_u8),
_ => bail!("Expected a str literal, got: {}", self),
}
}
pub(crate) fn into_unquoted_str_literal(self) -> Result<&'a [u8]> {
Ok(escaper::unquote_slice(self.into_str_literal()?))
}
pub(crate) fn into_number(self) -> Result<&'a [u8]> {
match self {
Token::Number(vec_u8, _) => Ok(vec_u8),
_ => bail!("Expected a number, got: {}", self),
}
}
pub(crate) fn into_identifier(self) -> Result<&'a [u8]> {
match self {
Token::Identifier(vec_u8, _) => Ok(vec_u8),
_ => bail!("Expected an identifier, got: {}", self),
}
}
pub(crate) fn into_dash(self) -> Result<&'a [u8]> {
match self {
Token::Dash(_) => Ok(self.as_bytes()),
_ => bail!("Expected a dash, got: {}", self),
}
}
pub(crate) fn is_triple_str_literal(&self) -> bool {
matches!(self, Token::TripleStrLiteral(..))
}
pub(crate) fn is_decl(&self) -> bool {
matches!(self, Token::Decl(..))
}
pub(crate) fn is_str_literal(&self) -> bool {
matches!(self, Token::StrLiteral(..))
}
pub(crate) fn is_number(&self) -> bool {
matches!(self, Token::Number(..))
}
pub(crate) fn is_identifier(&self) -> bool {
matches!(self, Token::Identifier(..))
}
pub(crate) fn is_comma(&self) -> bool {
matches!(self, Token::Comma(_))
}
pub(crate) fn is_semicolon(&self) -> bool {
matches!(self, Token::Semicolon(_))
}
pub(crate) fn is_colon(&self) -> bool {
matches!(self, Token::Colon(_))
}
pub(crate) fn is_dash(&self) -> bool {
matches!(self, Token::Dash(_))
}
pub(crate) fn is_open_bracket(&self) -> bool {
matches!(self, Token::OpenBracket(_))
}
pub(crate) fn is_open_paren(&self) -> bool {
matches!(self, Token::OpenParen(_))
}
pub(crate) fn is_close(&self) -> bool {
matches!(
self,
Token::CloseParen(_) | Token::CloseBracket(_) | Token::CloseCurly(_)
)
}
pub(crate) fn is_close_paren(&self) -> bool {
matches!(self, Token::CloseParen(_))
}
pub(crate) fn is_close_bracket(&self) -> bool {
matches!(self, Token::CloseBracket(_))
}
pub(crate) fn is_open_curly(&self) -> bool {
matches!(self, Token::OpenCurly(_))
}
pub(crate) fn is_close_curly(&self) -> bool {
matches!(self, Token::CloseCurly(_))
}
pub(crate) fn is_equal(&self) -> bool {
matches!(self, Token::Equal(_))
}
pub(crate) fn is_lt(&self) -> bool {
matches!(self, Token::Lt(_))
}
pub(crate) fn is_gt(&self) -> bool {
matches!(self, Token::Gt(_))
}
pub(crate) fn is_variadic(&self) -> bool {
matches!(self, Token::Variadic(_))
}
}
impl fmt::Display for Token<'_> {
/// Purpose of this fmt: so that vec of u8 (internal str representation of each token) is printed as a string rather than bytes
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let text = std::str::from_utf8(self.as_bytes()).map_err(|_| fmt::Error)?;
let variant: &str = (*self).into();
let line = self.line();
write!(f, r#"{variant}("{text}", line: {line})"#)
}
} |
TOML | hhvm/hphp/hack/src/hackc/bytecode_printer/Cargo.toml | # @generated by autocargo
[package]
name = "bytecode_printer"
version = "0.0.0"
edition = "2021"
[lib]
path = "lib.rs"
[dependencies]
anyhow = "1.0.71"
bstr = { version = "1.4.0", features = ["serde", "std", "unicode"] }
escaper = { version = "0.0.0", path = "../../utils/escaper" }
ffi = { version = "0.0.0", path = "../../utils/ffi" }
hash = { version = "0.0.0", path = "../../utils/hash" }
hhbc = { version = "0.0.0", path = "../hhbc/cargo/hhbc" }
hhbc_string_utils = { version = "0.0.0", path = "../utils/cargo/hhbc_string_utils" }
hhvm_hhbc_defs_ffi = { version = "0.0.0", path = "../hhvm_cxx/hhvm_hhbc_defs" }
hhvm_types_ffi = { version = "0.0.0", path = "../hhvm_cxx/hhvm_types" }
itertools = "0.10.3"
oxidized = { version = "0.0.0", path = "../../oxidized" }
print_opcode = { version = "0.0.0", path = "print_opcode/cargo/lib" }
relative_path = { version = "0.0.0", path = "../../utils/rust/relative_path" }
thiserror = "1.0.43"
write_bytes = { version = "0.0.0", path = "../../utils/write_bytes/write_bytes" } |
Rust | hhvm/hphp/hack/src/hackc/bytecode_printer/coeffects.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::io::Result;
use std::io::Write;
use hhbc::Coeffects;
use write_bytes::write_bytes;
use write_bytes::DisplayBytes;
use crate::context::Context;
use crate::context::FmtIndent;
use crate::write::fmt_separated;
use crate::write::fmt_separated_with;
pub(crate) fn coeffects_to_hhas(
ctx: &Context<'_>,
w: &mut dyn Write,
coeffects: &Coeffects<'_>,
) -> Result<()> {
let indent = FmtIndent(ctx);
let static_coeffects = coeffects.get_static_coeffects();
let unenforced_static_coeffects = coeffects.get_unenforced_static_coeffects();
if !static_coeffects.is_empty() || !unenforced_static_coeffects.is_empty() {
write_bytes!(
w,
"\n{}.coeffects_static {};",
indent,
fmt_separated(
" ",
static_coeffects
.iter()
.map(|co| co as &dyn DisplayBytes)
.chain(
unenforced_static_coeffects
.iter()
.map(|co| co as &dyn DisplayBytes),
),
),
)?;
}
let fun_params = coeffects.get_fun_param();
if !fun_params.is_empty() {
write_bytes!(
w,
"\n{}.coeffects_fun_param {};",
indent,
fmt_separated(" ", fun_params)
)?;
}
let cc_params = coeffects.get_cc_param();
if !cc_params.is_empty() {
write_bytes!(
w,
"\n{}.coeffects_cc_param {};",
indent,
fmt_separated_with(" ", cc_params, |w, c| write_bytes!(
w, "{} {}", c.index, c.ctx_name
))
)?;
}
for v in coeffects.get_cc_this() {
write_bytes!(
w,
"\n{}.coeffects_cc_this {};",
indent,
fmt_separated(" ", v.types.iter())
)?;
}
for v in coeffects.get_cc_reified() {
write_bytes!(
w,
"\n{}.coeffects_cc_reified {}{} {};",
indent,
if v.is_class { "isClass " } else { "" },
v.index,
fmt_separated(" ", v.types.iter())
)?;
}
if coeffects.is_closure_parent_scope() {
write!(w, "\n{}.coeffects_closure_parent_scope;", indent)?;
}
if coeffects.generator_this() {
write!(w, "\n{}.coeffects_generator_this;", indent)?;
}
if coeffects.caller() {
write!(w, "\n{}.coeffects_caller;", indent)?;
}
Ok(())
} |
Rust | hhvm/hphp/hack/src/hackc/bytecode_printer/context.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::fmt;
use std::io::Result;
use std::io::Write;
use relative_path::RelativePath;
/// Indent is an abstraction of indentation. Configurable indentation
/// and perf tweaking will be easier.
#[derive(Clone)]
struct Indent(usize);
impl Indent {
fn new() -> Self {
Self(0)
}
fn inc(&mut self) {
self.0 += 1;
}
fn dec(&mut self) {
self.0 -= 1;
}
}
impl fmt::Display for Indent {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for _ in 0..self.0 {
f.write_str(" ")?;
}
Ok(())
}
}
#[derive(Clone)]
pub struct Context<'a> {
pub(crate) path: Option<&'a RelativePath>,
indent: Indent,
pub(crate) array_provenance: bool,
}
impl<'a> Context<'a> {
pub fn new(path: Option<&'a RelativePath>, array_provenance: bool) -> Self {
Self {
path,
indent: Indent::new(),
array_provenance,
}
}
/// Insert a newline with indentation
pub(crate) fn newline(&self, w: &mut dyn Write) -> Result<()> {
write!(w, "\n{}", self.indent)
}
/// Start a new indented block
pub(crate) fn block<F>(&self, w: &mut dyn Write, f: F) -> Result<()>
where
F: FnOnce(&Self, &mut dyn Write) -> Result<()>,
{
let mut ctx = self.clone();
ctx.indent.inc();
f(&ctx, w)
}
pub(crate) fn unblock<F>(&self, w: &mut dyn Write, f: F) -> Result<()>
where
F: FnOnce(&Self, &mut dyn Write) -> Result<()>,
{
let mut ctx = self.clone();
ctx.indent.dec();
f(&ctx, w)
}
/// Printing instruction list requires manually control indentation,
/// where indent_inc/indent_dec are called
pub(crate) fn indent_inc(&mut self) {
self.indent.inc();
}
pub(crate) fn indent_dec(&mut self) {
self.indent.dec();
}
}
pub(crate) struct FmtIndent<'a>(pub(crate) &'a Context<'a>);
impl fmt::Display for FmtIndent<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.indent.fmt(f)?;
Ok(())
}
}
write_bytes::display_bytes_using_display!(FmtIndent<'_>); |
Rust | hhvm/hphp/hack/src/hackc/bytecode_printer/lib.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
mod coeffects;
mod context;
mod print;
mod print_opcode;
mod write;
pub use context::Context;
pub use print::external_print_unit as print_unit;
pub use write::Error; |
Rust | hhvm/hphp/hack/src/hackc/bytecode_printer/print.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::borrow::Cow;
use std::io;
use std::io::Result;
use std::io::Write;
use std::write;
use ffi::Maybe;
use ffi::Maybe::*;
use ffi::Slice;
use ffi::Str;
use hash::HashSet;
use hhbc::Adata;
use hhbc::Attribute;
use hhbc::Body;
use hhbc::Class;
use hhbc::ClassName;
use hhbc::Coeffects;
use hhbc::ConstName;
use hhbc::Constant;
use hhbc::CtxConstant;
use hhbc::DefaultValue;
use hhbc::DictEntry;
use hhbc::FCallArgs;
use hhbc::Fatal;
use hhbc::FatalOp;
use hhbc::Function;
use hhbc::FunctionName;
use hhbc::IncludePath;
use hhbc::Instruct;
use hhbc::Label;
use hhbc::Method;
use hhbc::MethodFlags;
use hhbc::Module;
use hhbc::Param;
use hhbc::Property;
use hhbc::Pseudo;
use hhbc::Requirement;
use hhbc::Rule;
use hhbc::RuleKind;
use hhbc::Span;
use hhbc::SrcLoc;
use hhbc::SymbolRefs;
use hhbc::TraitReqKind;
use hhbc::TypeConstant;
use hhbc::TypeInfo;
use hhbc::TypedValue;
use hhbc::Typedef;
use hhbc::Unit;
use hhbc::UpperBound;
use hhbc_string_utils::float;
use hhvm_types_ffi::ffi::*;
use itertools::Itertools;
use oxidized::ast_defs;
use write_bytes::write_bytes;
use crate::coeffects;
use crate::context::Context;
use crate::write;
use crate::write::angle;
use crate::write::braces;
use crate::write::concat;
use crate::write::concat_by;
use crate::write::concat_str;
use crate::write::concat_str_by;
use crate::write::fmt_separated;
use crate::write::fmt_separated_with;
use crate::write::newline;
use crate::write::option;
use crate::write::option_or;
use crate::write::paren;
use crate::write::quotes;
use crate::write::square;
use crate::write::triple_quotes;
use crate::write::wrap_by;
use crate::write::Error;
macro_rules! write_if {
($pred:expr, $($rest:tt)*) => {
if ($pred) { write!($($rest)*) } else { Ok(()) }
};
}
fn print_unit(ctx: &Context<'_>, w: &mut dyn Write, prog: &Unit<'_>) -> Result<()> {
match ctx.path {
Some(p) => {
let abs = p.path(); // consider: should we also show prefix?
let p = escaper::escape(
abs.to_str()
.ok_or_else(|| <io::Error as From<Error>>::from(Error::InvalidUTF8))?,
);
concat_str_by(w, " ", ["#", p.as_ref(), "starts here"])?;
newline(w)?;
newline(w)?;
concat_str(w, [".filepath ", &format!("\"{}\"", p), ";"])?;
newline(w)?;
handle_not_impl(|| print_unit_(ctx, w, prog))?;
newline(w)?;
concat_str_by(w, " ", ["#", p.as_ref(), "ends here"])?;
newline(w)
}
None => {
w.write_all(b"#starts here")?;
newline(w)?;
handle_not_impl(|| print_unit_(ctx, w, prog))?;
newline(w)?;
w.write_all(b"#ends here")?;
newline(w)
}
}
}
fn get_fatal_op(f: &FatalOp) -> &str {
match *f {
FatalOp::Parse => "Parse",
FatalOp::Runtime => "Runtime",
FatalOp::RuntimeOmitFrame => "RuntimeOmitFrame",
_ => panic!("Enum value does not match one of listed variants"),
}
}
fn print_unit_(ctx: &Context<'_>, w: &mut dyn Write, prog: &Unit<'_>) -> Result<()> {
if let Just(Fatal {
op,
loc:
SrcLoc {
line_begin,
line_end,
col_begin,
col_end,
},
message,
}) = &prog.fatal
{
newline(w)?;
write_bytes!(
w,
".fatal {}:{},{}:{} {} \"{}\";",
line_begin,
col_begin,
line_end,
col_end,
get_fatal_op(op),
escaper::escape_bstr(message.as_bstr()),
)?;
}
newline(w)?;
print_module_use(w, &prog.module_use)?;
concat(w, prog.adata, |w, a| print_adata_region(ctx, w, a))?;
concat(w, prog.functions, |w, f| print_fun_def(ctx, w, f))?;
concat(w, prog.classes, |w, cd| print_class_def(ctx, w, cd))?;
concat(w, prog.modules, |w, cd| print_module_def(ctx, w, cd))?;
concat(w, prog.constants, |w, c| print_constant(ctx, w, c))?;
concat(w, prog.typedefs, |w, td| print_typedef(ctx, w, td))?;
print_file_attributes(ctx, w, prog.file_attributes.as_ref())?;
print_include_region(w, &prog.symbol_refs.includes)?;
print_symbol_ref_regions(ctx, w, &prog.symbol_refs)?;
Ok(())
}
fn print_include_region(w: &mut dyn Write, includes: &Slice<'_, IncludePath<'_>>) -> Result<()> {
fn print_include(w: &mut dyn Write, inc: &IncludePath<'_>) -> Result<()> {
let (s1, s2) = inc.extract_str();
write!(w, "\n {}{}", s1, s2)?;
Ok(())
}
if !includes.is_empty() {
w.write_all(b"\n.includes {")?;
for inc in includes.as_ref().iter() {
print_include(w, inc)?;
}
w.write_all(b"\n}\n")?;
}
Ok(())
}
fn print_symbol_ref_regions<'arena>(
ctx: &Context<'_>,
w: &mut dyn Write,
symbol_refs: &SymbolRefs<'arena>,
) -> Result<()> {
fn print_region<'a, T: 'a, F>(
ctx: &Context<'_>,
w: &mut dyn Write,
name: &str,
refs: impl IntoIterator<Item = &'a T>,
f: F,
) -> Result<()>
where
F: Fn(&'a T) -> &'a [u8],
{
let mut iter = refs.into_iter();
if let Some(first) = iter.next() {
ctx.newline(w)?;
write!(w, ".{} {{", name)?;
ctx.block(w, |c, w| {
c.newline(w)?;
w.write_all(f(first))?;
for s in iter {
c.newline(w)?;
w.write_all(f(s))?;
}
Ok(())
})?;
w.write_all(b"\n}\n")?;
}
Ok(())
}
print_region(
ctx,
w,
"constant_refs",
&symbol_refs.constants,
ConstName::as_bytes,
)?;
print_region(
ctx,
w,
"function_refs",
&symbol_refs.functions,
FunctionName::as_bytes,
)?;
print_region(
ctx,
w,
"class_refs",
&symbol_refs.classes,
ClassName::as_bytes,
)
}
fn print_adata_region(ctx: &Context<'_>, w: &mut dyn Write, adata: &Adata<'_>) -> Result<()> {
write_bytes!(w, ".adata {} = ", adata.id)?;
triple_quotes(w, |w| print_adata(ctx, w, &adata.value))?;
w.write_all(b";")?;
ctx.newline(w)
}
fn print_typedef(ctx: &Context<'_>, w: &mut dyn Write, td: &Typedef<'_>) -> Result<()> {
newline(w)?;
w.write_all(if td.case_type {
b".case_type "
} else {
b".alias "
})?;
print_special_and_user_attrs(
ctx,
w,
td.attributes.as_ref(),
&AttrContext::Alias,
&td.attrs,
)?;
w.write_all(td.name.as_bstr())?;
w.write_all(b" = ")?;
print_typedef_info_union(w, td.type_info_union.as_ref())?;
w.write_all(b" ")?;
print_span(w, &td.span)?;
w.write_all(b" ")?;
triple_quotes(w, |w| print_adata(ctx, w, &td.type_structure))?;
w.write_all(b";")
}
fn handle_not_impl<F>(f: F) -> Result<()>
where
F: FnOnce() -> Result<()>,
{
f().or_else(|e| {
match write::get_embedded_error(&e) {
Some(Error::NotImpl(msg)) => {
println!("#### NotImpl: {}", msg);
eprintln!("NotImpl: {}", msg);
return Ok(());
}
_ => {}
}
Err(e)
})
}
fn print_fun_def(ctx: &Context<'_>, w: &mut dyn Write, fun_def: &Function<'_>) -> Result<()> {
let body = &fun_def.body;
newline(w)?;
w.write_all(b".function ")?;
print_upper_bounds_(w, body.upper_bounds)?;
w.write_all(b" ")?;
print_special_and_user_attrs(
ctx,
w,
fun_def.attributes.as_ref(),
&AttrContext::Func,
&fun_def.attrs,
)?;
print_span(w, &fun_def.span)?;
w.write_all(b" ")?;
option(w, body.return_type_info.as_ref(), |w, ti| {
print_type_info(w, ti)?;
w.write_all(b" ")
})?;
w.write_all(fun_def.name.as_bstr())?;
let params = fun_def.params();
let dv_labels = find_dv_labels(params);
print_params(ctx, w, fun_def.params(), &dv_labels)?;
if fun_def.is_generator() {
w.write_all(b" isGenerator")?;
}
if fun_def.is_async() {
w.write_all(b" isAsync")?;
}
if fun_def.is_pair_generator() {
w.write_all(b" isPairGenerator")?;
}
w.write_all(b" ")?;
braces(w, |w| {
ctx.block(w, |c, w| {
print_body(c, w, body, &fun_def.coeffects, &dv_labels)
})?;
newline(w)
})?;
newline(w)
}
fn print_requirement(ctx: &Context<'_>, w: &mut dyn Write, r: &Requirement<'_>) -> Result<()> {
ctx.newline(w)?;
w.write_all(b".require ")?;
match r.kind {
TraitReqKind::MustExtend => {
write_bytes!(w, "extends <{}>;", r.name)
}
TraitReqKind::MustImplement => {
write_bytes!(w, "implements <{}>;", r.name)
}
TraitReqKind::MustBeClass => {
write_bytes!(w, "class <{}>;", r.name)
}
}
}
fn print_type_constant(ctx: &Context<'_>, w: &mut dyn Write, c: &TypeConstant<'_>) -> Result<()> {
ctx.newline(w)?;
write_bytes!(w, ".const {} isType", c.name)?;
if c.is_abstract {
w.write_all(b" isAbstract")?;
}
option(w, c.initializer.as_ref(), |w, init| {
w.write_all(b" = ")?;
triple_quotes(w, |w| print_adata(ctx, w, init))
})?;
w.write_all(b";")
}
fn print_ctx_constant(ctx: &Context<'_>, w: &mut dyn Write, c: &CtxConstant<'_>) -> Result<()> {
ctx.newline(w)?;
write_bytes!(w, ".ctx {}", c.name)?;
if c.is_abstract {
w.write_all(b" isAbstract")?;
}
let recognized = c.recognized.as_ref();
if !recognized.is_empty() {
write_bytes!(w, " {}", fmt_separated(" ", recognized))?;
}
let unrecognized = c.unrecognized.as_ref();
if !unrecognized.is_empty() {
write_bytes!(w, " {}", fmt_separated(" ", unrecognized))?;
}
w.write_all(b";")?;
Ok(())
}
fn print_property_doc_comment(w: &mut dyn Write, p: &Property<'_>) -> Result<()> {
if let Just(s) = p.doc_comment.as_ref() {
write_bytes!(w, r#""""{}""""#, escaper::escape_bstr(s.as_bstr()))?;
w.write_all(b" ")?;
}
Ok(())
}
fn print_property_type_info(w: &mut dyn Write, p: &Property<'_>) -> Result<()> {
print_type_info(w, &p.type_info)?;
w.write_all(b" ")
}
fn print_property(ctx: &Context<'_>, w: &mut dyn Write, property: &Property<'_>) -> Result<()> {
newline(w)?;
w.write_all(b" .property ")?;
print_special_and_user_attrs(
ctx,
w,
property.attributes.as_ref(),
&AttrContext::Prop,
&property.flags,
)?;
print_property_doc_comment(w, property)?;
print_property_type_info(w, property)?;
w.write_all(property.name.as_bstr())?;
w.write_all(b" =\n ")?;
let initial_value = property.initial_value.as_ref();
if initial_value == Just(&TypedValue::Uninit) {
w.write_all(b"uninit;")
} else {
triple_quotes(w, |w| match initial_value {
Nothing => w.write_all(b"N;"),
Just(value) => print_adata(ctx, w, value),
})?;
w.write_all(b";")
}
}
fn print_constant(ctx: &Context<'_>, w: &mut dyn Write, c: &Constant<'_>) -> Result<()> {
ctx.newline(w)?;
w.write_all(b".const ")?;
print_special_and_user_attrs(ctx, w, &[], &AttrContext::Constant, &c.attrs)?;
w.write_all(c.name.as_bstr())?;
match c.value.as_ref() {
Just(TypedValue::Uninit) => w.write_all(b" = uninit")?,
Just(value) => {
w.write_all(b" = ")?;
triple_quotes(w, |w| print_adata(ctx, w, value))?;
}
Nothing => {}
}
w.write_all(b";")
}
fn print_enum_ty(ctx: &Context<'_>, w: &mut dyn Write, c: &Class<'_>) -> Result<()> {
if let Just(et) = c.enum_type.as_ref() {
ctx.newline(w)?;
w.write_all(b".enum_ty ")?;
print_type_info_(w, true, et)?;
w.write_all(b";")?;
}
Ok(())
}
fn print_doc_comment<'arena>(
ctx: &Context<'_>,
w: &mut dyn Write,
doc_comment: Maybe<&Str<'arena>>,
) -> Result<()> {
if let Just(cmt) = doc_comment {
ctx.newline(w)?;
write_bytes!(w, r#".doc """{}""";"#, escaper::escape_bstr(cmt.as_bstr()))?;
}
Ok(())
}
fn print_uses<'arena>(w: &mut dyn Write, c: &Class<'arena>) -> Result<()> {
if c.uses.is_empty() {
Ok(())
} else {
newline(w)?;
write_bytes!(w, " .use {}", fmt_separated(" ", c.uses.iter()))?;
w.write_all(b";")
}
}
fn print_implements(w: &mut dyn Write, implements: &[ClassName<'_>]) -> Result<()> {
if implements.is_empty() {
return Ok(());
}
write_bytes!(w, " implements ({})", fmt_separated(" ", implements))
}
fn print_enum_includes(w: &mut dyn Write, enum_includes: &[ClassName<'_>]) -> Result<()> {
if enum_includes.is_empty() {
return Ok(());
}
write_bytes!(w, " enum_includes ({})", fmt_separated(" ", enum_includes))
}
fn print_shadowed_tparams<'arena>(
w: &mut dyn Write,
shadowed_tparams: impl AsRef<[Str<'arena>]>,
) -> Result<()> {
write_bytes!(w, "{{{}}}", fmt_separated(", ", shadowed_tparams.as_ref()))
}
fn print_method_def(ctx: &Context<'_>, w: &mut dyn Write, method_def: &Method<'_>) -> Result<()> {
let body = &method_def.body;
newline(w)?;
w.write_all(b" .method ")?;
print_shadowed_tparams(w, body.shadowed_tparams)?;
print_upper_bounds_(w, body.upper_bounds)?;
w.write_all(b" ")?;
print_special_and_user_attrs(
ctx,
w,
method_def.attributes.as_ref(),
&AttrContext::Func,
&method_def.attrs,
)?;
print_span(w, &method_def.span)?;
w.write_all(b" ")?;
option(w, body.return_type_info.as_ref(), |w, t| {
print_type_info(w, t)?;
w.write_all(b" ")
})?;
w.write_all(method_def.name.as_bstr())?;
let dv_labels = find_dv_labels(&body.params);
print_params(ctx, w, &body.params, &dv_labels)?;
if method_def.flags.contains(MethodFlags::IS_GENERATOR) {
w.write_all(b" isGenerator")?;
}
if method_def.flags.contains(MethodFlags::IS_ASYNC) {
w.write_all(b" isAsync")?;
}
if method_def.flags.contains(MethodFlags::IS_PAIR_GENERATOR) {
w.write_all(b" isPairGenerator")?;
}
if method_def.flags.contains(MethodFlags::IS_CLOSURE_BODY) {
w.write_all(b" isClosureBody")?;
}
w.write_all(b" ")?;
braces(w, |w| {
ctx.block(w, |c, w| {
print_body(c, w, body, &method_def.coeffects, &dv_labels)
})?;
newline(w)?;
w.write_all(b" ")
})
}
fn print_class_def<'arena>(
ctx: &Context<'_>,
w: &mut dyn Write,
class_def: &Class<'arena>,
) -> Result<()> {
newline(w)?;
w.write_all(b".class ")?;
print_upper_bounds(w, class_def.upper_bounds.as_ref())?;
w.write_all(b" ")?;
print_special_and_user_attrs(
ctx,
w,
class_def.attributes.as_ref(),
&AttrContext::Class,
&class_def.flags,
)?;
w.write_all(class_def.name.as_bstr())?;
w.write_all(b" ")?;
print_span(w, &class_def.span)?;
print_extends(
w,
class_def
.base
.as_ref()
.map(|x: &ClassName<'arena>| x.unsafe_as_str())
.into(),
)?;
print_implements(w, class_def.implements.as_ref())?;
print_enum_includes(w, class_def.enum_includes.as_ref())?;
w.write_all(b" {")?;
ctx.block(w, |c, w| {
print_doc_comment(c, w, class_def.doc_comment.as_ref())?;
print_uses(w, class_def)?;
print_enum_ty(c, w, class_def)?;
for x in class_def.requirements.as_ref() {
print_requirement(c, w, x)?;
}
for x in class_def.constants.as_ref() {
print_constant(c, w, x)?;
}
for x in class_def.type_constants.as_ref() {
print_type_constant(c, w, x)?;
}
for x in class_def.ctx_constants.as_ref() {
print_ctx_constant(c, w, x)?;
}
for x in class_def.properties.as_ref() {
print_property(c, w, x)?;
}
for m in class_def.methods.as_ref() {
print_method_def(c, w, m)?;
}
Ok(())
})?;
newline(w)?;
w.write_all(b"}")?;
newline(w)
}
fn print_rules(w: &mut dyn Write, rules: &Slice<'_, Rule<'_>>) -> Result<()> {
let mut first = true;
for rule in rules.as_ref().iter() {
if first {
first = false;
} else {
w.write_all(b" ")?;
}
match rule.kind {
RuleKind::Global => {
w.write_all(b"global")?;
}
RuleKind::Prefix => {
write_bytes!(w, "prefix({})", rule.name.unwrap())?;
}
RuleKind::Exact => {
write_bytes!(w, "exact({})", rule.name.unwrap())?;
}
}
}
Ok(())
}
fn print_named_rules(
w: &mut dyn Write,
name: &str,
rules: Maybe<&Slice<'_, Rule<'_>>>,
) -> Result<()> {
if let Just(v) = rules {
newline(w)?;
write!(w, ".{} [", name)?;
print_rules(w, v)?;
w.write_all(b"] ;")?;
}
Ok(())
}
fn print_module_def<'arena>(
ctx: &Context<'_>,
w: &mut dyn Write,
module_def: &Module<'arena>,
) -> Result<()> {
newline(w)?;
w.write_all(b".module ")?;
print_special_and_user_attrs(
ctx,
w,
module_def.attributes.as_ref(),
&AttrContext::Module,
&Attr::AttrNone,
)?;
w.write_all(module_def.name.as_bstr())?;
w.write_all(b" ")?;
print_span(w, &module_def.span)?;
w.write_all(b" {")?;
print_doc_comment(ctx, w, module_def.doc_comment.as_ref())?;
print_named_rules(w, "exports", module_def.exports.as_ref())?;
print_named_rules(w, "imports", module_def.imports.as_ref())?;
newline(w)?;
w.write_all(b"}")?;
newline(w)
}
fn print_pos_as_prov_tag(
ctx: &Context<'_>,
w: &mut dyn Write,
loc: Option<&ast_defs::Pos>,
) -> Result<()> {
match loc {
Some(l) if ctx.array_provenance => {
let (line, ..) = l.info_pos();
let filename = l.filename().path(); // consider: should we also show prefix?
let filename = match filename.to_str().unwrap() {
"" => "(unknown hackc filename)",
x => x,
};
write!(
w,
r#"p:i:{};s:{}:\"{}\";"#,
line,
filename.len(),
escaper::escape(filename)
)
}
_ => Ok(()),
}
}
fn print_adata_mapped_argument<F, V>(
ctx: &Context<'_>,
w: &mut dyn Write,
col_type: &str,
loc: Option<&ast_defs::Pos>,
values: &[V],
f: F,
) -> Result<()>
where
F: Fn(&Context<'_>, &mut dyn Write, &V) -> Result<()>,
{
write!(w, "{}:{}:{{", col_type, values.len(),)?;
print_pos_as_prov_tag(ctx, w, loc)?;
for v in values {
f(ctx, w, v)?
}
write!(w, "}}")
}
fn print_adata_collection_argument(
ctx: &Context<'_>,
w: &mut dyn Write,
col_type: &str,
loc: Option<&ast_defs::Pos>,
values: &[TypedValue<'_>],
) -> Result<()> {
print_adata_mapped_argument(ctx, w, col_type, loc, values, print_adata)
}
fn print_adata_dict_collection_argument(
ctx: &Context<'_>,
w: &mut dyn Write,
col_type: &str,
loc: Option<&ast_defs::Pos>,
pairs: &[DictEntry<'_>],
) -> Result<()> {
print_adata_mapped_argument(ctx, w, col_type, loc, pairs, |ctx, w, e| {
print_adata(ctx, w, &e.key)?;
print_adata(ctx, w, &e.value)
})
}
fn print_adata(ctx: &Context<'_>, w: &mut dyn Write, tv: &TypedValue<'_>) -> Result<()> {
match tv {
TypedValue::Uninit => w.write_all(b"uninit"),
TypedValue::Null => w.write_all(b"N;"),
TypedValue::String(s) => {
write_bytes!(
w,
r#"s:{}:\"{}\";"#,
s.len(),
escaper::escape_bstr(s.as_bstr())
)
}
TypedValue::LazyClass(s) => {
write_bytes!(
w,
r#"l:{}:\"{}\";"#,
s.len(),
escaper::escape_bstr(s.as_bstr())
)
}
TypedValue::Float(f) => {
write!(w, "d:{};", float::to_string(f.to_f64()))
}
TypedValue::Int(i) => write!(w, "i:{};", i),
// TODO: The False case seems to sometimes be b:0 and sometimes i:0. Why?
TypedValue::Bool(false) => w.write_all(b"b:0;"),
TypedValue::Bool(true) => w.write_all(b"b:1;"),
TypedValue::Vec(values) => {
print_adata_collection_argument(ctx, w, Adata::VEC_PREFIX, None, values.as_ref())
}
TypedValue::Dict(entries) => {
print_adata_dict_collection_argument(ctx, w, Adata::DICT_PREFIX, None, entries.as_ref())
}
TypedValue::Keyset(values) => {
print_adata_collection_argument(ctx, w, Adata::KEYSET_PREFIX, None, values.as_ref())
}
}
}
fn print_attribute(ctx: &Context<'_>, w: &mut dyn Write, a: &Attribute<'_>) -> Result<()> {
let unescaped = a.name.as_bstr();
let escaped = if a.name.starts_with(b"__") {
Cow::Borrowed(unescaped)
} else {
escaper::escape_bstr(unescaped)
};
write_bytes!(
w,
"\"{}\"(\"\"\"{}:{}:{{",
escaped,
Adata::VEC_PREFIX,
a.arguments.len()
)?;
concat(w, a.arguments, |w, arg| print_adata(ctx, w, arg))?;
w.write_all(b"}\"\"\")")
}
fn print_attributes<'a>(ctx: &Context<'_>, w: &mut dyn Write, al: &[Attribute<'a>]) -> Result<()> {
// Adjust for underscore coming before alphabet
let al = al
.iter()
.sorted_by_key(|a| (!a.name.starts_with(b"__"), a.name));
write_bytes!(
w,
"{}",
fmt_separated_with(" ", al, |w, a| print_attribute(ctx, w, a))
)
}
fn print_file_attributes(ctx: &Context<'_>, w: &mut dyn Write, al: &[Attribute<'_>]) -> Result<()> {
if al.is_empty() {
return Ok(());
}
newline(w)?;
w.write_all(b".file_attributes [")?;
print_attributes(ctx, w, al)?;
w.write_all(b"] ;")?;
newline(w)
}
fn print_module_use(w: &mut dyn Write, m_opt: &Maybe<Str<'_>>) -> Result<()> {
if let Just(m) = m_opt {
newline(w)?;
write_bytes!(w, ".module_use \"{}\";", m)?;
newline(w)?;
}
Ok(())
}
fn is_bareword_char(c: &u8) -> bool {
match *c {
b'_' | b'.' | b'$' | b'\\' => true,
c => c.is_ascii_alphanumeric(),
}
}
fn print_body(
ctx: &Context<'_>,
w: &mut dyn Write,
body: &Body<'_>,
coeffects: &Coeffects<'_>,
dv_labels: &HashSet<Label>,
) -> Result<()> {
print_doc_comment(ctx, w, body.doc_comment.as_ref())?;
if body.is_memoize_wrapper {
ctx.newline(w)?;
w.write_all(b".ismemoizewrapper;")?;
}
if body.is_memoize_wrapper_lsb {
ctx.newline(w)?;
w.write_all(b".ismemoizewrapperlsb;")?;
}
if body.num_iters > 0 {
ctx.newline(w)?;
write!(w, ".numiters {};", body.num_iters)?;
}
if !body.decl_vars.is_empty() {
ctx.newline(w)?;
w.write_all(b".declvars ")?;
concat_by(w, " ", body.decl_vars, |w, var| {
if var.iter().all(is_bareword_char) {
w.write_all(var)
} else {
quotes(w, |w| w.write_all(&escaper::escape_bstr(var.as_bstr())))
}
})?;
w.write_all(b";")?;
}
coeffects::coeffects_to_hhas(ctx, w, coeffects)?;
let local_names: Vec<Str<'_>> = body
.params
.iter()
.map(|param| param.name)
.chain(body.decl_vars.iter().copied())
.collect();
print_instructions(ctx, w, &body.body_instrs, dv_labels, &local_names)
}
fn print_instructions<'a, 'b>(
ctx: &Context<'_>,
w: &mut dyn Write,
instrs: &'b [Instruct<'a>],
dv_labels: &'b HashSet<Label>,
local_names: &'b [Str<'a>],
) -> Result<()> {
let mut ctx = ctx.clone();
for instr in instrs {
match instr {
Instruct::Pseudo(Pseudo::Continue | Pseudo::Break) => {
return Err(Error::fail("Cannot break/continue").into());
}
Instruct::Pseudo(Pseudo::Comment(_)) => {
// indentation = 0
newline(w)?;
print_instr(w, instr, dv_labels, local_names)?;
}
Instruct::Pseudo(Pseudo::Label(_)) => ctx.unblock(w, |c, w| {
c.newline(w)?;
print_instr(w, instr, dv_labels, local_names)
})?,
Instruct::Pseudo(Pseudo::TryCatchBegin) => {
ctx.newline(w)?;
print_instr(w, instr, dv_labels, local_names)?;
ctx.indent_inc();
}
Instruct::Pseudo(Pseudo::TryCatchMiddle) => ctx.unblock(w, |c, w| {
c.newline(w)?;
print_instr(w, instr, dv_labels, local_names)
})?,
Instruct::Pseudo(Pseudo::TryCatchEnd) => {
ctx.indent_dec();
ctx.newline(w)?;
print_instr(w, instr, dv_labels, local_names)?;
}
_ => {
ctx.newline(w)?;
print_instr(w, instr, dv_labels, local_names)?;
}
}
}
Ok(())
}
pub(crate) fn print_fcall_args(
w: &mut dyn Write,
args @ FCallArgs {
flags,
num_args,
num_rets,
inouts,
readonly,
async_eager_target,
context,
}: &FCallArgs<'_>,
dv_labels: &HashSet<Label>,
) -> Result<()> {
angle(w, |w| {
let flags = hhvm_hhbc_defs_ffi::ffi::fcall_flags_to_string_ffi(*flags);
write!(w, "{}", flags)
})?;
w.write_all(b" ")?;
print_int(w, num_args)?;
w.write_all(b" ")?;
print_int(w, num_rets)?;
w.write_all(b" ")?;
quotes(w, |w| {
concat_by(w, "", inouts, |w, i| {
w.write_all(if *i { b"1" } else { b"0" })
})
})?;
w.write_all(b" ")?;
quotes(w, |w| {
concat_by(w, "", readonly, |w, i| {
w.write_all(if *i { b"1" } else { b"0" })
})
})?;
w.write_all(b" ")?;
if args.has_async_eager_target() {
print_label(w, async_eager_target, dv_labels)?;
} else {
w.write_all(b"-")?;
}
w.write_all(b" ")?;
quotes(w, |w| w.write_all(context))
}
fn print_pseudo(w: &mut dyn Write, instr: &Pseudo<'_>, dv_labels: &HashSet<Label>) -> Result<()> {
match instr {
Pseudo::TypedValue(_) => Err(Error::fail("print_lit_const: TypedValue").into()),
Pseudo::Label(l) => {
print_label(w, l, dv_labels)?;
w.write_all(b":")
}
Pseudo::TryCatchBegin => w.write_all(b".try {"),
Pseudo::TryCatchMiddle => w.write_all(b"} .catch {"),
Pseudo::TryCatchEnd => w.write_all(b"}"),
Pseudo::Comment(s) => write_bytes!(w, "# {}", s),
Pseudo::SrcLoc(p) => write!(
w,
".srcloc {}:{},{}:{};",
p.line_begin, p.col_begin, p.line_end, p.col_end
),
Pseudo::Break | Pseudo::Continue => Err(Error::fail("invalid instruction").into()),
}
}
fn print_instr<'a, 'b>(
w: &mut dyn Write,
instr: &'b Instruct<'a>,
dv_labels: &'b HashSet<Label>,
local_names: &'b [Str<'a>],
) -> Result<()> {
match instr {
Instruct::Opcode(opcode) => {
crate::print_opcode::PrintOpcode::new(opcode, dv_labels, local_names).print_opcode(w)
}
Instruct::Pseudo(pseudo) => print_pseudo(w, pseudo, dv_labels),
}
}
/// Build a set containing the labels for param default-value initializers
/// so they can be formatted as `DV123` instead of `L123`.
fn find_dv_labels(params: &[Param<'_>]) -> HashSet<Label> {
params
.iter()
.filter_map(|param| match ¶m.default_value {
Just(dv) => Some(dv.label),
_ => None,
})
.collect()
}
fn print_params<'arena>(
ctx: &Context<'_>,
w: &mut dyn Write,
params: &[Param<'arena>],
dv_labels: &HashSet<Label>,
) -> Result<()> {
paren(w, |w| {
concat_by(w, ", ", params, |w, i| print_param(ctx, w, i, dv_labels))
})
}
fn print_param<'arena>(
ctx: &Context<'_>,
w: &mut dyn Write,
param: &Param<'arena>,
dv_labels: &HashSet<Label>,
) -> Result<()> {
print_param_user_attributes(ctx, w, param)?;
write_if!(param.is_inout, w, "inout ")?;
write_if!(param.is_readonly, w, "readonly ")?;
write_if!(param.is_variadic, w, "...")?;
option(w, param.type_info.as_ref(), |w, ty| {
print_type_info(w, ty)?;
w.write_all(b" ")
})?;
w.write_all(¶m.name)?;
option(
w,
param.default_value.as_ref(),
|w, dv: &DefaultValue<'_>| print_param_default_value(w, dv.label, dv.expr, dv_labels),
)
}
fn print_param_default_value<'arena>(
w: &mut dyn Write,
label: Label,
php_code: Str<'arena>,
dv_labels: &HashSet<Label>,
) -> Result<()> {
w.write_all(b" = ")?;
print_label(w, &label, dv_labels)?;
paren(w, |w| {
triple_quotes(w, |w| {
w.write_all(&escaper::escape_bstr(php_code.as_bstr()))
})
})
}
pub(crate) fn print_label(
w: &mut dyn Write,
label: &Label,
dv_labels: &HashSet<Label>,
) -> Result<()> {
let prefix = if dv_labels.contains(label) { "DV" } else { "L" };
write!(w, "{}{}", prefix, label.0)
}
pub(crate) fn print_int<T: std::fmt::Display>(w: &mut dyn Write, i: T) -> Result<()> {
write!(w, "{}", i)
}
fn print_param_user_attributes(
ctx: &Context<'_>,
w: &mut dyn Write,
param: &Param<'_>,
) -> Result<()> {
match param.user_attributes.as_ref()[..] {
[] => Ok(()),
_ => square(w, |w| print_attributes(ctx, w, ¶m.user_attributes)),
}
}
fn print_span(
w: &mut dyn Write,
&Span {
line_begin,
line_end,
}: &Span,
) -> Result<()> {
write!(w, "({},{})", line_begin, line_end)
}
fn print_special_and_user_attrs(
ctx: &Context<'_>,
w: &mut dyn Write,
users: &[Attribute<'_>],
attr_ctx: &AttrContext,
attrs: &Attr,
) -> Result<()> {
if !users.is_empty() || !attrs.is_empty() {
square(w, |w| {
write!(w, "{}", attrs_to_string_ffi(*attr_ctx, *attrs))?;
if !users.is_empty() {
w.write_all(b" ")?;
}
print_attributes(ctx, w, users)
})?;
w.write_all(b" ")?;
}
Ok(())
}
fn print_upper_bounds<'arena>(
w: &mut dyn Write,
ubs: impl AsRef<[UpperBound<'arena>]>,
) -> Result<()> {
braces(w, |w| concat_by(w, ", ", ubs, print_upper_bound))
}
fn print_upper_bound<'arena>(w: &mut dyn Write, ub: &UpperBound<'arena>) -> Result<()> {
paren(w, |w| {
write_bytes!(w, "{} as ", ub.name)?;
concat_by(w, ", ", ub.bounds, print_type_info)
})
}
fn print_upper_bounds_<'arena>(
w: &mut dyn Write,
ubs: impl AsRef<[UpperBound<'arena>]>,
) -> Result<()> {
braces(w, |w| concat_by(w, ", ", ubs, print_upper_bound_))
}
fn print_upper_bound_<'arena>(w: &mut dyn Write, ub: &UpperBound<'arena>) -> Result<()> {
paren(w, |w| {
write_bytes!(w, "{} as ", ub.name)?;
concat_by(w, ", ", ub.bounds, print_type_info)
})
}
fn print_type_info(w: &mut dyn Write, ti: &TypeInfo<'_>) -> Result<()> {
print_type_info_(w, false, ti)
}
fn print_type_flags(w: &mut dyn Write, flag: TypeConstraintFlags) -> Result<()> {
write!(w, "{}", type_flags_to_string_ffi(flag))
}
fn print_type_info_(w: &mut dyn Write, is_enum: bool, ti: &TypeInfo<'_>) -> Result<()> {
let print_quote_str = |w: &mut dyn Write, opt: Option<&str>| {
option_or(
w,
opt,
|w, s: &str| quotes(w, |w| w.write_all(escaper::escape(s).as_bytes())),
"N",
)
};
angle(w, |w| {
print_quote_str(w, ti.user_type.map(|n| n.unsafe_as_str()).into())?;
w.write_all(b" ")?;
if !is_enum {
print_quote_str(w, ti.type_constraint.name.map(|n| n.unsafe_as_str()).into())?;
w.write_all(b" ")?;
}
print_type_flags(w, ti.type_constraint.flags)
})
}
// T125888411: User type not printed
// T126391106: also -- no name and "" as a name both print as "", which is ambiguous for the assembler
fn print_typedef_info(w: &mut dyn Write, ti: &TypeInfo<'_>) -> Result<()> {
angle(w, |w| {
write_bytes!(
w,
r#""{}""#,
escaper::escape_bstr(
ti.type_constraint
.name
.as_ref()
.unwrap_or(&Default::default())
.as_bstr()
)
)?;
let flags = ti.type_constraint.flags & TypeConstraintFlags::Nullable;
if !flags.is_empty() {
wrap_by(w, " ", |w| print_type_flags(w, flags))?;
}
Ok(())
})
}
fn print_typedef_info_union(w: &mut dyn Write, tis: &[TypeInfo<'_>]) -> Result<()> {
concat_by(w, ",", tis, print_typedef_info)
}
fn print_extends(w: &mut dyn Write, base: Option<&str>) -> Result<()> {
match base {
None => Ok(()),
Some(b) => concat_str_by(w, " ", [" extends", b]),
}
}
pub fn external_print_unit(
ctx: &Context<'_>,
w: &mut dyn std::io::Write,
prog: &Unit<'_>,
) -> std::result::Result<(), Error> {
print_unit(ctx, w, prog).map_err(write::into_error)?;
w.flush().map_err(write::into_error)?;
Ok(())
} |
Rust | hhvm/hphp/hack/src/hackc/bytecode_printer/print_opcode.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::io::Error;
use std::io::ErrorKind;
use std::io::Result;
use std::io::Write;
use ffi::Str;
use hash::HashSet;
use hhbc::AdataId;
use hhbc::BareThisOp;
use hhbc::ClassName;
use hhbc::CollectionType;
use hhbc::ConstName;
use hhbc::ContCheckOp;
use hhbc::Dummy;
use hhbc::FCallArgs;
use hhbc::FatalOp;
use hhbc::FloatBits;
use hhbc::FunctionName;
use hhbc::IncDecOp;
use hhbc::InitPropOp;
use hhbc::IsLogAsDynamicCallOp;
use hhbc::IsTypeOp;
use hhbc::IterArgs;
use hhbc::IterId;
use hhbc::Label;
use hhbc::Local;
use hhbc::LocalRange;
use hhbc::MOpMode;
use hhbc::MemberKey;
use hhbc::MethodName;
use hhbc::NumParams;
use hhbc::OODeclExistsOp;
use hhbc::ObjMethodOp;
use hhbc::Opcode;
use hhbc::PropName;
use hhbc::QueryMOp;
use hhbc::ReadonlyOp;
use hhbc::SetOpOp;
use hhbc::SetRangeOp;
use hhbc::SilenceOp;
use hhbc::SpecialClsRef;
use hhbc::StackIndex;
use hhbc::SwitchKind;
use hhbc::TypeStructResolveOp;
use hhbc_string_utils::float;
use print_opcode::PrintOpcode;
use print_opcode::PrintOpcodeTypes;
use crate::print;
#[derive(PrintOpcode)]
#[print_opcode(override = "SSwitch")]
pub(crate) struct PrintOpcode<'a, 'b> {
pub(crate) opcode: &'b Opcode<'a>,
pub(crate) dv_labels: &'b HashSet<Label>,
pub(crate) local_names: &'b [Str<'a>],
}
impl<'a, 'b> PrintOpcode<'a, 'b> {
pub(crate) fn new(
opcode: &'b Opcode<'a>,
dv_labels: &'b HashSet<Label>,
local_names: &'b [Str<'a>],
) -> Self {
Self {
opcode,
dv_labels,
local_names,
}
}
fn get_opcode(&self) -> &'b Opcode<'a> {
self.opcode
}
fn print_branch_labels(&self, w: &mut dyn Write, labels: &[Label]) -> Result<()> {
w.write_all(b"<")?;
for (i, label) in labels.iter().enumerate() {
if i != 0 {
w.write_all(b" ")?;
}
self.print_label(w, label)?;
}
w.write_all(b">")
}
fn print_fcall_args(&self, w: &mut dyn Write, args: &FCallArgs<'_>) -> Result<()> {
print::print_fcall_args(w, args, self.dv_labels)
}
fn print_label(&self, w: &mut dyn Write, label: &Label) -> Result<()> {
print::print_label(w, label, self.dv_labels)
}
fn print_label2(&self, w: &mut dyn Write, [label1, label2]: &[Label; 2]) -> Result<()> {
self.print_label(w, label1)?;
w.write_all(b" ")?;
self.print_label(w, label2)
}
fn print_local(&self, w: &mut dyn Write, local: &Local) -> Result<()> {
print_local(w, local, self.local_names)
}
fn print_iter_args(&self, w: &mut dyn Write, iter_args: &IterArgs) -> Result<()> {
print_iter_args(w, iter_args, self.local_names)
}
fn print_member_key(&self, w: &mut dyn Write, member_key: &MemberKey<'_>) -> Result<()> {
print_member_key(w, member_key, self.local_names)
}
fn print_s_switch(
&self,
w: &mut dyn Write,
cases: &[Str<'_>],
targets: &[Label],
_dummy_imm: &Dummy,
) -> Result<()> {
if cases.len() != targets.len() {
return Err(Error::new(
ErrorKind::Other,
"sswitch cases and targets must match length",
));
}
let mut iter = cases.iter().zip(targets).rev();
let (_, last_target) = if let Some(last) = iter.next() {
last
} else {
return Err(Error::new(
ErrorKind::Other,
"sswitch should have at least one case",
));
};
let iter = iter.rev();
w.write_all(b"SSwitch <")?;
for (case, target) in iter {
print_quoted_str(w, case)?;
w.write_all(b":")?;
self.print_label(w, target)?;
w.write_all(b" ")?;
}
w.write_all(b"-:")?;
self.print_label(w, last_target)?;
w.write_all(b">")
}
}
macro_rules! print_with_display {
($func_name: ident, $ty: ty) => {
fn $func_name(w: &mut dyn Write, arg: &$ty) -> Result<()> {
write!(w, "{}", arg)
}
};
}
print_with_display!(print_num_params, NumParams);
print_with_display!(print_stack_index, StackIndex);
macro_rules! print_with_debug {
($vis: vis $func_name: ident, $ty: ty) => {
$vis fn $func_name(w: &mut dyn Write, arg: &$ty) -> Result<()> {
write!(w, "{:?}", arg)
}
};
}
print_with_debug!(print_bare_this_op, BareThisOp);
print_with_debug!(print_collection_type, CollectionType);
print_with_debug!(print_cont_check_op, ContCheckOp);
print_with_debug!(print_fatal_op, FatalOp);
print_with_debug!(print_inc_dec_op, IncDecOp);
print_with_debug!(print_init_prop_op, InitPropOp);
print_with_debug!(print_is_log_as_dynamic_call_op, IsLogAsDynamicCallOp);
print_with_debug!(print_is_type_op, IsTypeOp);
print_with_debug!(print_m_op_mode, MOpMode);
print_with_debug!(print_obj_method_op, ObjMethodOp);
print_with_debug!(print_oo_decl_exists_op, OODeclExistsOp);
print_with_debug!(print_query_m_op, QueryMOp);
print_with_debug!(print_readonly_op, ReadonlyOp);
print_with_debug!(print_set_op_op, SetOpOp);
print_with_debug!(print_set_range_op, SetRangeOp);
print_with_debug!(print_silence_op, SilenceOp);
print_with_debug!(print_special_cls_ref, SpecialClsRef);
print_with_debug!(print_switch_kind, SwitchKind);
print_with_debug!(print_type_struct_resolve_op, TypeStructResolveOp);
fn print_adata_id(w: &mut dyn Write, id: &AdataId<'_>) -> Result<()> {
w.write_all(b"@")?;
print_str(w, &id.as_ffi_str())
}
fn print_class_name(w: &mut dyn Write, id: &ClassName<'_>) -> Result<()> {
print_quoted_str(w, &id.as_ffi_str())
}
fn print_const_name(w: &mut dyn Write, id: &ConstName<'_>) -> Result<()> {
print_quoted_str(w, &id.as_ffi_str())
}
fn print_float(w: &mut dyn Write, d: FloatBits) -> Result<()> {
write!(w, "{}", float::to_string(d.to_f64()))
}
fn print_function_name(w: &mut dyn Write, id: &FunctionName<'_>) -> Result<()> {
print_quoted_str(w, &id.as_ffi_str())
}
fn print_iter_args(w: &mut dyn Write, iter_args: &IterArgs, local_names: &[Str<'_>]) -> Result<()> {
print_iterator_id(w, &iter_args.iter_id)?;
if iter_args.key_id.is_valid() {
w.write_all(b" K:")?;
print_local(w, &iter_args.key_id, local_names)?;
} else {
w.write_all(b" NK")?;
}
w.write_all(b" V:")?;
print_local(w, &iter_args.val_id, local_names)
}
fn print_iterator_id(w: &mut dyn Write, i: &IterId) -> Result<()> {
write!(w, "{}", i)
}
fn print_local(w: &mut dyn Write, local: &Local, local_names: &[Str<'_>]) -> Result<()> {
match local_names.get(local.idx as usize) {
Some(name) => write!(w, "{}", name.unsafe_as_str()),
None => write!(w, "_{}", local.idx),
}
}
fn print_local_range(w: &mut dyn Write, locrange: &LocalRange) -> Result<()> {
write!(w, "L:{}+{}", locrange.start, locrange.len)
}
fn print_member_key(w: &mut dyn Write, mk: &MemberKey<'_>, local_names: &[Str<'_>]) -> Result<()> {
use MemberKey as M;
match mk {
M::EC(si, op) => {
w.write_all(b"EC:")?;
print_stack_index(w, si)?;
w.write_all(b" ")?;
print_readonly_op(w, op)
}
M::EL(local, op) => {
w.write_all(b"EL:")?;
print_local(w, local, local_names)?;
w.write_all(b" ")?;
print_readonly_op(w, op)
}
M::ET(s, op) => {
w.write_all(b"ET:")?;
print_quoted_str(w, s)?;
w.write_all(b" ")?;
print_readonly_op(w, op)
}
M::EI(i, op) => {
write!(w, "EI:{} ", i)?;
print_readonly_op(w, op)
}
M::PC(si, op) => {
w.write_all(b"PC:")?;
print_stack_index(w, si)?;
w.write_all(b" ")?;
print_readonly_op(w, op)
}
M::PL(local, op) => {
w.write_all(b"PL:")?;
print_local(w, local, local_names)?;
w.write_all(b" ")?;
print_readonly_op(w, op)
}
M::PT(id, op) => {
w.write_all(b"PT:")?;
print_prop_name(w, id)?;
w.write_all(b" ")?;
print_readonly_op(w, op)
}
M::QT(id, op) => {
w.write_all(b"QT:")?;
print_prop_name(w, id)?;
w.write_all(b" ")?;
print_readonly_op(w, op)
}
M::W => w.write_all(b"W"),
}
}
fn print_method_name(w: &mut dyn Write, id: &MethodName<'_>) -> Result<()> {
print_quoted_str(w, &id.as_ffi_str())
}
pub(crate) fn print_prop_name(w: &mut dyn Write, id: &PropName<'_>) -> Result<()> {
print_quoted_str(w, &id.as_ffi_str())
}
fn print_quoted_str(w: &mut dyn Write, s: &ffi::Str<'_>) -> Result<()> {
w.write_all(b"\"")?;
w.write_all(&escaper::escape_bstr(s.as_bstr()))?;
w.write_all(b"\"")
}
fn print_shape_fields(w: &mut dyn Write, keys: &[ffi::Str<'_>]) -> Result<()> {
w.write_all(b"<")?;
for (i, key) in keys.iter().enumerate() {
if i != 0 {
w.write_all(b" ")?;
}
print_quoted_str(w, key)?;
}
w.write_all(b">")
}
fn print_str(w: &mut dyn Write, s: &ffi::Str<'_>) -> Result<()> {
use bstr::ByteSlice;
w.write_all(s.as_bytes())
}
impl<'a, 'b> PrintOpcodeTypes for PrintOpcode<'a, 'b> {
type Write = dyn Write + 'b;
type Error = Error;
} |
Rust | hhvm/hphp/hack/src/hackc/bytecode_printer/write.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::cell::Cell;
use std::fmt::Debug;
use std::io;
use std::io::Result;
use std::io::Write;
use thiserror::Error;
use write_bytes::BytesFormatter;
use write_bytes::DisplayBytes;
#[derive(Error, Debug)]
pub enum Error {
#[error("write error: {0:?}")]
WriteError(anyhow::Error),
#[error("a string may contain invalid utf-8")]
InvalidUTF8,
//TODO(hrust): This is a temp error during porting
#[error("NOT_IMPL: {0}")]
NotImpl(String),
#[error("Failed: {0}")]
Fail(String),
}
impl Error {
pub fn fail(s: impl Into<String>) -> Self {
Self::Fail(s.into())
}
}
pub(crate) fn get_embedded_error(e: &io::Error) -> Option<&Error> {
if e.kind() == io::ErrorKind::Other {
if let Some(e) = e.get_ref() {
if e.is::<Error>() {
let err = e.downcast_ref::<Error>();
return err;
}
}
}
None
}
pub(crate) fn into_error(e: io::Error) -> Error {
if e.kind() == io::ErrorKind::Other && e.get_ref().map_or(false, |e| e.is::<Error>()) {
let err: Error = *e.into_inner().unwrap().downcast::<Error>().unwrap();
return err;
}
Error::WriteError(e.into())
}
impl From<Error> for std::io::Error {
fn from(e: Error) -> Self {
io::Error::new(io::ErrorKind::Other, e)
}
}
pub(crate) fn newline(w: &mut dyn Write) -> Result<()> {
w.write_all(b"\n")?;
Ok(())
}
pub(crate) fn wrap_by_<F>(w: &mut dyn Write, s: &str, e: &str, f: F) -> Result<()>
where
F: FnOnce(&mut dyn Write) -> Result<()>,
{
w.write_all(s.as_bytes())?;
f(w)?;
w.write_all(e.as_bytes())
}
pub(crate) fn wrap_by<F>(w: &mut dyn Write, s: &str, f: F) -> Result<()>
where
F: FnOnce(&mut dyn Write) -> Result<()>,
{
wrap_by_(w, s, s, f)
}
macro_rules! wrap_by {
($name:ident, $left:expr, $right:expr) => {
pub(crate) fn $name<F>(w: &mut dyn Write, f: F) -> Result<()>
where
F: FnOnce(&mut dyn Write) -> Result<()>,
{
$crate::write::wrap_by_(w, $left, $right, f)
}
};
}
wrap_by!(braces, "{", "}");
wrap_by!(paren, "(", ")");
wrap_by!(quotes, "\"", "\"");
wrap_by!(triple_quotes, "\"\"\"", "\"\"\"");
wrap_by!(angle, "<", ">");
wrap_by!(square, "[", "]");
pub(crate) fn concat_str<I: AsRef<str>>(w: &mut dyn Write, ss: impl AsRef<[I]>) -> Result<()> {
concat(w, ss, |w, s| {
w.write_all(s.as_ref().as_bytes())?;
Ok(())
})
}
pub(crate) fn concat_str_by<I: AsRef<str>>(
w: &mut dyn Write,
sep: impl AsRef<str>,
ss: impl AsRef<[I]>,
) -> Result<()> {
concat_by(w, sep, ss, |w, s| {
w.write_all(s.as_ref().as_bytes())?;
Ok(())
})
}
pub(crate) fn concat<T, F>(w: &mut dyn Write, items: impl AsRef<[T]>, f: F) -> Result<()>
where
F: FnMut(&mut dyn Write, &T) -> Result<()>,
{
concat_by(w, "", items, f)
}
pub(crate) fn concat_by<T, F>(
w: &mut dyn Write,
sep: impl AsRef<str>,
items: impl AsRef<[T]>,
mut f: F,
) -> Result<()>
where
F: FnMut(&mut dyn Write, &T) -> Result<()>,
{
let mut first = true;
let sep = sep.as_ref();
Ok(for i in items.as_ref() {
if first {
first = false;
} else {
w.write_all(sep.as_bytes())?;
}
f(w, i)?;
})
}
pub(crate) fn option<T, F>(w: &mut dyn Write, i: impl Into<Option<T>>, mut f: F) -> Result<()>
where
F: FnMut(&mut dyn Write, T) -> Result<()>,
{
match i.into() {
None => Ok(()),
Some(i) => f(w, i),
}
}
pub(crate) fn option_or<T, F>(
w: &mut dyn Write,
i: impl Into<Option<T>>,
f: F,
default: impl AsRef<str>,
) -> Result<()>
where
F: Fn(&mut dyn Write, T) -> Result<()>,
{
match i.into() {
None => w.write_all(default.as_ref().as_bytes()),
Some(i) => f(w, i),
}
}
pub(crate) struct FmtSeparated<'a, T, I>
where
T: DisplayBytes,
I: Iterator<Item = T>,
{
items: Cell<Option<I>>,
sep: &'a str,
}
impl<'a, Item, I> DisplayBytes for FmtSeparated<'a, Item, I>
where
Item: DisplayBytes,
I: Iterator<Item = Item>,
{
fn fmt(&self, f: &mut BytesFormatter<'_>) -> Result<()> {
let mut items = self.items.take().unwrap();
if let Some(item) = items.next() {
item.fmt(f)?;
}
for item in items {
f.write_all(self.sep.as_bytes())?;
item.fmt(f)?;
}
Ok(())
}
}
pub(crate) fn fmt_separated<'a, Item, I, II>(sep: &'a str, items: II) -> FmtSeparated<'a, Item, I>
where
Item: DisplayBytes,
I: Iterator<Item = Item>,
II: IntoIterator<Item = Item, IntoIter = I>,
{
FmtSeparated {
items: Cell::new(Some(items.into_iter())),
sep,
}
}
pub(crate) struct FmtSeparatedWith<'a, Item, I, F>
where
I: Iterator<Item = Item>,
F: Fn(&mut BytesFormatter<'_>, Item) -> Result<()>,
{
items: Cell<Option<I>>,
sep: &'a str,
with: F,
}
impl<'a, Item, I, F> DisplayBytes for FmtSeparatedWith<'a, Item, I, F>
where
I: Iterator<Item = Item>,
F: Fn(&mut BytesFormatter<'_>, Item) -> Result<()>,
{
fn fmt(&self, f: &mut BytesFormatter<'_>) -> Result<()> {
let mut items = self.items.take().unwrap();
if let Some(item) = items.next() {
(self.with)(f, item)?;
}
for item in items {
f.write_all(self.sep.as_bytes())?;
(self.with)(f, item)?;
}
Ok(())
}
}
pub(crate) fn fmt_separated_with<'a, Item, I, F, II>(
sep: &'a str,
items: II,
with: F,
) -> FmtSeparatedWith<'a, Item, I, F>
where
I: Iterator<Item = Item>,
F: Fn(&mut BytesFormatter<'_>, Item) -> Result<()>,
II: IntoIterator<Item = Item, IntoIter = I>,
{
FmtSeparatedWith {
items: Cell::new(Some(items.into_iter())),
sep,
with,
}
}
#[test]
fn test_fmt_separated() -> Result<()> {
use bstr::BStr;
use write_bytes::format_bytes;
use write_bytes::write_bytes;
let v: Vec<&str> = vec!["a", "b"];
assert_eq!(
format_bytes!("{}", fmt_separated(" ", v)),
<&BStr>::from("a b")
);
let v: Vec<&BStr> = vec!["a".into(), "b".into()];
assert_eq!(
format_bytes!("{}", fmt_separated(" ", v)),
<&BStr>::from("a b")
);
let v1: Vec<&BStr> = vec!["a".into(), "b".into()];
let v2: Vec<i64> = vec![1, 2];
let it = v1
.iter()
.map(|i: &&BStr| -> &dyn DisplayBytes { i })
.chain(v2.iter().map(|i: &i64| -> &dyn DisplayBytes { i }));
assert_eq!(
format_bytes!("{}", fmt_separated(" ", it),),
<&BStr>::from("a b 1 2")
);
Ok(())
} |
Rust | hhvm/hphp/hack/src/hackc/bytecode_printer/print_opcode/lib.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
pub use print_opcode_impl::PrintOpcodeTypes;
pub use print_opcode_macro::PrintOpcode; |
Rust | hhvm/hphp/hack/src/hackc/bytecode_printer/print_opcode/print_opcode_impl.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use hash::HashSet;
use hhbc_gen::ImmType;
use hhbc_gen::InstrFlags;
use hhbc_gen::OpcodeData;
use proc_macro2::Ident;
use proc_macro2::Span;
use proc_macro2::TokenStream;
use quote::quote;
use quote::ToTokens;
use syn::spanned::Spanned;
use syn::DeriveInput;
use syn::Error;
use syn::Lit;
use syn::LitByteStr;
use syn::LitStr;
use syn::Meta;
use syn::MetaList;
use syn::MetaNameValue;
use syn::NestedMeta;
use syn::Result;
// ----------------------------------------------------------------------------
pub fn build_print_opcode(input: TokenStream, opcodes: &[OpcodeData]) -> Result<TokenStream> {
let input = syn::parse2::<DeriveInput>(input)?;
let struct_name = &input.ident;
let attributes = Attributes::from_derive_input(&input)?;
let mut body = Vec::new();
for opcode in opcodes {
// Op1 { some, parameters } => write!("op1 {} {}", some, parameters),
let variant_name = Ident::new(opcode.name, Span::call_site());
let symbol = {
let mut name = opcode.name.to_string();
if !opcode.immediates.is_empty() {
name.push(' ');
}
LitByteStr::new(name.as_bytes(), Span::call_site())
};
let is_struct = opcode.flags.contains(InstrFlags::AS_STRUCT);
let is_override = attributes.overrides.contains(opcode.name);
let parameters: Vec<Ident> = opcode
.immediates
.iter()
.map(|(name, _)| Ident::new(name, Span::call_site()))
.collect();
let input_parameters = if parameters.is_empty() {
TokenStream::new()
} else if is_struct {
quote!( {#(#parameters),*} )
} else {
quote!( (#(#parameters),*) )
};
if is_override {
let override_call = {
use convert_case::Case;
use convert_case::Casing;
let name = opcode.name.to_case(Case::Snake);
Ident::new(&format!("print_{}", name), Span::call_site())
};
let call_args: Vec<TokenStream> = opcode
.immediates
.iter()
.map(|(name, imm)| convert_call_arg(name, imm))
.collect();
body.push(quote!(
Opcode::#variant_name #input_parameters => {
self.#override_call (w, #(#call_args),* )?;
}
));
} else {
let immediates = {
let mut imms = Vec::new();
for (name, imm) in opcode.immediates.iter() {
imms.push(convert_immediate(name, imm));
imms.push(quote!(w.write_all(b" ")?;));
}
imms.pop();
imms
};
body.push(quote!(
Opcode::#variant_name #input_parameters => {
w.write_all(#symbol)?;
#(#immediates)*
}
));
}
}
let vis = input.vis;
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
let output = quote!(
impl #impl_generics #struct_name #ty_generics #where_clause {
#vis fn print_opcode(
&self,
w: &mut <Self as PrintOpcodeTypes>::Write
) -> std::result::Result<(), <Self as PrintOpcodeTypes>::Error> {
match self.get_opcode() {
#(#body)*
}
Ok(())
}
}
);
Ok(output)
}
trait MetaHelper {
fn expect_list(self) -> Result<MetaList>;
fn expect_name_value(self) -> Result<MetaNameValue>;
}
impl MetaHelper for Meta {
fn expect_list(self) -> Result<MetaList> {
match self {
Meta::Path(_) | Meta::NameValue(_) => Err(Error::new(self.span(), "Expected List")),
Meta::List(list) => Ok(list),
}
}
fn expect_name_value(self) -> Result<MetaNameValue> {
match self {
Meta::Path(_) | Meta::List(_) => {
Err(Error::new(self.span(), "Expected 'Name' = 'Value'"))
}
Meta::NameValue(nv) => Ok(nv),
}
}
}
trait NestedMetaHelper {
fn expect_meta(self) -> Result<Meta>;
}
impl NestedMetaHelper for NestedMeta {
fn expect_meta(self) -> Result<Meta> {
match self {
NestedMeta::Lit(lit) => Err(Error::new(lit.span(), "Unexpected literal")),
NestedMeta::Meta(meta) => Ok(meta),
}
}
}
trait LitHelper {
fn expect_str(self) -> Result<LitStr>;
}
impl LitHelper for Lit {
fn expect_str(self) -> Result<LitStr> {
match self {
Lit::Str(ls) => Ok(ls),
_ => Err(Error::new(self.span(), "Literal string expected")),
}
}
}
struct Attributes {
overrides: HashSet<String>,
}
impl Attributes {
fn from_derive_input(input: &DeriveInput) -> Result<Self> {
let mut result = Attributes {
overrides: Default::default(),
};
for attr in &input.attrs {
if attr.path.is_ident("print_opcode") {
let args = attr.parse_meta()?.expect_list()?;
for nested in args.nested.into_iter() {
let meta = nested.expect_meta()?;
if meta.path().is_ident("override") {
let nv = meta.expect_name_value()?;
let ov = nv.lit.expect_str()?;
result.overrides.insert(ov.value());
} else {
return Err(Error::new(
meta.span(),
format!("Unknown attribute '{:?}'", meta.path()),
));
}
}
}
}
Ok(result)
}
}
fn convert_immediate(name: &str, imm: &ImmType) -> TokenStream {
let name = Ident::new(name, Span::call_site());
match imm {
ImmType::AA => quote!(print_adata_id(w, #name)?;),
ImmType::ARR(_sub_ty) => {
let msg = format!("unsupported '{}'", name);
quote!(todo!(#msg);)
}
ImmType::BA => quote!(self.print_label(w, #name)?;),
ImmType::BA2 => quote!(self.print_label2(w, #name)?;),
ImmType::BLA => quote!(self.print_branch_labels(w, #name.as_ref())?;),
ImmType::DA => quote!(print_float(w, *#name)?;),
ImmType::DUMMY => TokenStream::new(),
ImmType::FCA => quote!(self.print_fcall_args(w, #name)?;),
ImmType::I64A => quote!(write!(w, "{}", #name)?;),
ImmType::IA => quote!(print_iterator_id(w, #name)?;),
ImmType::ILA => quote!(self.print_local(w, #name)?;),
ImmType::ITA => quote!(self.print_iter_args(w, #name)?;),
ImmType::IVA => quote!(write!(w, "{}", #name)?;),
ImmType::KA => quote!(self.print_member_key(w, #name)?;),
ImmType::LA => quote!(self.print_local(w, #name)?;),
ImmType::LAR => quote!(print_local_range(w, #name)?;),
ImmType::NA => panic!("NA is not expected"),
ImmType::NLA => quote!(self.print_local(w, #name)?;),
ImmType::OA(ty) | ImmType::OAL(ty) => {
use convert_case::Case;
use convert_case::Casing;
let handler = Ident::new(
&format!("print_{}", ty.to_case(Case::Snake)),
Span::call_site(),
);
quote!(#handler(w, #name)?;)
}
ImmType::RATA => quote!(print_str(w, #name)?;),
ImmType::SA => quote!(print_quoted_str(w, #name)?;),
ImmType::SLA => quote!(print_switch_labels(w, #name)?;),
ImmType::VSA => quote!(print_shape_fields(w, #name)?;),
}
}
fn convert_call_arg(name: &str, imm: &ImmType) -> TokenStream {
let name = Ident::new(name, Span::call_site());
match imm {
ImmType::AA
| ImmType::BA
| ImmType::BA2
| ImmType::DA
| ImmType::DUMMY
| ImmType::FCA
| ImmType::I64A
| ImmType::IA
| ImmType::ILA
| ImmType::ITA
| ImmType::IVA
| ImmType::KA
| ImmType::LA
| ImmType::LAR
| ImmType::NLA
| ImmType::RATA
| ImmType::SA
| ImmType::SLA
| ImmType::VSA => name.to_token_stream(),
ImmType::ARR(_) | ImmType::BLA | ImmType::OA(_) | ImmType::OAL(_) => {
quote!(#name.as_ref())
}
ImmType::NA => panic!("NA is not expected"),
}
}
pub trait PrintOpcodeTypes {
type Write: ?Sized;
type Error: std::error::Error;
}
#[cfg(test)]
mod tests {
use hhbc_gen as _;
use macro_test_util::assert_pat_eq;
use quote::quote;
use super::*;
#[test]
fn test_basic() {
#[rustfmt::skip]
assert_pat_eq(
build_print_opcode(
quote!(
#[derive(PrintOpcode)]
struct PrintMe<T>(Opcode);
),
&opcode_test_data::test_opcodes(),
),
quote!(
impl<T> PrintMe<T> {
fn print_opcode(
&self,
w: &mut <Self as PrintOpcodeTypes>::Write
) -> std::result::Result<(), <Self as PrintOpcodeTypes>::Error>
{
match self.get_opcode() {
Opcode::TestZeroImm => {
w.write_all(b"TestZeroImm")?;
}
Opcode::TestOneImm(str1) => {
w.write_all(b"TestOneImm ")?;
print_quoted_str(w, str1)?;
}
Opcode::TestTwoImm(str1, str2) => {
w.write_all(b"TestTwoImm ")?;
print_quoted_str(w, str1)?;
w.write_all(b" ")?;
print_quoted_str(w, str2)?;
}
Opcode::TestThreeImm(str1, str2, str3) => {
w.write_all(b"TestThreeImm ")?;
print_quoted_str(w, str1)?;
w.write_all(b" ")?;
print_quoted_str(w, str2)?;
w.write_all(b" ")?;
print_quoted_str(w, str3)?;
}
// -------------------------------------------
Opcode::TestAsStruct { str1, str2 } => {
w.write_all(b"TestAsStruct ")?;
print_quoted_str(w, str1)?;
w.write_all(b" ")?;
print_quoted_str(w, str2)?;
}
// -------------------------------------------
Opcode::TestAA(arr1) => {
w.write_all(b"TestAA ")?;
print_adata_id(w, arr1)?;
}
Opcode::TestARR(arr1) => {
w.write_all(b"TestARR ")?;
todo!("unsupported 'arr1'");
}
Opcode::TestBA(target1) => {
w.write_all(b"TestBA ")?;
self.print_label(w, target1)?;
}
Opcode::TestBA2(target1) => {
w.write_all(b"TestBA2 ")?;
self.print_label2(w, target1)?;
}
Opcode::TestBLA(targets) => {
w.write_all(b"TestBLA ")?;
self.print_branch_labels(w, targets.as_ref())?;
}
Opcode::TestDA(dbl1) => {
w.write_all(b"TestDA ")?;
print_float(w, *dbl1)?;
}
Opcode::TestFCA(fca) => {
w.write_all(b"TestFCA ")?;
self.print_fcall_args(w, fca)?;
}
Opcode::TestI64A(arg1) => {
w.write_all(b"TestI64A ")?;
write!(w, "{}", arg1)?;
}
Opcode::TestIA(iter1) => {
w.write_all(b"TestIA ")?;
print_iterator_id(w, iter1)?;
}
Opcode::TestILA(loc1) => {
w.write_all(b"TestILA ")?;
self.print_local(w, loc1)?;
}
Opcode::TestITA(ita) => {
w.write_all(b"TestITA ")?;
self.print_iter_args(w, ita)?;
}
Opcode::TestIVA(arg1) => {
w.write_all(b"TestIVA ")?;
write!(w, "{}", arg1)?;
}
Opcode::TestKA(mkey) => {
w.write_all(b"TestKA ")?;
self.print_member_key(w, mkey)?;
}
Opcode::TestLA(loc1) => {
w.write_all(b"TestLA ")?;
self.print_local(w, loc1)?;
}
Opcode::TestLAR(locrange) => {
w.write_all(b"TestLAR ")?;
print_local_range(w, locrange)?;
}
Opcode::TestNLA(nloc1) => {
w.write_all(b"TestNLA ")?;
self.print_local(w, nloc1)?;
}
Opcode::TestOA(subop1) => {
w.write_all(b"TestOA ")?;
print_oa_sub_type(w, subop1)?;
}
Opcode::TestOAL(subop1) => {
w.write_all(b"TestOAL ")?;
print_oa_sub_type(w, subop1)?;
}
Opcode::TestRATA(rat) => {
w.write_all(b"TestRATA ")?;
print_str(w, rat)?;
}
Opcode::TestSA(str1) => {
w.write_all(b"TestSA ")?;
print_quoted_str(w, str1)?;
}
Opcode::TestSLA(targets) => {
w.write_all(b"TestSLA ")?;
print_switch_labels(w, targets)?;
}
Opcode::TestVSA(keys) => {
w.write_all(b"TestVSA ")?;
print_shape_fields(w, keys)?;
}
}
Ok(())
}
}
),
);
}
} |
Rust | hhvm/hphp/hack/src/hackc/bytecode_printer/print_opcode/print_opcode_macro.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
// ----------------------------------------------------------------------------
/// Emit a formatter to print opcodes.
///
/// Given input that looks like this:
/// ```
/// #[derive(macros::OpcodeDisplay)]
/// struct PrintMe(Opcodes);
/// ```
///
/// This will add an impl for Display that looks something like this:
///
/// ```
/// impl<T> OpcodeDisplay for PrintMe<T> {
/// fn print_opcode(&self, w: &mut Self::Write) -> Result<(), Self::Error> {
/// match self.0 {
/// PrintMe::Jmp(target1) => {
/// write!(w, "Jmp ")?;
/// print_label(w, target1)?;
/// }
/// }
/// }
/// }
/// ```
///
/// See print_opcode_derive::tests::test_basic() for a more detailed example
/// output.
///
#[proc_macro_derive(PrintOpcode, attributes(print_opcode))]
pub fn print_opcode_macro(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
match print_opcode_impl::build_print_opcode(input.into(), hhbc_gen::opcode_data()) {
Ok(res) => res.into(),
Err(err) => err.into_compile_error().into(),
}
} |
TOML | hhvm/hphp/hack/src/hackc/bytecode_printer/print_opcode/cargo/lib/Cargo.toml | # @generated by autocargo
[package]
name = "print_opcode"
version = "0.0.0"
edition = "2021"
[lib]
path = "../../lib.rs"
[dependencies]
print_opcode_impl = { version = "0.0.0", path = "../print_opcode_impl" }
print_opcode_macro = { version = "0.0.0", path = "../print_opcode_macro" } |
TOML | hhvm/hphp/hack/src/hackc/bytecode_printer/print_opcode/cargo/print_opcode_impl/Cargo.toml | # @generated by autocargo
[package]
name = "print_opcode_impl"
version = "0.0.0"
edition = "2021"
[lib]
path = "../../print_opcode_impl.rs"
[dependencies]
convert_case = "0.4.0"
hash = { version = "0.0.0", path = "../../../../../utils/hash" }
hhbc-gen = { version = "0.0.0", path = "../../../../../../../tools/hhbc-gen" }
proc-macro2 = { version = "1.0.64", features = ["span-locations"] }
quote = "1.0.29"
syn = { version = "1.0.109", features = ["extra-traits", "fold", "full", "visit", "visit-mut"] }
[dev-dependencies]
macro_test_util = { version = "0.0.0", path = "../../../../../utils/test/macro_test_util" }
opcode_test_data = { version = "0.0.0", path = "../../../../hhbc/cargo/opcode_test_data" } |
TOML | hhvm/hphp/hack/src/hackc/bytecode_printer/print_opcode/cargo/print_opcode_macro/Cargo.toml | # @generated by autocargo
[package]
name = "print_opcode_macro"
version = "0.0.0"
edition = "2021"
[lib]
path = "../../print_opcode_macro.rs"
test = false
doctest = false
proc-macro = true
[dependencies]
hhbc-gen = { version = "0.0.0", path = "../../../../../../../tools/hhbc-gen" }
print_opcode_impl = { version = "0.0.0", path = "../print_opcode_impl" } |
TOML | hhvm/hphp/hack/src/hackc/cargo/assemble/Cargo.toml | # @generated by autocargo
[package]
name = "assemble"
version = "0.0.0"
edition = "2021"
[lib]
path = "../../assemble/lib.rs"
[dependencies]
anyhow = "1.0.71"
assemble_opcode_macro = { version = "0.0.0", path = "../assemble_opcode_macro" }
bumpalo = { version = "3.11.1", features = ["collections"] }
escaper = { version = "0.0.0", path = "../../../utils/escaper" }
ffi = { version = "0.0.0", path = "../../../utils/ffi" }
hash = { version = "0.0.0", path = "../../../utils/hash" }
hhbc = { version = "0.0.0", path = "../../hhbc/cargo/hhbc" }
hhvm_types_ffi = { version = "0.0.0", path = "../../hhvm_cxx/hhvm_types" }
log = { version = "0.4.17", features = ["kv_unstable", "kv_unstable_std"] }
naming_special_names_rust = { version = "0.0.0", path = "../../../naming" }
newtype = { version = "0.0.0", path = "../../../utils/newtype" }
parse_macro = { version = "0.0.0", path = "../parse_macro" }
stack_depth = { version = "0.0.0", path = "../../utils/cargo/stack_depth" }
strum = { version = "0.24", features = ["derive"] } |
TOML | hhvm/hphp/hack/src/hackc/cargo/assemble_opcode_macro/Cargo.toml | # @generated by autocargo
[package]
name = "assemble_opcode_macro"
version = "0.0.0"
edition = "2021"
[lib]
path = "../../assemble/assemble_opcode_macro.rs"
test = false
doctest = false
proc-macro = true
[dependencies]
hhbc-gen = { version = "0.0.0", path = "../../../../../tools/hhbc-gen" }
itertools = "0.10.3"
proc-macro2 = { version = "1.0.64", features = ["span-locations"] }
quote = "1.0.29"
syn = { version = "1.0.109", features = ["extra-traits", "fold", "full", "visit", "visit-mut"] } |
TOML | hhvm/hphp/hack/src/hackc/cargo/parse_macro/Cargo.toml | # @generated by autocargo
[package]
name = "parse_macro"
version = "0.0.0"
edition = "2021"
[lib]
path = "../../assemble/parse_macro.rs"
test = false
doctest = false
proc-macro = true
[dependencies]
proc-macro-error = "1.0"
proc-macro2 = { version = "1.0.64", features = ["span-locations"] }
quote = "1.0.29" |
Rust | hhvm/hphp/hack/src/hackc/cli/asm.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::fs::File;
use std::io::stdout;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use ::assemble as _;
use anyhow::anyhow;
use anyhow::Result;
use bumpalo::Bump;
use clap::Args;
use parking_lot::Mutex;
use rayon::prelude::*;
use relative_path::RelativePath;
use crate::util::SyncWrite;
use crate::FileOpts;
#[derive(Args, Debug)]
pub struct Opts {
/// Output file. Creates it if necessary
#[clap(short = 'o')]
output_file: Option<PathBuf>,
/// The input hhas file(s) to assemble back to hhbc::Unit
#[command(flatten)]
files: FileOpts,
}
pub fn run(opts: Opts) -> Result<()> {
let writer: SyncWrite = match &opts.output_file {
None => Mutex::new(Box::new(stdout())),
Some(output_file) => Mutex::new(Box::new(File::create(output_file)?)),
};
let files = opts.files.gather_input_files()?;
files
.into_par_iter()
.map(|path| process_one_file(&path, &writer))
.collect::<Vec<_>>()
.into_iter()
.collect()
}
/// Assemble the hhas in a given file to a hhbc::Unit. Then use bytecode printer
/// to write the hhas representation of that HCU to output.
pub fn process_one_file(f: &Path, w: &SyncWrite) -> Result<()> {
let alloc = Bump::default();
let (hcu, fp) = assemble::assemble(&alloc, f)?;
let filepath = RelativePath::make(relative_path::Prefix::Dummy, fp);
let ctxt = bytecode_printer::Context::new(Some(&filepath), false);
let mut output = Vec::new();
match bytecode_printer::print_unit(&ctxt, &mut output, &hcu) {
Err(e) => {
eprintln!("Error bytecode_printing file {}: {}", f.display(), e);
Err(anyhow!("bytecode_printer problem"))
}
Ok(_) => {
w.lock().write_all(&output)?;
Ok(())
}
}
} |
Rust | hhvm/hphp/hack/src/hackc/cli/asm_ir.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::fs::File;
use std::io::stdout;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use ::assemble as _;
use anyhow::anyhow;
use anyhow::Result;
use bumpalo::Bump;
use clap::Args;
use parking_lot::Mutex;
use rayon::prelude::*;
use crate::util::SyncWrite;
use crate::FileOpts;
#[derive(Args, Debug)]
pub struct Opts {
/// Output file. Creates it if necessary
#[clap(short = 'o')]
output_file: Option<PathBuf>,
/// The input hhas file(s) to assemble back to ir::Unit
#[command(flatten)]
files: FileOpts,
}
pub fn run(opts: Opts) -> Result<()> {
let writer: SyncWrite = match &opts.output_file {
None => Mutex::new(Box::new(stdout())),
Some(output_file) => Mutex::new(Box::new(File::create(output_file)?)),
};
let files = opts.files.gather_input_files()?;
files
.into_par_iter()
.map(|path| process_one_file(&path, &writer))
.collect::<Vec<_>>()
.into_iter()
.collect()
}
/// Assemble the hhas in a given file to a hhbc::Unit. Then use bytecode printer
/// to write the hhas representation of that HCU to output.
pub fn process_one_file(f: &Path, w: &SyncWrite) -> Result<()> {
let alloc = Bump::default();
let strings = Arc::new(ir::StringInterner::default());
let unit = ir::assemble::unit_from_path(f, Arc::clone(&strings), &alloc)?;
let mut output = String::new();
match ir::print::print_unit(&mut output, &unit, false) {
Err(e) => {
eprintln!("Error printing file {}: {}", f.display(), e);
Err(anyhow!("ir::print problem"))
}
Ok(_) => {
w.lock().write_all(output.as_bytes())?;
Ok(())
}
}
} |
Rust | hhvm/hphp/hack/src/hackc/cli/cmp_ir.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use ffi::Str;
use ir::class::Requirement;
use ir::func::DefaultValue;
use ir::func::ExFrame;
use ir::instr::BaseOp;
use ir::instr::FinalOp;
use ir::instr::Hhbc;
use ir::instr::IntermediateOp;
use ir::instr::IteratorArgs;
use ir::instr::MemberKey;
use ir::instr::MemberOp;
use ir::instr::Special;
use ir::instr::Terminator;
use ir::unit::SymbolRefs;
// This is reasonable because if we compare everything then we'll end up pulling
// in everything...
use ir::*;
use crate::cmp_unit::cmp_eq;
use crate::cmp_unit::cmp_map_t;
use crate::cmp_unit::cmp_option;
use crate::cmp_unit::cmp_slice;
use crate::cmp_unit::CmpContext;
use crate::cmp_unit::CmpError;
use crate::cmp_unit::MapName;
use crate::cmp_unit::Result;
macro_rules! bail {
($msg:literal $(,)?) => {
return Err(CmpError::error(format!($msg)))
};
($err:expr $(,)?) => {
return Err(CmpError::error(format!($err)))
};
($fmt:expr, $($arg:tt)*) => {
return Err(CmpError::error(format!($fmt, $($arg)*)))
};
}
pub(crate) fn cmp_ir(a: &Unit<'_>, b: &Unit<'_>) -> Result {
cmp_unit(a, b).with_raw(|| "unit".to_string())
}
fn cmp_attribute(
(a, a_strings): (&Attribute, &StringInterner),
(b, b_strings): (&Attribute, &StringInterner),
) -> Result {
let cmp_id = |a: UnitBytesId, b: UnitBytesId| cmp_id((a, a_strings), (b, b_strings));
cmp_id(a.name.id, b.name.id).qualified("name")?;
cmp_slice(
a.arguments.iter().map(|a| (a, a_strings)),
b.arguments.iter().map(|b| (b, b_strings)),
cmp_typed_value,
)
.qualified("arguments")?;
Ok(())
}
fn cmp_attributes(
(a, a_strings): (&[Attribute], &StringInterner),
(b, b_strings): (&[Attribute], &StringInterner),
) -> Result {
cmp_map_t(
a.iter().map(|a| (a, a_strings)),
b.iter().map(|b| (b, b_strings)),
cmp_attribute,
)
}
fn cmp_block(a_block: &Block, b_block: &Block) -> Result {
cmp_eq(a_block.params.len(), b_block.params.len()).qualified("params.len")?;
cmp_eq(a_block.iids.len(), b_block.iids.len()).qualified("iids.len")?;
cmp_option(
a_block.pname_hint.as_ref(),
b_block.pname_hint.as_ref(),
cmp_eq,
)
.qualified("pname_hint")?;
cmp_eq(a_block.tcid, b_block.tcid).qualified("tcid")?;
cmp_slice(&a_block.iids, &b_block.iids, cmp_eq).qualified("iids")?;
Ok(())
}
fn cmp_cc_reified(a: &CcReified<'_>, b: &CcReified<'_>) -> Result {
let CcReified {
is_class: a_is_class,
index: a_index,
types: a_types,
} = a;
let CcReified {
is_class: b_is_class,
index: b_index,
types: b_types,
} = b;
cmp_eq(a_is_class, b_is_class).qualified("is_class")?;
cmp_eq(a_index, b_index).qualified("index")?;
cmp_slice(a_types, b_types, cmp_eq).qualified("types")?;
Ok(())
}
fn cmp_cc_this(a: &CcThis<'_>, b: &CcThis<'_>) -> Result {
let CcThis { types: a_types } = a;
let CcThis { types: b_types } = b;
cmp_slice(a_types, b_types, cmp_eq).qualified("types")?;
Ok(())
}
fn cmp_class(
(a, a_strings): (&Class<'_>, &StringInterner),
(b, b_strings): (&Class<'_>, &StringInterner),
) -> Result {
let cmp_id = |a: UnitBytesId, b: UnitBytesId| cmp_id((a, a_strings), (b, b_strings));
let Class {
attributes: a_attributes,
base: a_base,
constants: a_constants,
ctx_constants: a_ctx_constants,
doc_comment: a_doc_comment,
enum_type: a_enum_type,
enum_includes: a_enum_includes,
flags: a_flags,
implements: a_implements,
methods: a_methods,
name: a_name,
properties: a_properties,
requirements: a_requirements,
src_loc: a_src_loc,
type_constants: a_type_constants,
upper_bounds: a_upper_bounds,
uses: a_uses,
} = a;
let Class {
attributes: b_attributes,
base: b_base,
constants: b_constants,
ctx_constants: b_ctx_constants,
doc_comment: b_doc_comment,
enum_type: b_enum_type,
enum_includes: b_enum_includes,
flags: b_flags,
implements: b_implements,
methods: b_methods,
name: b_name,
properties: b_properties,
requirements: b_requirements,
src_loc: b_src_loc,
type_constants: b_type_constants,
upper_bounds: b_upper_bounds,
uses: b_uses,
} = b;
cmp_attributes((a_attributes, a_strings), (b_attributes, b_strings)).qualified("attributes")?;
cmp_option(a_base.map(|i| i.id), b_base.map(|i| i.id), cmp_id).qualified("base")?;
cmp_map_t(
a_constants.iter().map(|a| (a, a_strings)),
b_constants.iter().map(|b| (b, b_strings)),
cmp_hack_constant,
)
.qualified("constants")?;
cmp_map_t(a_ctx_constants.iter(), b_ctx_constants, cmp_ctx_constant)
.qualified("ctx_constants")?;
cmp_eq(a_doc_comment, b_doc_comment).qualified("doc_comment")?;
cmp_option(
a_enum_type.as_ref().map(|i| (i, a_strings)),
b_enum_type.as_ref().map(|i| (i, b_strings)),
cmp_type_info,
)
.qualified("enum_type")?;
cmp_slice(
a_enum_includes.iter().map(|i| i.id),
b_enum_includes.iter().map(|i| i.id),
cmp_id,
)
.qualified("enum_includes")?;
cmp_eq(a_flags, b_flags).qualified("flags")?;
cmp_slice(
a_implements.iter().map(|i| i.id),
b_implements.iter().map(|i| i.id),
cmp_id,
)
.qualified("implements")?;
cmp_map_t(
a_methods.iter().map(|i| (i, a_strings)),
b_methods.iter().map(|i| (i, b_strings)),
cmp_method,
)
.qualified("methods")?;
cmp_id(a_name.id, b_name.id).qualified("name")?;
cmp_map_t(
a_properties.iter().map(|i| (i, a_strings)),
b_properties.iter().map(|i| (i, b_strings)),
cmp_property,
)
.qualified("properties")?;
cmp_slice(
a_requirements.iter().map(|i| (i, a_strings)),
b_requirements.iter().map(|i| (i, b_strings)),
cmp_requirement,
)
.qualified("requirements")?;
cmp_src_loc((a_src_loc, a_strings), (b_src_loc, b_strings)).qualified("src_loc")?;
cmp_slice(
a_type_constants.iter().map(|i| (i, a_strings)),
b_type_constants.iter().map(|i| (i, b_strings)),
cmp_type_constant,
)
.qualified("type_constants")?;
cmp_slice(
a_upper_bounds.iter().map(|i| (i, a_strings)),
b_upper_bounds.iter().map(|i| (i, b_strings)),
cmp_upper_bounds,
)
.qualified("upper_bounds")?;
cmp_slice(
a_uses.iter().map(|i| i.id),
b_uses.iter().map(|i| i.id),
cmp_id,
)
.qualified("uses")?;
Ok(())
}
fn cmp_coeffects(a: &Coeffects<'_>, b: &Coeffects<'_>) -> Result {
let Coeffects {
static_coeffects: a_static_coeffects,
unenforced_static_coeffects: a_unenforced_static_coeffects,
fun_param: a_fun_param,
cc_param: a_cc_param,
cc_this: a_cc_this,
cc_reified: a_cc_reified,
closure_parent_scope: a_closure_parent_scope,
generator_this: a_generator_this,
caller: a_caller,
} = a;
let Coeffects {
static_coeffects: b_static_coeffects,
unenforced_static_coeffects: b_unenforced_static_coeffects,
fun_param: b_fun_param,
cc_param: b_cc_param,
cc_this: b_cc_this,
cc_reified: b_cc_reified,
closure_parent_scope: b_closure_parent_scope,
generator_this: b_generator_this,
caller: b_caller,
} = b;
cmp_slice(a_static_coeffects, b_static_coeffects, cmp_eq).qualified("static_coeffects")?;
cmp_slice(
a_unenforced_static_coeffects,
b_unenforced_static_coeffects,
cmp_eq,
)
.qualified("unenforced_static_coeffects")?;
cmp_slice(a_fun_param, b_fun_param, cmp_eq).qualified("fun_param")?;
cmp_slice(a_cc_param, b_cc_param, cmp_eq).qualified("cc_param")?;
cmp_slice(a_cc_this, b_cc_this, cmp_cc_this).qualified("cc_this")?;
cmp_slice(a_cc_reified, b_cc_reified, cmp_cc_reified).qualified("cc_reified")?;
cmp_eq(a_closure_parent_scope, b_closure_parent_scope).qualified("closure_parent_scope")?;
cmp_eq(a_generator_this, b_generator_this).qualified("generator_this")?;
cmp_eq(a_caller, b_caller).qualified("caller")?;
Ok(())
}
fn cmp_constant(
(a_const, a_strings): (&Constant<'_>, &StringInterner),
(b_const, b_strings): (&Constant<'_>, &StringInterner),
) -> Result {
let cmp_id = |a: UnitBytesId, b: UnitBytesId| cmp_id((a, a_strings), (b, b_strings));
cmp_eq(
std::mem::discriminant(a_const),
std::mem::discriminant(b_const),
)?;
match (a_const, b_const) {
(Constant::Array(a), Constant::Array(b)) => {
cmp_typed_value((a, a_strings), (b, b_strings)).qualified("array")?
}
(Constant::Bool(a), Constant::Bool(b)) => cmp_eq(a, b).qualified("bool")?,
(Constant::Float(a), Constant::Float(b)) => cmp_eq(a, b).qualified("float")?,
(Constant::Int(a), Constant::Int(b)) => cmp_eq(a, b).qualified("int")?,
(Constant::Named(a), Constant::Named(b)) => cmp_eq(a, b).qualified("named")?,
(Constant::NewCol(a), Constant::NewCol(b)) => cmp_eq(a, b).qualified("new_col")?,
(Constant::String(a), Constant::String(b)) => cmp_id(*a, *b).qualified("string")?,
(Constant::Dir, Constant::Dir)
| (Constant::File, Constant::File)
| (Constant::FuncCred, Constant::FuncCred)
| (Constant::Method, Constant::Method)
| (Constant::Null, Constant::Null)
| (Constant::Uninit, Constant::Uninit) => {}
_ => unreachable!(),
}
Ok(())
}
fn cmp_ctx_constant(a: &CtxConstant<'_>, b: &CtxConstant<'_>) -> Result {
let CtxConstant {
name: a_name,
recognized: a_recognized,
unrecognized: a_unrecognized,
is_abstract: a_is_abstract,
} = a;
let CtxConstant {
name: b_name,
recognized: b_recognized,
unrecognized: b_unrecognized,
is_abstract: b_is_abstract,
} = b;
cmp_eq(a_name, b_name).qualified("name")?;
cmp_eq(a_recognized, b_recognized).qualified("recognized")?;
cmp_eq(a_unrecognized, b_unrecognized).qualified("unrecognized")?;
cmp_eq(a_is_abstract, b_is_abstract).qualified("is_abstract")?;
Ok(())
}
fn cmp_ex_frame(a_frame: (&ExFrameId, &ExFrame), b_frame: (&ExFrameId, &ExFrame)) -> Result {
cmp_eq(a_frame.0, b_frame.0).qualified("id")?;
cmp_eq(a_frame.1.parent, b_frame.1.parent).qualified("parent")?;
cmp_eq(a_frame.1.catch_bid, b_frame.1.catch_bid).qualified("catch_bid")?;
Ok(())
}
fn cmp_fatal(
(a, a_strings): (&Fatal, &StringInterner),
(b, b_strings): (&Fatal, &StringInterner),
) -> Result {
let Fatal {
op: a_op,
loc: a_loc,
message: a_message,
} = a;
let Fatal {
op: b_op,
loc: b_loc,
message: b_message,
} = b;
cmp_eq(a_op, b_op).qualified("op")?;
cmp_src_loc((a_loc, a_strings), (b_loc, b_strings)).qualified("loc")?;
cmp_eq(a_message, b_message).qualified("message")?;
Ok(())
}
fn cmp_func(
(a, a_strings): (&Func<'_>, &StringInterner),
(b, b_strings): (&Func<'_>, &StringInterner),
) -> Result {
let cmp_id = |a: UnitBytesId, b: UnitBytesId| cmp_id((a, a_strings), (b, b_strings));
let Func {
blocks: a_blocks,
doc_comment: a_doc_comment,
ex_frames: a_ex_frames,
instrs: a_instrs,
is_memoize_wrapper: a_is_memoize_wrapper,
is_memoize_wrapper_lsb: a_is_memoize_wrapper_lsb,
constants: _,
locs: _,
num_iters: a_num_iters,
params: a_params,
return_type: a_return_type,
shadowed_tparams: a_shadowed_tparams,
loc_id: a_loc_id,
tparams: a_tparams,
} = a;
let Func {
blocks: b_blocks,
doc_comment: b_doc_comment,
ex_frames: b_ex_frames,
instrs: b_instrs,
is_memoize_wrapper: b_is_memoize_wrapper,
is_memoize_wrapper_lsb: b_is_memoize_wrapper_lsb,
constants: _,
locs: _,
num_iters: b_num_iters,
params: b_params,
return_type: b_return_type,
shadowed_tparams: b_shadowed_tparams,
loc_id: b_loc_id,
tparams: b_tparams,
} = b;
cmp_eq(a_doc_comment, b_doc_comment).qualified("doc_comment")?;
cmp_eq(a_is_memoize_wrapper, b_is_memoize_wrapper).qualified("is_memoize_wrapper")?;
cmp_eq(a_is_memoize_wrapper_lsb, b_is_memoize_wrapper_lsb)
.qualified("is_memoize_wrapper_lsb")?;
cmp_eq(a_num_iters, b_num_iters).qualified("num_iters")?;
cmp_slice(
a_params.iter().map(|a| (a, a_strings)),
b_params.iter().map(|b| (b, b_strings)),
cmp_param,
)
.qualified("params")?;
cmp_type_info((a_return_type, a_strings), (b_return_type, b_strings))
.qualified("return_type")?;
cmp_slice(
a_shadowed_tparams.iter().map(|i| i.id),
b_shadowed_tparams.iter().map(|i| i.id),
cmp_id,
)
.qualified("shadowed_tparams")?;
cmp_map_t(
a_tparams.iter().map(|(i, j)| (i, j, a_strings)),
b_tparams.iter().map(|(i, j)| (i, j, b_strings)),
cmp_tparam_bounds,
)
.qualified("tparams")?;
cmp_slice(a_blocks.iter(), b_blocks.iter(), cmp_block).qualified("blocks")?;
cmp_map_t(a_ex_frames.iter(), b_ex_frames.iter(), cmp_ex_frame).qualified("ex_frames")?;
cmp_slice(
a_instrs.iter().map(|i| (i, a, a_strings)),
b_instrs.iter().map(|i| (i, b, b_strings)),
cmp_instr,
)
.qualified("instrs")?;
cmp_loc_id((*a_loc_id, a, a_strings), (*b_loc_id, b, b_strings)).qualified("loc_id")?;
Ok(())
}
fn cmp_function(
(a, a_strings): (&Function<'_>, &StringInterner),
(b, b_strings): (&Function<'_>, &StringInterner),
) -> Result {
let cmp_id = |a: UnitBytesId, b: UnitBytesId| cmp_id((a, a_strings), (b, b_strings));
let Function {
attributes: a_attributes,
attrs: a_attrs,
coeffects: a_coeffects,
flags: a_flags,
name: a_name,
func: a_func,
} = a;
let Function {
attributes: b_attributes,
attrs: b_attrs,
coeffects: b_coeffects,
flags: b_flags,
name: b_name,
func: b_func,
} = b;
cmp_attributes((a_attributes, a_strings), (b_attributes, b_strings)).qualified("attributes")?;
cmp_eq(a_attrs, b_attrs).qualified("attrs")?;
cmp_coeffects(a_coeffects, b_coeffects).qualified("coeffects")?;
cmp_eq(a_flags, b_flags).qualified("flags")?;
cmp_id(a_name.id, b_name.id).qualified("name")?;
cmp_func((a_func, a_strings), (b_func, b_strings)).qualified("func")?;
Ok(())
}
fn cmp_hack_constant(
(a, a_strings): (&HackConstant, &StringInterner),
(b, b_strings): (&HackConstant, &StringInterner),
) -> Result {
let cmp_id = |a: UnitBytesId, b: UnitBytesId| cmp_id((a, a_strings), (b, b_strings));
let HackConstant {
name: a_name,
value: a_value,
attrs: a_attrs,
} = a;
let HackConstant {
name: b_name,
value: b_value,
attrs: b_attrs,
} = b;
cmp_id(a_name.id, b_name.id).qualified("name")?;
cmp_option(
a_value.as_ref().map(|i| (i, a_strings)),
b_value.as_ref().map(|i| (i, b_strings)),
cmp_typed_value,
)
.qualified("value")?;
cmp_eq(a_attrs, b_attrs).qualified("attrs")?;
Ok(())
}
fn cmp_id(
(a, a_strings): (UnitBytesId, &StringInterner),
(b, b_strings): (UnitBytesId, &StringInterner),
) -> Result {
match (a, b) {
(UnitBytesId::NONE, UnitBytesId::NONE) => {}
(UnitBytesId::NONE, b) => {
let b = b_strings.lookup_bytes(b);
bail!("UnitBytesId NONE vs \"{}\"", String::from_utf8_lossy(&b));
}
(a, UnitBytesId::NONE) => {
let a = a_strings.lookup_bytes(a);
bail!("UnitBytesId \"{}\" vs NONE", String::from_utf8_lossy(&a));
}
(a, b) => {
let a = a_strings.lookup_bytes(a);
let b = b_strings.lookup_bytes(b);
cmp_eq(a.as_ref() as &[u8], b.as_ref() as &[u8])?;
}
}
Ok(())
}
fn cmp_instr(
(a_instr, a_func, a_strings): (&Instr, &Func<'_>, &StringInterner),
(b_instr, b_func, b_strings): (&Instr, &Func<'_>, &StringInterner),
) -> Result {
use ir::instr::HasLoc;
use ir::instr::HasLocals;
use ir::instr::HasOperands;
// eprintln!("A: {a_instr:?}");
// eprintln!("B: {b_instr:?}");
// Do a little extra work to make the errors nicer.
cmp_eq(
&std::mem::discriminant(a_instr),
&std::mem::discriminant(b_instr),
)
.qualified("discriminant")?;
fn cmp_instr_(
(a_instr, a_func, a_strings): (&Instr, &Func<'_>, &StringInterner),
(b_instr, b_func, b_strings): (&Instr, &Func<'_>, &StringInterner),
) -> Result {
cmp_eq(a_instr.operands().len(), b_instr.operands().len()).qualified("operands.len")?;
cmp_slice(
a_instr.operands().iter().map(|i| (*i, a_func, a_strings)),
b_instr.operands().iter().map(|i| (*i, b_func, b_strings)),
cmp_operand,
)
.qualified("operands")?;
cmp_eq(a_instr.locals().len(), b_instr.locals().len()).qualified("locals.len")?;
cmp_slice(
a_instr.locals().iter().map(|i| (*i, a_strings)),
b_instr.locals().iter().map(|i| (*i, b_strings)),
cmp_local,
)
.qualified("locals")?;
cmp_slice(a_instr.edges(), b_instr.edges(), cmp_eq).qualified("edges")?;
cmp_loc_id(
(a_instr.loc_id(), a_func, a_strings),
(b_instr.loc_id(), b_func, b_strings),
)
.qualified("loc_id")?;
match (a_instr, b_instr) {
(Instr::Call(a), Instr::Call(b)) => {
cmp_instr_call((a, a_strings), (b, b_strings)).qualified("call")
}
(Instr::Hhbc(a), Instr::Hhbc(b)) => {
cmp_instr_hhbc((a, a_func, a_strings), (b, b_func, b_strings)).qualified("hhbc")
}
(Instr::MemberOp(a), Instr::MemberOp(b)) => {
cmp_instr_member_op((a, a_func, a_strings), (b, b_func, b_strings))
.qualified("member_op")
}
(Instr::Special(a), Instr::Special(b)) => cmp_instr_special(a, b).qualified("special"),
(Instr::Terminator(a), Instr::Terminator(b)) => {
cmp_instr_terminator((a, a_strings), (b, b_strings)).qualified("terminator")
}
_ => unreachable!(),
}
}
cmp_instr_((a_instr, a_func, a_strings), (b_instr, b_func, b_strings))
.with_raw(|| format!("::<{:?}>", std::mem::discriminant(a_instr)))
}
fn cmp_local(
(a, a_strings): (LocalId, &StringInterner),
(b, b_strings): (LocalId, &StringInterner),
) -> Result {
let cmp_id = |a: UnitBytesId, b: UnitBytesId| cmp_id((a, a_strings), (b, b_strings));
match (a, b) {
(LocalId::Named(a_id), LocalId::Named(b_id)) => cmp_id(a_id, b_id).qualified("named"),
(LocalId::Unnamed(a_id), LocalId::Unnamed(b_id)) => cmp_eq(a_id, b_id).qualified("unnamed"),
(LocalId::Named(a_id), LocalId::Unnamed(b_id)) => bail!(
"LocalId mismatch {} vs {b_id}",
String::from_utf8_lossy(&a_strings.lookup_bytes(a_id))
),
(LocalId::Unnamed(a_id), LocalId::Named(b_id)) => bail!(
"LocalId mismatch {a_id} vs {}",
String::from_utf8_lossy(&b_strings.lookup_bytes(b_id))
),
}
}
fn cmp_operand(
(a, a_func, a_strings): (ValueId, &Func<'_>, &StringInterner),
(b, b_func, b_strings): (ValueId, &Func<'_>, &StringInterner),
) -> Result {
use FullInstrId as I;
match (a.full(), b.full()) {
(I::None, I::None) => {}
(I::None, _) => bail!("Mismatch in ValueId (none)"),
(I::Instr(a), I::Instr(b)) => cmp_eq(a, b).qualified("instr")?,
(I::Instr(_), _) => bail!("Mismatch in ValueId (instr)"),
(I::Constant(a), I::Constant(b)) => cmp_constant(
(a_func.constant(a), a_strings),
(b_func.constant(b), b_strings),
)
.qualified("constant")?,
(I::Constant(_), _) => bail!("Mismatch in ValueId (const)"),
}
Ok(())
}
fn cmp_instr_call(
(a, a_strings): (&Call, &StringInterner),
(b, b_strings): (&Call, &StringInterner),
) -> Result {
let cmp_id = |a: UnitBytesId, b: UnitBytesId| cmp_id((a, a_strings), (b, b_strings));
// Ignore LocId, ValueIds and LocalIds - those are checked elsewhere.
let Call {
operands: _,
context: a_context,
detail: a_detail,
flags: a_flags,
num_rets: a_num_rets,
inouts: a_inouts,
readonly: a_readonly,
loc: _,
} = a;
let Call {
operands: _,
context: b_context,
detail: b_detail,
flags: b_flags,
num_rets: b_num_rets,
inouts: b_inouts,
readonly: b_readonly,
loc: _,
} = b;
cmp_id(*a_context, *b_context).qualified("context")?;
cmp_eq(a_flags, b_flags).qualified("flags")?;
cmp_eq(a_num_rets, b_num_rets).qualified("num_rets")?;
cmp_slice(a_inouts, b_inouts, cmp_eq).qualified("inouts")?;
cmp_slice(a_readonly, b_readonly, cmp_eq).qualified("readonly")?;
cmp_eq(
std::mem::discriminant(a_detail),
std::mem::discriminant(b_detail),
)?;
use instr::CallDetail;
#[rustfmt::skip]
match (a_detail, b_detail) {
(CallDetail::FCallCtor, CallDetail::FCallCtor)
| (CallDetail::FCallFunc, CallDetail::FCallFunc) => {}
(CallDetail::FCallClsMethod { log: a_log },
CallDetail::FCallClsMethod { log: b_log }) => {
cmp_eq(a_log, b_log).qualified("log")?;
}
(CallDetail::FCallClsMethodD { clsid: a_clsid, method: a_method },
CallDetail::FCallClsMethodD { clsid: b_clsid, method: b_method }) => {
cmp_id(a_clsid.id, b_clsid.id).qualified("clsid")?;
cmp_id(a_method.id, b_method.id).qualified("method")?;
}
(CallDetail::FCallClsMethodM { method: a_method, log: a_log },
CallDetail::FCallClsMethodM { method: b_method, log: b_log }) => {
cmp_id(a_method.id, b_method.id).qualified("method")?;
cmp_eq(a_log, b_log).qualified("log")?;
}
(CallDetail::FCallClsMethodS { clsref: a_clsref },
CallDetail::FCallClsMethodS { clsref: b_clsref }) => {
cmp_eq(a_clsref, b_clsref).qualified("clsref")?;
}
(CallDetail::FCallClsMethodSD { clsref: a_clsref, method: a_method },
CallDetail::FCallClsMethodSD { clsref: b_clsref, method: b_method }) => {
cmp_eq(a_clsref, b_clsref).qualified("clsref")?;
cmp_id(a_method.id, b_method.id).qualified("method")?;
}
(CallDetail::FCallFuncD { func: a_func },
CallDetail::FCallFuncD { func: b_func }) => {
cmp_id(a_func.id, b_func.id).qualified("func")?;
}
(CallDetail::FCallObjMethod { flavor: a_flavor },
CallDetail::FCallObjMethod { flavor: b_flavor }) => {
cmp_eq(a_flavor, b_flavor).qualified("flavor")?;
}
(CallDetail::FCallObjMethodD { flavor: a_flavor, method: a_method },
CallDetail::FCallObjMethodD { flavor: b_flavor, method: b_method }) => {
cmp_eq(a_flavor, b_flavor).qualified("flavor")?;
cmp_id(a_method.id, b_method.id).qualified("method")?;
}
(CallDetail::FCallCtor, _)
| (CallDetail::FCallFunc, _)
| (CallDetail::FCallClsMethod {..}, _)
| (CallDetail::FCallClsMethodD {..}, _)
| (CallDetail::FCallClsMethodM {..}, _)
| (CallDetail::FCallClsMethodS {..}, _)
| (CallDetail::FCallClsMethodSD {..}, _)
| (CallDetail::FCallFuncD {..}, _)
| (CallDetail::FCallObjMethod {..}, _)
| (CallDetail::FCallObjMethodD {..}, _) => unreachable!(),
};
Ok(())
}
fn cmp_instr_hhbc(
(a, a_func, a_strings): (&Hhbc, &Func<'_>, &StringInterner),
(b, b_func, b_strings): (&Hhbc, &Func<'_>, &StringInterner),
) -> Result {
let cmp_id = |a: UnitBytesId, b: UnitBytesId| cmp_id((a, a_strings), (b, b_strings));
cmp_eq(&std::mem::discriminant(a), &std::mem::discriminant(b))?;
// Ignore LocId, ValueIds and LocalIds - those are checked elsewhere.
match (a, b) {
(Hhbc::BareThis(x0, _), Hhbc::BareThis(x1, _)) => {
cmp_eq(x0, x1).qualified("BareThis param x")?;
}
(Hhbc::CGetS(_, x0, _), Hhbc::CGetS(_, x1, _)) => {
cmp_eq(x0, x1).qualified("CGetS param x")?;
}
(Hhbc::CheckProp(x0, _), Hhbc::CheckProp(x1, _)) => {
cmp_id(x0.id, x1.id).qualified("CheckProp param x")?;
}
(Hhbc::ClsCns(_, x0, _), Hhbc::ClsCns(_, x1, _)) => {
cmp_id(x0.id, x1.id).qualified("ClsCns param x")?;
}
(Hhbc::ClsCnsD(x0, y0, _), Hhbc::ClsCnsD(x1, y1, _)) => {
cmp_id(x0.id, x1.id).qualified("ClsCnsD param x")?;
cmp_id(y0.id, y1.id).qualified("ClsCnsD param y")?;
}
(Hhbc::CmpOp(_, x0, _), Hhbc::CmpOp(_, x1, _)) => {
cmp_eq(x0, x1).qualified("CmpOp param x")?;
}
(Hhbc::ColFromArray(_, x0, _), Hhbc::ColFromArray(_, x1, _)) => {
cmp_eq(x0, x1).qualified("ColFromArray param x")?;
}
(Hhbc::ContCheck(x0, _), Hhbc::ContCheck(x1, _)) => {
cmp_eq(x0, x1).qualified("ContCheck param x")?;
}
(
Hhbc::CreateCl {
operands: _,
clsid: x0,
loc: _,
},
Hhbc::CreateCl {
operands: _,
clsid: x1,
loc: _,
},
) => {
cmp_id(x0.id, x1.id).qualified("CreateCl param x")?;
}
(Hhbc::IncDecL(_, x0, _), Hhbc::IncDecL(_, x1, _)) => {
cmp_eq(x0, x1).qualified("IncDecL param x")?;
}
(Hhbc::IncDecS(_, x0, _), Hhbc::IncDecS(_, x1, _)) => {
cmp_eq(x0, x1).qualified("IncDecS param x")?;
}
(Hhbc::IncludeEval(x0), Hhbc::IncludeEval(x1)) => {
let instr::IncludeEval {
kind: a_kind,
vid: _,
loc: a_loc,
} = x0;
let instr::IncludeEval {
kind: b_kind,
vid: _,
loc: b_loc,
} = x1;
cmp_eq(a_kind, b_kind).qualified("kind")?;
cmp_loc_id((*a_loc, a_func, a_strings), (*b_loc, b_func, b_strings))
.qualified("loc")?;
}
(Hhbc::InitProp(_, x0, y0, _), Hhbc::InitProp(_, x1, y1, _)) => {
cmp_id(x0.id, x1.id).qualified("InitProp param x")?;
cmp_eq(y0, y1).qualified("InitProp param y")?;
}
(Hhbc::InstanceOfD(_, x0, _), Hhbc::InstanceOfD(_, x1, _)) => {
cmp_id(x0.id, x1.id).qualified("InstanceOfD param x")?;
}
(Hhbc::IsTypeC(_, x0, _), Hhbc::IsTypeC(_, x1, _)) => {
cmp_eq(x0, x1).qualified("IsTypeC param x")?;
}
(Hhbc::IsTypeL(_, x0, _), Hhbc::IsTypeL(_, x1, _)) => {
cmp_eq(x0, x1).qualified("IsTypeL param x")?;
}
(Hhbc::IsTypeStructC(_, x0, _), Hhbc::IsTypeStructC(_, x1, _)) => {
cmp_eq(x0, x1).qualified("IsTypeStructC param x")?;
}
(Hhbc::IterFree(x0, _), Hhbc::IterFree(x1, _)) => {
cmp_eq(x0, x1).qualified("IterFree param x")?;
}
(Hhbc::LazyClass(x0, _), Hhbc::LazyClass(x1, _)) => {
cmp_id(x0.id, x1.id).qualified("LazyClass param x")?;
}
(Hhbc::NewDictArray(x0, _), Hhbc::NewDictArray(x1, _)) => {
cmp_eq(x0, x1).qualified("NewDictArray param x")?;
}
(Hhbc::NewObjD(x0, _), Hhbc::NewObjD(x1, _)) => {
cmp_id(x0.id, x1.id).qualified("NewObjD param x")?;
}
(Hhbc::NewObjS(x0, _), Hhbc::NewObjS(x1, _)) => {
cmp_eq(x0, x1).qualified("NewObjS param x")?;
}
(Hhbc::NewStructDict(x0, _, _), Hhbc::NewStructDict(x1, _, _)) => {
cmp_slice(x0.iter().copied(), x1.iter().copied(), cmp_id)
.qualified("NewStructDict param x")?;
}
(Hhbc::OODeclExists(_, x0, _), Hhbc::OODeclExists(_, x1, _)) => {
cmp_eq(x0, x1).qualified("OODeclExists param x")?;
}
(Hhbc::ResolveClass(x0, _), Hhbc::ResolveClass(x1, _)) => {
cmp_id(x0.id, x1.id).qualified("ResolveClass param x")?;
}
(Hhbc::ResolveClsMethod(_, x0, _), Hhbc::ResolveClsMethod(_, x1, _)) => {
cmp_id(x0.id, x1.id).qualified("ResolveClsMethod param x")?;
}
(Hhbc::ResolveClsMethodD(x0, y0, _), Hhbc::ResolveClsMethodD(x1, y1, _)) => {
cmp_id(x0.id, x1.id).qualified("ResolveClsMethodD param x")?;
cmp_id(y0.id, y1.id).qualified("ResolveClsMethodD param y")?;
}
(Hhbc::ResolveClsMethodS(x0, y0, _), Hhbc::ResolveClsMethodS(x1, y1, _)) => {
cmp_eq(x0, x1).qualified("ResolveClsMethodS param x")?;
cmp_id(y0.id, y1.id).qualified("ResolveClsMethodS param y")?;
}
(Hhbc::ResolveRClsMethod(_, x0, _), Hhbc::ResolveRClsMethod(_, x1, _)) => {
cmp_id(x0.id, x1.id).qualified("ResolveRClsMethod param x")?;
}
(Hhbc::ResolveRClsMethodS(_, x0, y0, _), Hhbc::ResolveRClsMethodS(_, x1, y1, _)) => {
cmp_eq(x0, x1).qualified("ResolveRClsMethodS param x")?;
cmp_id(y0.id, y1.id).qualified("ResolveRClsMethodS param y")?;
}
(Hhbc::ResolveFunc(x0, _), Hhbc::ResolveFunc(x1, _)) => {
cmp_id(x0.id, x1.id).qualified("ResolveFunc param x")?;
}
(Hhbc::ResolveRClsMethodD(_, x0, y0, _), Hhbc::ResolveRClsMethodD(_, x1, y1, _)) => {
cmp_id(x0.id, x1.id).qualified("ResolveRClsMethodD param x")?;
cmp_id(y0.id, y1.id).qualified("ResolveRClsMethodD param y")?;
}
(Hhbc::ResolveRFunc(_, x0, _), Hhbc::ResolveRFunc(_, x1, _)) => {
cmp_id(x0.id, x1.id).qualified("ResolveRFunc param x")?;
}
(Hhbc::ResolveMethCaller(x0, _), Hhbc::ResolveMethCaller(x1, _)) => {
cmp_id(x0.id, x1.id).qualified("ResolveMethCaller param x")?;
}
(Hhbc::SetOpL(_, _, x0, _), Hhbc::SetOpL(_, _, x1, _)) => {
cmp_eq(x0, x1).qualified("SetOpL param x")?;
}
(Hhbc::SetOpG(_, x0, _), Hhbc::SetOpG(_, x1, _)) => {
cmp_eq(x0, x1).qualified("SetOpG param x")?;
}
(Hhbc::SetOpS(_, x0, _), Hhbc::SetOpS(_, x1, _)) => {
cmp_eq(x0, x1).qualified("SetOpS param x")?;
}
(Hhbc::SetS(_, x0, _), Hhbc::SetS(_, x1, _)) => {
cmp_eq(x0, x1).qualified("SetS param x")?;
}
(Hhbc::Silence(_, x0, _), Hhbc::Silence(_, x1, _)) => {
cmp_eq(x0, x1).qualified("Silence param x")?;
}
// These have no params that weren't already checked.
(Hhbc::AKExists(_, _), _)
| (Hhbc::Add(_, _), _)
| (Hhbc::AddElemC(_, _), _)
| (Hhbc::AddNewElemC(_, _), _)
| (Hhbc::ArrayIdx(_, _), _)
| (Hhbc::ArrayMarkLegacy(_, _), _)
| (Hhbc::ArrayUnmarkLegacy(_, _), _)
| (Hhbc::Await(_, _), _)
| (Hhbc::AwaitAll(_, _), _)
| (Hhbc::BitAnd(_, _), _)
| (Hhbc::BitNot(_, _), _)
| (Hhbc::BitOr(_, _), _)
| (Hhbc::BitXor(_, _), _)
| (Hhbc::CGetG(_, _), _)
| (Hhbc::CGetL(_, _), _)
| (Hhbc::CGetQuietL(_, _), _)
| (Hhbc::CUGetL(_, _), _)
| (Hhbc::CastBool(_, _), _)
| (Hhbc::CastDict(_, _), _)
| (Hhbc::CastDouble(_, _), _)
| (Hhbc::CastInt(_, _), _)
| (Hhbc::CastKeyset(_, _), _)
| (Hhbc::CastString(_, _), _)
| (Hhbc::CastVec(_, _), _)
| (Hhbc::ChainFaults(_, _), _)
| (Hhbc::CheckClsReifiedGenericMismatch(_, _), _)
| (Hhbc::CheckClsRGSoft(_, _), _)
| (Hhbc::CheckThis(_), _)
| (Hhbc::ClassGetC(_, _), _)
| (Hhbc::ClassGetTS(_, _), _)
| (Hhbc::ClassHasReifiedGenerics(_, _), _)
| (Hhbc::ClassName(_, _), _)
| (Hhbc::Clone(_, _), _)
| (Hhbc::ClsCnsL(_, _, _), _)
| (Hhbc::Cmp(_, _), _)
| (Hhbc::CombineAndResolveTypeStruct(_, _), _)
| (Hhbc::Concat(_, _), _)
| (Hhbc::ConcatN(_, _), _)
| (Hhbc::ConsumeL(_, _), _)
| (Hhbc::ContCurrent(_), _)
| (Hhbc::ContEnter(_, _), _)
| (Hhbc::ContGetReturn(_), _)
| (Hhbc::ContKey(_), _)
| (Hhbc::ContRaise(_, _), _)
| (Hhbc::ContValid(_), _)
| (Hhbc::CreateCl { .. }, _)
| (Hhbc::CreateCont(_), _)
| (Hhbc::CreateSpecialImplicitContext(_, _), _)
| (Hhbc::Div(_, _), _)
| (Hhbc::GetClsRGProp(_, _), _)
| (Hhbc::GetMemoKeyL(_, _), _)
| (Hhbc::HasReifiedParent(_, _), _)
| (Hhbc::Idx(_, _), _)
| (Hhbc::IsLateBoundCls(_, _), _)
| (Hhbc::IssetG(_, _), _)
| (Hhbc::IssetL(_, _), _)
| (Hhbc::IssetS(_, _), _)
| (Hhbc::LateBoundCls(_), _)
| (Hhbc::LazyClassFromClass(_, _), _)
| (Hhbc::LockObj(_, _), _)
| (Hhbc::MemoSet(_, _, _), _)
| (Hhbc::MemoSetEager(_, _, _), _)
| (Hhbc::Modulo(_, _), _)
| (Hhbc::Mul(_, _), _)
| (Hhbc::NewKeysetArray(_, _), _)
| (Hhbc::NewObj(_, _), _)
| (Hhbc::NewPair(_, _), _)
| (Hhbc::NewVec(_, _), _)
| (Hhbc::Not(_, _), _)
| (Hhbc::ParentCls(_), _)
| (Hhbc::Pow(_, _), _)
| (Hhbc::Print(_, _), _)
| (Hhbc::RaiseClassStringConversionWarning(_), _)
| (Hhbc::RecordReifiedGeneric(_, _), _)
| (Hhbc::SelfCls(_), _)
| (Hhbc::SetG(_, _), _)
| (Hhbc::SetImplicitContextByValue(_, _), _)
| (Hhbc::SetL(_, _, _), _)
| (Hhbc::Shl(_, _), _)
| (Hhbc::Shr(_, _), _)
| (Hhbc::Sub(_, _), _)
| (Hhbc::This(_), _)
| (Hhbc::ThrowNonExhaustiveSwitch(_), _)
| (Hhbc::UnsetG(_, _), _)
| (Hhbc::UnsetL(_, _), _)
| (Hhbc::VerifyImplicitContextState(_), _)
| (Hhbc::VerifyOutType(_, _, _), _)
| (Hhbc::VerifyParamType(_, _, _), _)
| (Hhbc::VerifyParamTypeTS(_, _, _), _)
| (Hhbc::VerifyRetTypeC(_, _), _)
| (Hhbc::VerifyRetTypeTS(_, _), _)
| (Hhbc::WHResult(_, _), _)
| (Hhbc::Yield(_, _), _)
| (Hhbc::YieldK(_, _), _) => {}
// these should never happen
(Hhbc::BareThis(..), _)
| (Hhbc::CGetS(..), _)
| (Hhbc::CheckProp(..), _)
| (Hhbc::ClsCns(..), _)
| (Hhbc::ClsCnsD(..), _)
| (Hhbc::CmpOp(..), _)
| (Hhbc::ColFromArray(..), _)
| (Hhbc::ContCheck(..), _)
| (Hhbc::IncDecL(..), _)
| (Hhbc::IncDecS(..), _)
| (Hhbc::IncludeEval(..), _)
| (Hhbc::InitProp(..), _)
| (Hhbc::InstanceOfD(..), _)
| (Hhbc::IsTypeC(..), _)
| (Hhbc::IsTypeL(..), _)
| (Hhbc::IsTypeStructC(..), _)
| (Hhbc::IterFree(..), _)
| (Hhbc::LazyClass(..), _)
| (Hhbc::NewDictArray(..), _)
| (Hhbc::NewObjD(..), _)
| (Hhbc::NewObjS(..), _)
| (Hhbc::NewStructDict(..), _)
| (Hhbc::OODeclExists(..), _)
| (Hhbc::ResolveClass(..), _)
| (Hhbc::ResolveClsMethod(..), _)
| (Hhbc::ResolveClsMethodD(..), _)
| (Hhbc::ResolveClsMethodS(..), _)
| (Hhbc::ResolveRClsMethod(..), _)
| (Hhbc::ResolveRClsMethodS(..), _)
| (Hhbc::ResolveFunc(..), _)
| (Hhbc::ResolveRClsMethodD(..), _)
| (Hhbc::ResolveRFunc(..), _)
| (Hhbc::ResolveMethCaller(..), _)
| (Hhbc::SetOpL(..), _)
| (Hhbc::SetOpG(..), _)
| (Hhbc::SetOpS(..), _)
| (Hhbc::SetS(..), _)
| (Hhbc::Silence(..), _) => unreachable!(),
}
Ok(())
}
fn cmp_instr_member_op(
(a, a_func, a_strings): (&MemberOp, &Func<'_>, &StringInterner),
(b, b_func, b_strings): (&MemberOp, &Func<'_>, &StringInterner),
) -> Result {
let MemberOp {
base_op: a_base_op,
intermediate_ops: a_intermediate_ops,
final_op: a_final_op,
operands: _,
locals: _,
} = a;
let MemberOp {
base_op: b_base_op,
intermediate_ops: b_intermediate_ops,
final_op: b_final_op,
operands: _,
locals: _,
} = b;
cmp_instr_member_op_base(
(a_base_op, a_func, a_strings),
(b_base_op, b_func, b_strings),
)
.qualified("base")?;
cmp_slice(
a_intermediate_ops.iter().map(|i| (i, a_func, a_strings)),
b_intermediate_ops.iter().map(|i| (i, b_func, b_strings)),
cmp_instr_member_op_intermediate,
)
.qualified("intermediate")?;
cmp_instr_member_op_final(
(a_final_op, a_func, a_strings),
(b_final_op, b_func, b_strings),
)
.qualified("final")?;
Ok(())
}
fn cmp_instr_member_op_base(
(a, a_func, a_strings): (&BaseOp, &Func<'_>, &StringInterner),
(b, b_func, b_strings): (&BaseOp, &Func<'_>, &StringInterner),
) -> Result {
cmp_eq(&std::mem::discriminant(a), &std::mem::discriminant(b))?;
#[rustfmt::skip]
match (a, b) {
(BaseOp::BaseC { mode: a_mode, loc: a_loc },
BaseOp::BaseC { mode: b_mode, loc: b_loc }) |
(BaseOp::BaseGC { mode: a_mode, loc: a_loc },
BaseOp::BaseGC { mode: b_mode, loc: b_loc }) => {
cmp_eq(a_mode, b_mode).qualified("mode")?;
cmp_loc_id((*a_loc, a_func, a_strings), (*b_loc, b_func, b_strings)).qualified("loc")?;
}
(BaseOp::BaseH { loc: a_loc },
BaseOp::BaseH { loc: b_loc }) => {
cmp_loc_id((*a_loc, a_func, a_strings), (*b_loc, b_func, b_strings)).qualified("loc")?;
}
(BaseOp::BaseL { mode: a_mode, readonly: a_readonly, loc: a_loc },
BaseOp::BaseL { mode: b_mode, readonly: b_readonly, loc: b_loc }) |
(BaseOp::BaseSC { mode: a_mode, readonly: a_readonly, loc: a_loc },
BaseOp::BaseSC { mode: b_mode, readonly: b_readonly, loc: b_loc }) => {
cmp_eq(a_mode, b_mode).qualified("mode")?;
cmp_eq(a_readonly, b_readonly).qualified("readonly")?;
cmp_loc_id((*a_loc, a_func, a_strings), (*b_loc, b_func, b_strings)).qualified("loc")?;
}
(BaseOp::BaseST { mode: a_mode, readonly: a_readonly, loc: a_loc, prop: a_prop },
BaseOp::BaseST { mode: b_mode, readonly: b_readonly, loc: b_loc, prop: b_prop }) => {
cmp_eq(a_mode, b_mode).qualified("mode")?;
cmp_eq(a_readonly, b_readonly).qualified("readonly")?;
cmp_loc_id((*a_loc, a_func, a_strings), (*b_loc, b_func, b_strings)).qualified("loc")?;
cmp_id((a_prop.id, a_strings), (b_prop.id, b_strings)).qualified("prop")?;
}
(BaseOp::BaseC { .. }, _)
| (BaseOp::BaseGC { .. }, _)
| (BaseOp::BaseH { .. }, _)
| (BaseOp::BaseL { .. }, _)
| (BaseOp::BaseSC { .. }, _)
| (BaseOp::BaseST { .. }, _) => unreachable!(),
};
Ok(())
}
fn cmp_instr_member_op_intermediate(
(a, a_func, a_strings): (&IntermediateOp, &Func<'_>, &StringInterner),
(b, b_func, b_strings): (&IntermediateOp, &Func<'_>, &StringInterner),
) -> Result {
let IntermediateOp {
key: a_key,
mode: a_mode,
readonly: a_readonly,
loc: a_loc,
} = a;
let IntermediateOp {
key: b_key,
mode: b_mode,
readonly: b_readonly,
loc: b_loc,
} = b;
cmp_member_key((a_key, a_strings), (b_key, b_strings)).qualified("key")?;
cmp_eq(a_mode, b_mode).qualified("mode")?;
cmp_eq(a_readonly, b_readonly).qualified("readonly")?;
cmp_loc_id((*a_loc, a_func, a_strings), (*b_loc, b_func, b_strings)).qualified("loc")?;
Ok(())
}
fn cmp_instr_member_op_final(
(a, a_func, a_strings): (&FinalOp, &Func<'_>, &StringInterner),
(b, b_func, b_strings): (&FinalOp, &Func<'_>, &StringInterner),
) -> Result {
cmp_eq(&std::mem::discriminant(a), &std::mem::discriminant(b))?;
#[rustfmt::skip]
match (a, b) {
(FinalOp::IncDecM { key: a_key, readonly: a_readonly, inc_dec_op: a_inc_dec_op, loc: a_loc },
FinalOp::IncDecM { key: b_key, readonly: b_readonly, inc_dec_op: b_inc_dec_op, loc: b_loc }) => {
cmp_member_key((a_key, a_strings), (b_key, b_strings)).qualified("key")?;
cmp_eq(a_readonly, b_readonly).qualified("readonly")?;
cmp_eq(a_inc_dec_op, b_inc_dec_op).qualified("inc_dec_op")?;
cmp_loc_id((*a_loc, a_func, a_strings), (*b_loc, b_func, b_strings)).qualified("loc")?;
}
(FinalOp::QueryM { key: a_key, readonly: a_readonly, query_m_op: a_query_m_op, loc: a_loc },
FinalOp::QueryM { key: b_key, readonly: b_readonly, query_m_op: b_query_m_op, loc: b_loc }) => {
cmp_member_key((a_key, a_strings), (b_key, b_strings)).qualified("key")?;
cmp_eq(a_readonly, b_readonly).qualified("readonly")?;
cmp_eq(a_query_m_op, b_query_m_op).qualified("query_m_op")?;
cmp_loc_id((*a_loc, a_func, a_strings), (*b_loc, b_func, b_strings)).qualified("loc")?;
}
(FinalOp::SetM { key: a_key, readonly: a_readonly, loc: a_loc },
FinalOp::SetM { key: b_key, readonly: b_readonly, loc: b_loc }) => {
cmp_member_key((a_key, a_strings), (b_key, b_strings)).qualified("key")?;
cmp_eq(a_readonly, b_readonly).qualified("readonly")?;
cmp_loc_id((*a_loc, a_func, a_strings), (*b_loc, b_func, b_strings)).qualified("loc")?;
}
(FinalOp::SetRangeM { sz: a_sz, set_range_op: a_set_range_op, loc: a_loc },
FinalOp::SetRangeM { sz: b_sz, set_range_op: b_set_range_op, loc: b_loc }) => {
cmp_eq(a_sz, b_sz).qualified("sz")?;
cmp_eq(a_set_range_op, b_set_range_op).qualified("set_range_op")?;
cmp_loc_id((*a_loc, a_func, a_strings), (*b_loc, b_func, b_strings)).qualified("loc")?;
}
(FinalOp::SetOpM { key: a_key, readonly: a_readonly, set_op_op: a_set_op_op, loc: a_loc },
FinalOp::SetOpM { key: b_key, readonly: b_readonly, set_op_op: b_set_op_op, loc: b_loc }) => {
cmp_member_key((a_key, a_strings), (b_key, b_strings)).qualified("key")?;
cmp_eq(a_readonly, b_readonly).qualified("readonly")?;
cmp_eq(a_set_op_op, b_set_op_op).qualified("set_op_op")?;
cmp_loc_id((*a_loc, a_func, a_strings), (*b_loc, b_func, b_strings)).qualified("loc")?;
}
(FinalOp::UnsetM { key: a_key, readonly: a_readonly, loc: a_loc },
FinalOp::UnsetM { key: b_key, readonly: b_readonly, loc: b_loc }) => {
cmp_member_key((a_key, a_strings), (b_key, b_strings)).qualified("key")?;
cmp_eq(a_readonly, b_readonly).qualified("readonly")?;
cmp_loc_id((*a_loc, a_func, a_strings), (*b_loc, b_func, b_strings)).qualified("loc")?;
}
(FinalOp::IncDecM { .. }, _)
| (FinalOp::QueryM { .. }, _)
| (FinalOp::SetM { .. }, _)
| (FinalOp::SetRangeM { .. }, _)
| (FinalOp::SetOpM { .. }, _)
| (FinalOp::UnsetM { .. }, _) => unreachable!(),
};
Ok(())
}
fn cmp_member_key(
(a, a_strings): (&MemberKey, &StringInterner),
(b, b_strings): (&MemberKey, &StringInterner),
) -> Result {
let cmp_id = |a: UnitBytesId, b: UnitBytesId| cmp_id((a, a_strings), (b, b_strings));
cmp_eq(&std::mem::discriminant(a), &std::mem::discriminant(b))?;
match (a, b) {
(MemberKey::EI(a), MemberKey::EI(b)) => cmp_eq(a, b)?,
(MemberKey::ET(a), MemberKey::ET(b)) => {
cmp_id(*a, *b)?;
}
(MemberKey::PT(a), MemberKey::PT(b)) | (MemberKey::QT(a), MemberKey::QT(b)) => {
cmp_id(a.id, b.id)?;
}
(MemberKey::EC, MemberKey::EC)
| (MemberKey::EL, MemberKey::EL)
| (MemberKey::PC, MemberKey::PC)
| (MemberKey::PL, MemberKey::PL)
| (MemberKey::W, MemberKey::W) => {}
(MemberKey::EC, _)
| (MemberKey::EI(..), _)
| (MemberKey::EL, _)
| (MemberKey::ET(..), _)
| (MemberKey::PC, _)
| (MemberKey::PL, _)
| (MemberKey::PT(..), _)
| (MemberKey::QT(..), _)
| (MemberKey::W, _) => unreachable!(),
}
Ok(())
}
fn cmp_instr_special(a: &Special, b: &Special) -> Result {
cmp_eq(&std::mem::discriminant(a), &std::mem::discriminant(b))?;
// Ignore LocId, ValueIds, LocalIds and BlockIds - those are checked elsewhere.
match (a, b) {
(Special::Copy(_), Special::Copy(_))
| (Special::Param, Special::Param)
| (Special::Tombstone, Special::Tombstone) => {}
(Special::Select(_, a), Special::Select(_, b)) => cmp_eq(a, b)?,
(Special::IrToBc(_), _) | (Special::Tmp(_), _) | (Special::Textual(_), _) => todo!(),
(Special::Copy(..), _)
| (Special::Param, _)
| (Special::Select(..), _)
| (Special::Tombstone, _) => unreachable!(),
}
Ok(())
}
fn cmp_instr_terminator(
(a, a_strings): (&Terminator, &StringInterner),
(b, b_strings): (&Terminator, &StringInterner),
) -> Result {
cmp_eq(&std::mem::discriminant(a), &std::mem::discriminant(b))?;
fn cmp_instr_terminator_(
(a, a_strings): (&Terminator, &StringInterner),
(b, b_strings): (&Terminator, &StringInterner),
) -> Result {
// Ignore LocId, ValueIds, LocalIds and BlockIds - those are checked elsewhere.
#[rustfmt::skip]
match (a, b) {
(Terminator::CallAsync(a_call, _),
Terminator::CallAsync(b_call, _)) => {
cmp_instr_call((a_call, a_strings), (b_call, b_strings))?;
}
(Terminator::Fatal(_, a_op, _),
Terminator::Fatal(_, b_op, _)) => {
cmp_eq(a_op, b_op)?;
}
(Terminator::IterInit(a_iterator, _),
Terminator::IterInit(b_iterator, _))
| (Terminator::IterNext(a_iterator),
Terminator::IterNext(b_iterator)) => {
cmp_instr_iterator(a_iterator, b_iterator)?;
}
(Terminator::JmpOp { cond: _, pred: a_pred, targets: _, loc: _, },
Terminator::JmpOp { cond: _, pred: b_pred, targets: _, loc: _, }, ) => {
cmp_eq(a_pred, b_pred)?;
}
(Terminator::Switch { cond: _, bounded: a_kind, base: a_base, targets: _, loc: _, },
Terminator::Switch { cond: _, bounded: b_kind, base: b_base, targets: _, loc: _, }, ) => {
cmp_eq(a_kind, b_kind)?;
cmp_eq(a_base, b_base)?;
}
(Terminator::SSwitch { cond: _, cases: a_cases, targets: _, loc: _, },
Terminator::SSwitch { cond: _, cases: b_cases, targets: _, loc: _, }, ) => {
cmp_slice(a_cases.iter().map(|i| (*i, a_strings)), b_cases.iter().map(|i| (*i, b_strings)), cmp_id)?;
}
// These are ONLY made of LocId, ValueIds, LocalIds and BlockIds.
(Terminator::Enter(_, _), _)
| (Terminator::Exit(_, _), _)
| (Terminator::Jmp(_, _), _)
| (Terminator::JmpArgs(_, _, _), _)
| (Terminator::MemoGet(_), _)
| (Terminator::MemoGetEager(_), _)
| (Terminator::NativeImpl(_), _)
| (Terminator::Ret(_, _), _)
| (Terminator::RetCSuspended(_, _), _)
| (Terminator::RetM(_, _), _)
| (Terminator::Throw(_, _), _)
| (Terminator::ThrowAsTypeStructException(_, _), _)
| (Terminator::Unreachable, _) => {}
(Terminator::CallAsync(..), _)
| (Terminator::Fatal(..), _)
| (Terminator::IterInit(..), _)
| (Terminator::IterNext(..), _)
| (Terminator::JmpOp { .. }, _)
| (Terminator::Switch { .. }, _)
| (Terminator::SSwitch { .. }, _) => unreachable!(),
};
Ok(())
}
cmp_instr_terminator_((a, a_strings), (b, b_strings))
.with_raw(|| format!("::<{:?}>", std::mem::discriminant(a)))
}
fn cmp_instr_iterator(a: &IteratorArgs, b: &IteratorArgs) -> Result {
// Ignore LocId, ValueIds and LocalIds - those are checked elsewhere.
let IteratorArgs {
iter_id: a_iter_id,
locals: _,
targets: _,
loc: _,
} = a;
let IteratorArgs {
iter_id: b_iter_id,
locals: _,
targets: _,
loc: _,
} = b;
cmp_eq(a_iter_id, b_iter_id).qualified("iter_id")?;
Ok(())
}
fn cmp_loc_id(
(a, a_func, a_strings): (LocId, &Func<'_>, &StringInterner),
(b, b_func, b_strings): (LocId, &Func<'_>, &StringInterner),
) -> Result {
let a_src_loc = a_func.get_loc(a);
let b_src_loc = b_func.get_loc(b);
cmp_option(
a_src_loc.map(|i| (i, a_strings)),
b_src_loc.map(|i| (i, b_strings)),
cmp_src_loc,
)
}
fn cmp_method(
(a, a_strings): (&Method<'_>, &StringInterner),
(b, b_strings): (&Method<'_>, &StringInterner),
) -> Result {
let cmp_id = |a: UnitBytesId, b: UnitBytesId| cmp_id((a, a_strings), (b, b_strings));
let Method {
attributes: a_attributes,
attrs: a_attrs,
coeffects: a_coeffects,
flags: a_flags,
func: a_func,
name: a_name,
visibility: a_visibility,
} = a;
let Method {
attributes: b_attributes,
attrs: b_attrs,
coeffects: b_coeffects,
flags: b_flags,
func: b_func,
name: b_name,
visibility: b_visibility,
} = b;
cmp_attributes((a_attributes, a_strings), (b_attributes, b_strings)).qualified("attributes")?;
cmp_eq(a_attrs, b_attrs).qualified("attrs")?;
cmp_coeffects(a_coeffects, b_coeffects).qualified("coeffects")?;
cmp_eq(a_flags, b_flags).qualified("flags")?;
cmp_func((a_func, a_strings), (b_func, b_strings)).qualified("func")?;
cmp_id(a_name.id, b_name.id).qualified("name")?;
cmp_eq(a_visibility, b_visibility).qualified("visibility")?;
Ok(())
}
fn cmp_module(
(a, a_strings): (&Module<'_>, &StringInterner),
(b, b_strings): (&Module<'_>, &StringInterner),
) -> Result {
let cmp_id = |a: UnitBytesId, b: UnitBytesId| cmp_id((a, a_strings), (b, b_strings));
let Module {
attributes: a_attributes,
name: a_name,
src_loc: a_src_loc,
doc_comment: a_doc_comment,
} = a;
let Module {
attributes: b_attributes,
name: b_name,
src_loc: b_src_loc,
doc_comment: b_doc_comment,
} = b;
cmp_id(a_name.id, b_name.id).qualified("name")?;
cmp_attributes((a_attributes, a_strings), (b_attributes, b_strings)).qualified("attributes")?;
cmp_src_loc((a_src_loc, a_strings), (b_src_loc, b_strings)).qualified("src_loc")?;
cmp_eq(a_doc_comment, b_doc_comment).qualified("doc_comment")?;
Ok(())
}
fn cmp_param(
(a, a_strings): (&Param<'_>, &StringInterner),
(b, b_strings): (&Param<'_>, &StringInterner),
) -> Result {
let cmp_id = |a: UnitBytesId, b: UnitBytesId| cmp_id((a, a_strings), (b, b_strings));
let Param {
name: a_name,
is_variadic: a_is_variadic,
is_inout: a_is_inout,
is_readonly: a_is_readonly,
user_attributes: a_user_attributes,
ty: a_ty,
default_value: a_default_value,
} = a;
let Param {
name: b_name,
is_variadic: b_is_variadic,
is_inout: b_is_inout,
is_readonly: b_is_readonly,
user_attributes: b_user_attributes,
ty: b_ty,
default_value: b_default_value,
} = b;
cmp_id(*a_name, *b_name)
.qualified("name")
.qualified("name")?;
cmp_eq(a_is_variadic, b_is_variadic).qualified("is_variadic")?;
cmp_eq(a_is_inout, b_is_inout).qualified("is_inout")?;
cmp_eq(a_is_readonly, b_is_readonly).qualified("is_readonly")?;
cmp_attributes(
(a_user_attributes, a_strings),
(b_user_attributes, b_strings),
)
.qualified("user_attributes")?;
cmp_type_info((a_ty, a_strings), (b_ty, b_strings)).qualified("ty")?;
cmp_option(
a_default_value.as_ref(),
b_default_value.as_ref(),
cmp_default_value,
)
.qualified("default_value")?;
Ok(())
}
fn cmp_default_value(a: &DefaultValue<'_>, b: &DefaultValue<'_>) -> Result {
let DefaultValue {
init: a_init,
expr: a_expr,
} = a;
let DefaultValue {
init: b_init,
expr: b_expr,
} = b;
cmp_eq(a_init, b_init).qualified("init")?;
cmp_eq(a_expr, b_expr).qualified("expr")?;
Ok(())
}
fn cmp_property(
(a, a_strings): (&Property<'_>, &StringInterner),
(b, b_strings): (&Property<'_>, &StringInterner),
) -> Result {
let cmp_id = |a: UnitBytesId, b: UnitBytesId| cmp_id((a, a_strings), (b, b_strings));
let Property {
name: a_name,
flags: a_flags,
attributes: a_attributes,
visibility: a_visibility,
initial_value: a_initial_value,
type_info: a_type_info,
doc_comment: a_doc_comment,
} = a;
let Property {
name: b_name,
flags: b_flags,
attributes: b_attributes,
visibility: b_visibility,
initial_value: b_initial_value,
type_info: b_type_info,
doc_comment: b_doc_comment,
} = b;
cmp_id(a_name.id, b_name.id).qualified("name")?;
cmp_eq(a_flags, b_flags).qualified("flagsr")?;
cmp_attributes((a_attributes, a_strings), (b_attributes, b_strings)).qualified("attributes")?;
cmp_eq(a_visibility, b_visibility).qualified("visibility")?;
cmp_option(
a_initial_value.as_ref().map(|i| (i, a_strings)),
b_initial_value.as_ref().map(|i| (i, b_strings)),
cmp_typed_value,
)
.qualified("initial_value")?;
cmp_type_info((a_type_info, a_strings), (b_type_info, b_strings)).qualified("type_info")?;
cmp_option(
a_doc_comment.as_ref().into_option(),
b_doc_comment.as_ref().into_option(),
cmp_eq,
)
.qualified("doc_comment")?;
Ok(())
}
fn cmp_requirement(
(a, a_strings): (&Requirement, &StringInterner),
(b, b_strings): (&Requirement, &StringInterner),
) -> Result {
let cmp_id = |a: UnitBytesId, b: UnitBytesId| cmp_id((a, a_strings), (b, b_strings));
let Requirement {
name: a_name,
kind: a_kind,
} = a;
let Requirement {
name: b_name,
kind: b_kind,
} = b;
cmp_id(a_name.id, b_name.id).qualified("name")?;
cmp_eq(a_kind, b_kind).qualified("kind")?;
Ok(())
}
fn cmp_src_loc(
(a, a_strings): (&SrcLoc, &StringInterner),
(b, b_strings): (&SrcLoc, &StringInterner),
) -> Result {
let cmp_id = |a: UnitBytesId, b: UnitBytesId| cmp_id((a, a_strings), (b, b_strings));
cmp_id(a.filename.0, b.filename.0).qualified("filename")?;
cmp_eq(a.line_begin, b.line_begin).qualified("line_begin")?;
cmp_eq(a.line_end, b.line_end).qualified("line_end")?;
cmp_eq(a.col_begin, b.col_begin).qualified("col_begin")?;
cmp_eq(a.col_end, b.col_end).qualified("col_end")?;
Ok(())
}
fn cmp_symbol_refs(a: &SymbolRefs<'_>, b: &SymbolRefs<'_>) -> Result {
let SymbolRefs {
classes: a_classes,
constants: a_constants,
functions: a_functions,
includes: a_includes,
} = a;
let SymbolRefs {
classes: b_classes,
constants: b_constants,
functions: b_functions,
includes: b_includes,
} = b;
cmp_slice(a_classes, b_classes, cmp_eq).qualified("classes")?;
cmp_slice(a_constants, b_constants, cmp_eq).qualified("constants")?;
cmp_slice(a_functions, b_functions, cmp_eq).qualified("functions")?;
cmp_slice(a_includes, b_includes, cmp_eq).qualified("includes")?;
Ok(())
}
fn cmp_tparam_bounds(
(a_id, a, a_strings): (&ClassId, &TParamBounds, &StringInterner),
(b_id, b, b_strings): (&ClassId, &TParamBounds, &StringInterner),
) -> Result {
let cmp_id = |a: UnitBytesId, b: UnitBytesId| cmp_id((a, a_strings), (b, b_strings));
cmp_id(a_id.id, b_id.id).qualified("0")?;
cmp_slice(
a.bounds.iter().map(|i| (i, a_strings)),
b.bounds.iter().map(|i| (i, b_strings)),
cmp_type_info,
)
.qualified("bounds")
.qualified("1")?;
Ok(())
}
fn cmp_type_constant(
(a, a_strings): (&TypeConstant<'_>, &StringInterner),
(b, b_strings): (&TypeConstant<'_>, &StringInterner),
) -> Result {
let TypeConstant {
name: a_name,
initializer: a_initializer,
is_abstract: a_is_abstract,
} = a;
let TypeConstant {
name: b_name,
initializer: b_initializer,
is_abstract: b_is_abstract,
} = b;
cmp_eq(a_name, b_name).qualified("name")?;
cmp_option(
a_initializer.as_ref().map(|i| (i, a_strings)),
b_initializer.as_ref().map(|i| (i, b_strings)),
cmp_typed_value,
)
.qualified("initializer")?;
cmp_eq(a_is_abstract, b_is_abstract).qualified("is_abstract")?;
Ok(())
}
fn cmp_type_info(
(a, a_strings): (&TypeInfo, &StringInterner),
(b, b_strings): (&TypeInfo, &StringInterner),
) -> Result {
let cmp_id = |a: UnitBytesId, b: UnitBytesId| cmp_id((a, a_strings), (b, b_strings));
let TypeInfo {
user_type: a_user_type,
enforced: a_enforced,
} = a;
let TypeInfo {
user_type: b_user_type,
enforced: b_enforced,
} = b;
cmp_option(*a_user_type, *b_user_type, cmp_id).qualified("user_type")?;
let EnforceableType {
ty: a_ty,
modifiers: a_modifiers,
} = a_enforced;
let EnforceableType {
ty: b_ty,
modifiers: b_modifiers,
} = b_enforced;
cmp_base_ty((a_ty, a_strings), (b_ty, b_strings))
.qualified("ty")
.qualified("enforced")?;
cmp_eq(a_modifiers, b_modifiers)
.qualified("modifiers")
.qualified("enforced")?;
Ok(())
}
fn cmp_base_ty(
(a, a_strings): (&BaseType, &StringInterner),
(b, b_strings): (&BaseType, &StringInterner),
) -> Result {
let cmp_id = |a: UnitBytesId, b: UnitBytesId| cmp_id((a, a_strings), (b, b_strings));
cmp_eq(std::mem::discriminant(a), std::mem::discriminant(b))?;
match (a, b) {
(BaseType::Class(a), BaseType::Class(b)) => cmp_id(a.id, b.id),
(BaseType::AnyArray, _)
| (BaseType::Arraykey, _)
| (BaseType::Bool, _)
| (BaseType::Classname, _)
| (BaseType::Darray, _)
| (BaseType::Dict, _)
| (BaseType::Float, _)
| (BaseType::Int, _)
| (BaseType::Keyset, _)
| (BaseType::Mixed, _)
| (BaseType::None, _)
| (BaseType::Nonnull, _)
| (BaseType::Noreturn, _)
| (BaseType::Nothing, _)
| (BaseType::Null, _)
| (BaseType::Num, _)
| (BaseType::Resource, _)
| (BaseType::String, _)
| (BaseType::This, _)
| (BaseType::Typename, _)
| (BaseType::Varray, _)
| (BaseType::VarrayOrDarray, _)
| (BaseType::Vec, _)
| (BaseType::VecOrDict, _)
| (BaseType::Void, _) => Ok(()),
(BaseType::Class(_), _) => unreachable!(),
}
}
fn cmp_typed_value(
(a, a_strings): (&TypedValue, &StringInterner),
(b, b_strings): (&TypedValue, &StringInterner),
) -> Result {
let cmp_id = |a: UnitBytesId, b: UnitBytesId| cmp_id((a, a_strings), (b, b_strings));
cmp_eq(std::mem::discriminant(a), std::mem::discriminant(b))?;
match (a, b) {
(TypedValue::Uninit, TypedValue::Uninit) | (TypedValue::Null, TypedValue::Null) => {}
(TypedValue::Int(a), TypedValue::Int(b)) => cmp_eq(a, b).qualified("int")?,
(TypedValue::Bool(a), TypedValue::Bool(b)) => cmp_eq(a, b).qualified("bool")?,
(TypedValue::Float(a), TypedValue::Float(b)) => cmp_eq(a, b).qualified("float")?,
(TypedValue::String(a), TypedValue::String(b)) => cmp_id(*a, *b).qualified("string")?,
(TypedValue::LazyClass(ClassId { id: a }), TypedValue::LazyClass(ClassId { id: b })) => {
cmp_id(*a, *b).qualified("lazy_class")?
}
(TypedValue::Vec(a), TypedValue::Vec(b)) => {
cmp_slice(
a.iter().map(|i| (i, a_strings)),
b.iter().map(|i| (i, b_strings)),
cmp_typed_value,
)
.qualified("vec")?;
}
(TypedValue::Keyset(a), TypedValue::Keyset(b)) => {
cmp_slice(
a.0.iter().map(|i| (i, a_strings)),
b.0.iter().map(|i| (i, b_strings)),
cmp_array_key,
)
.qualified("keyset")?;
}
(TypedValue::Dict(a), TypedValue::Dict(b)) => {
cmp_slice(
a.0.keys().map(|i| (i, a_strings)),
b.0.keys().map(|i| (i, b_strings)),
cmp_array_key,
)
.qualified("dict keys")?;
cmp_slice(
a.0.values().map(|i| (i, a_strings)),
b.0.values().map(|i| (i, b_strings)),
cmp_typed_value,
)
.qualified("dict values")?;
}
(TypedValue::Uninit, _)
| (TypedValue::Int(_), _)
| (TypedValue::Bool(_), _)
| (TypedValue::Float(_), _)
| (TypedValue::String(_), _)
| (TypedValue::LazyClass(_), _)
| (TypedValue::Null, _)
| (TypedValue::Vec(_), _)
| (TypedValue::Keyset(_), _)
| (TypedValue::Dict(_), _) => unreachable!(),
}
Ok(())
}
fn cmp_array_key(
(a, a_strings): (&ArrayKey, &StringInterner),
(b, b_strings): (&ArrayKey, &StringInterner),
) -> Result {
let cmp_id = |a: UnitBytesId, b: UnitBytesId| cmp_id((a, a_strings), (b, b_strings));
cmp_eq(std::mem::discriminant(a), std::mem::discriminant(b))?;
match (a, b) {
(ArrayKey::Int(a), ArrayKey::Int(b)) => cmp_eq(a, b).qualified("int")?,
(ArrayKey::String(a), ArrayKey::String(b)) => cmp_id(*a, *b).qualified("string")?,
(ArrayKey::LazyClass(ClassId { id: a }), ArrayKey::LazyClass(ClassId { id: b })) => {
cmp_id(*a, *b).qualified("lazy_class")?
}
(ArrayKey::Int(_), _) | (ArrayKey::String(_), _) | (ArrayKey::LazyClass(_), _) => {
unreachable!()
}
}
Ok(())
}
fn cmp_typedef(
(a, a_strings): (&Typedef, &StringInterner),
(b, b_strings): (&Typedef, &StringInterner),
) -> Result {
let cmp_id = |a: UnitBytesId, b: UnitBytesId| cmp_id((a, a_strings), (b, b_strings));
let Typedef {
name: a_name,
attributes: a_attributes,
type_info_union: a_type_info_union,
type_structure: a_type_structure,
loc: a_loc,
attrs: a_attrs,
case_type: a_case_type,
} = a;
let Typedef {
name: b_name,
attributes: b_attributes,
type_info_union: b_type_info_union,
type_structure: b_type_structure,
loc: b_loc,
attrs: b_attrs,
case_type: b_case_type,
} = b;
cmp_id(a_name.id, b_name.id).qualified("name")?;
cmp_attributes((a_attributes, a_strings), (b_attributes, b_strings)).qualified("attributes")?;
cmp_slice(
a_type_info_union.iter().map(|i| (i, a_strings)),
b_type_info_union.iter().map(|i| (i, b_strings)),
cmp_type_info,
)?;
cmp_typed_value((a_type_structure, a_strings), (b_type_structure, b_strings))
.qualified("type_structure")?;
cmp_src_loc((a_loc, a_strings), (b_loc, b_strings)).qualified("loc")?;
cmp_eq(a_attrs, b_attrs).qualified("attrs")?;
cmp_eq(a_case_type, b_case_type).qualified("case_type")?;
Ok(())
}
fn cmp_unit(a_unit: &Unit<'_>, b_unit: &Unit<'_>) -> Result {
let Unit {
classes: a_classes,
constants: a_constants,
file_attributes: a_file_attributes,
functions: a_functions,
fatal: a_fatal,
modules: a_modules,
module_use: a_module_use,
strings: a_strings,
symbol_refs: a_symbol_refs,
typedefs: a_typedefs,
} = a_unit;
let Unit {
classes: b_classes,
constants: b_constants,
file_attributes: b_file_attributes,
functions: b_functions,
fatal: b_fatal,
modules: b_modules,
module_use: b_module_use,
strings: b_strings,
symbol_refs: b_symbol_refs,
typedefs: b_typedefs,
} = b_unit;
let a_strings = a_strings.as_ref();
let b_strings = b_strings.as_ref();
cmp_map_t(
a_classes.iter().map(|a| (a, a_strings)),
b_classes.iter().map(|b| (b, b_strings)),
cmp_class,
)
.qualified("classes")?;
cmp_map_t(
a_constants.iter().map(|a| (a, a_strings)),
b_constants.iter().map(|b| (b, b_strings)),
cmp_hack_constant,
)
.qualified("constants")?;
cmp_attributes(
(a_file_attributes, a_strings),
(b_file_attributes, b_strings),
)
.qualified("file_attributes")?;
cmp_map_t(
a_functions.iter().map(|a| (a, a_strings)),
b_functions.iter().map(|b| (b, b_strings)),
cmp_function,
)
.qualified("functions")?;
cmp_option(
a_fatal.as_ref().map(|a| (a, a_strings)),
b_fatal.as_ref().map(|b| (b, b_strings)),
cmp_fatal,
)
.qualified("fatal")?;
cmp_map_t(
a_modules.iter().map(|a| (a, a_strings)),
b_modules.iter().map(|b| (b, b_strings)),
cmp_module,
)
.qualified("modules")?;
cmp_option(a_module_use.as_ref(), b_module_use.as_ref(), cmp_eq).qualified("module_use")?;
cmp_symbol_refs(a_symbol_refs, b_symbol_refs).qualified("symbol_refs")?;
cmp_map_t(
a_typedefs.iter().map(|a| (a, a_strings)),
b_typedefs.iter().map(|b| (b, b_strings)),
cmp_typedef,
)
.qualified("typedefs")?;
Ok(())
}
fn cmp_upper_bounds(
(a, a_strings): (&(Str<'_>, Vec<TypeInfo>), &StringInterner),
(b, b_strings): (&(Str<'_>, Vec<TypeInfo>), &StringInterner),
) -> Result {
cmp_eq(a.0, b.0).qualified("key")?;
cmp_slice(
a.1.iter().map(|i| (i, a_strings)),
b.1.iter().map(|i| (i, b_strings)),
cmp_type_info,
)
.qualified("value")?;
Ok(())
}
mod mapping {
use super::*;
impl MapName for (&Attribute, &StringInterner) {
fn get_name(&self) -> String {
self.0.name.as_bstr(self.1).to_string()
}
}
impl MapName for (&Class<'_>, &StringInterner) {
fn get_name(&self) -> String {
self.0.name.as_bstr(self.1).to_string()
}
}
impl MapName for CtxConstant<'_> {
fn get_name(&self) -> String {
self.name.as_bstr().to_string()
}
}
impl MapName for (&ExFrameId, &ExFrame) {
fn get_name(&self) -> String {
self.0.to_string()
}
}
impl MapName for (&Function<'_>, &StringInterner) {
fn get_name(&self) -> String {
self.0.name.as_bstr(self.1).to_string()
}
}
impl MapName for (&HackConstant, &StringInterner) {
fn get_name(&self) -> String {
self.0.name.as_bstr(self.1).to_string()
}
}
impl MapName for (&Method<'_>, &StringInterner) {
fn get_name(&self) -> String {
self.0.name.as_bstr(self.1).to_string()
}
}
impl MapName for (&Module<'_>, &StringInterner) {
fn get_name(&self) -> String {
self.0.name.as_bstr(self.1).to_string()
}
}
impl MapName for (&Property<'_>, &StringInterner) {
fn get_name(&self) -> String {
self.0.name.as_bstr(self.1).to_string()
}
}
impl MapName for (&ClassId, &TParamBounds, &StringInterner) {
fn get_name(&self) -> String {
self.0.as_bstr(self.2).to_string()
}
}
impl MapName for (&Typedef, &StringInterner) {
fn get_name(&self) -> String {
self.0.name.as_bstr(self.1).to_string()
}
}
} |
Rust | hhvm/hphp/hack/src/hackc/cli/cmp_unit.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::fmt;
use ffi::Maybe;
use ffi::Slice;
use ffi::Str;
use hash::HashMap;
use hash::HashSet;
use hhbc::Attribute;
use hhbc::Body;
use hhbc::Class;
use hhbc::Constant;
use hhbc::Fatal;
use hhbc::Function;
use hhbc::Instruct;
use hhbc::Method;
use hhbc::Module;
use hhbc::Opcode;
use hhbc::Param;
use hhbc::Property;
use hhbc::Rule;
use hhbc::SymbolRefs;
use hhbc::TypeInfo;
use hhbc::TypedValue;
use hhbc::Typedef;
use hhbc::Unit;
#[derive(Debug, Hash, PartialEq, Eq)]
pub(crate) struct CmpError {
what: String,
loc: Option<String>,
}
impl CmpError {
pub fn error(what: String) -> Self {
CmpError { what, loc: None }
}
}
impl fmt::Display for CmpError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let loc = self.loc.as_ref().map_or("", String::as_str);
write!(f, "{}: {}", loc, self.what)
}
}
macro_rules! bail {
($msg:literal $(,)?) => {
return Err(CmpError::error(format!($msg)))
};
($err:expr $(,)?) => {
return Err(CmpError::error(format!($err)))
};
($fmt:expr, $($arg:tt)*) => {
return Err(CmpError::error(format!($fmt, $($arg)*)))
};
}
pub(crate) trait CmpContext {
fn with_indexed<F: FnOnce() -> String>(self, f: F) -> Self;
fn indexed(self, idx: &str) -> Self;
fn qualified(self, name: &str) -> Self;
fn with_raw<F: FnOnce() -> String>(self, f: F) -> Self;
}
impl<T> CmpContext for Result<T, CmpError> {
fn with_raw<F>(self, f: F) -> Self
where
F: FnOnce() -> String,
{
match self {
Ok(_) => self,
Err(CmpError { what, loc: None }) => Err(CmpError {
what,
loc: Some(f()),
}),
Err(CmpError {
what,
loc: Some(loc),
}) => Err(CmpError {
what,
loc: Some(format!("{}{loc}", f())),
}),
}
}
fn with_indexed<F>(self, f: F) -> Self
where
F: FnOnce() -> String,
{
self.with_raw(|| format!("[\"{}\"]", f()))
}
fn indexed(self, idx: &str) -> Self {
self.with_indexed(|| idx.to_string())
}
fn qualified(self, name: &str) -> Self {
self.with_raw(|| format!(".{name}"))
}
}
pub(crate) type Result<T = (), E = CmpError> = std::result::Result<T, E>;
pub(crate) trait MapName {
fn get_name(&self) -> String;
}
impl<T: MapName> MapName for &T {
fn get_name(&self) -> String {
T::get_name(self)
}
}
impl MapName for hhbc::Adata<'_> {
fn get_name(&self) -> String {
self.id.unsafe_as_str().to_string()
}
}
impl MapName for hhbc::Class<'_> {
fn get_name(&self) -> String {
self.name.unsafe_as_str().to_string()
}
}
impl MapName for hhbc::Constant<'_> {
fn get_name(&self) -> String {
self.name.unsafe_as_str().to_string()
}
}
impl MapName for hhbc::CtxConstant<'_> {
fn get_name(&self) -> String {
self.name.unsafe_as_str().to_string()
}
}
impl MapName for hhbc::Function<'_> {
fn get_name(&self) -> String {
self.name.unsafe_as_str().to_string()
}
}
impl MapName for hhbc::Method<'_> {
fn get_name(&self) -> String {
self.name.unsafe_as_str().to_string()
}
}
impl MapName for hhbc::Module<'_> {
fn get_name(&self) -> String {
self.name.unsafe_as_str().to_string()
}
}
impl MapName for hhbc::Property<'_> {
fn get_name(&self) -> String {
self.name.unsafe_as_str().to_string()
}
}
impl MapName for hhbc::Typedef<'_> {
fn get_name(&self) -> String {
self.name.unsafe_as_str().to_string()
}
}
impl MapName for hhbc::TypeConstant<'_> {
fn get_name(&self) -> String {
self.name.unsafe_as_str().to_string()
}
}
impl MapName for hhbc::Requirement<'_> {
fn get_name(&self) -> String {
self.name.unsafe_as_str().to_string()
}
}
impl MapName for hhbc::UpperBound<'_> {
fn get_name(&self) -> String {
self.name.unsafe_as_str().to_string()
}
}
pub(crate) fn cmp_eq<Ta, Tb>(a: Ta, b: Tb) -> Result
where
Ta: PartialEq<Tb> + fmt::Debug,
Tb: fmt::Debug,
{
if a != b {
bail!("Mismatch {:?} vs {:?}", a, b);
//panic!("Mismatch {:?} vs {:?}", a, b);
}
Ok(())
}
pub(crate) fn cmp_map_t<'a, 'b, Ta: 'a, Tb: 'b, F>(
a: impl IntoIterator<Item = Ta>,
b: impl IntoIterator<Item = Tb>,
f_eq: F,
) -> Result
where
Ta: MapName + 'a + Copy,
Tb: MapName + 'b + Copy,
F: Fn(Ta, Tb) -> Result,
{
let a_hash: HashMap<String, Ta> = a.into_iter().map(|t| (t.get_name(), t)).collect();
let b_hash: HashMap<String, Tb> = b.into_iter().map(|t| (t.get_name(), t)).collect();
let a_keys: HashSet<&String> = a_hash.keys().collect();
let b_keys: HashSet<&String> = b_hash.keys().collect();
for k in &a_keys & &b_keys {
f_eq(a_hash[k], b_hash[k]).with_indexed(|| k.to_string())?;
}
if let Some(k) = (&a_keys - &b_keys).into_iter().next() {
bail!("lhs has key {k} but rhs does not");
}
if let Some(k) = (&b_keys - &a_keys).into_iter().next() {
bail!("rhs has key {k} but lhs does not");
}
Ok(())
}
fn cmp_set_t<'a, T>(a: &'a [T], b: &'a [T]) -> Result
where
T: std::hash::Hash + Eq + std::fmt::Debug,
{
let a_keys: HashSet<&T> = a.iter().collect();
let b_keys: HashSet<&T> = b.iter().collect();
if let Some(k) = (&a_keys - &b_keys).into_iter().next() {
bail!("lhs has value {k:?} but rhs does not");
}
if let Some(k) = (&b_keys - &a_keys).into_iter().next() {
bail!("rhs has value {k:?} but lhs does not");
}
Ok(())
}
pub(crate) fn cmp_option<T, F>(a: Option<T>, b: Option<T>, f_eq: F) -> Result
where
T: std::fmt::Debug + Copy,
F: FnOnce(T, T) -> Result,
{
match (a, b) {
(None, None) => Ok(()),
(Some(a), None) => bail!("Some({a:?})\nNone"),
(None, Some(b)) => bail!("None\nSome({b:?})"),
(Some(lhs), Some(rhs)) => f_eq(lhs, rhs),
}
}
pub(crate) fn cmp_slice<'a, 'b, Ta, Tb, F>(
a: impl IntoIterator<Item = Ta>,
b: impl IntoIterator<Item = Tb>,
f_eq: F,
) -> Result
where
Ta: 'a + Copy,
Tb: 'b + Copy,
F: Fn(Ta, Tb) -> Result,
{
let mut a = a.into_iter();
let mut b = b.into_iter();
let mut idx = 0;
loop {
match (a.next(), b.next()) {
(None, None) => break,
(Some(_), None) => {
let rest = 1 + a.count();
bail!("Length mismatch: lhs is longer ({} vs {})", idx + rest, idx);
}
(None, Some(_)) => {
let rest = 1 + b.count();
bail!("Length mismatch: rhs is longer ({} vs {})", idx, idx + rest);
}
(Some(av), Some(bv)) => {
f_eq(av, bv).with_indexed(|| idx.to_string())?;
}
}
idx += 1;
}
Ok(())
}
/// Currently, some includes aren't printed out. So this is like the cmp_slice without a length check.
/// T126391106: BCP drops information
/// T126543346: Difficult to verify IncludeRootRelative
fn cmp_includes(
a: &Slice<'_, hhbc::IncludePath<'_>>,
b: &Slice<'_, hhbc::IncludePath<'_>>,
) -> Result {
for bv in b.iter() {
if !a.iter().any(|av| cmp_include(av, bv).is_ok()) {
bail!("{:?} has no matching includes", bv);
}
}
Ok(())
}
fn cmp_attributes(a: &[Attribute<'_>], b: &[Attribute<'_>]) -> Result {
cmp_set_t(a, b)
}
fn cmp_body(a: &Body<'_>, b: &Body<'_>) -> Result {
let Body {
body_instrs: a_body_instrs,
decl_vars: a_decl_vars,
num_iters: a_num_iters,
is_memoize_wrapper: a_is_memoize_wrapper,
is_memoize_wrapper_lsb: a_is_memoize_wrapper_lsb,
upper_bounds: a_upper_bounds,
shadowed_tparams: a_shadowed_tparams,
params: a_params,
return_type_info: a_return_type_info,
doc_comment: a_doc_comment,
stack_depth: a_stack_depth,
} = a;
let Body {
body_instrs: b_body_instrs,
decl_vars: b_decl_vars,
num_iters: b_num_iters,
is_memoize_wrapper: b_is_memoize_wrapper,
is_memoize_wrapper_lsb: b_is_memoize_wrapper_lsb,
upper_bounds: b_upper_bounds,
shadowed_tparams: b_shadowed_tparams,
params: b_params,
return_type_info: b_return_type_info,
doc_comment: b_doc_comment,
stack_depth: b_stack_depth,
} = b;
cmp_eq(a_num_iters, b_num_iters).qualified("num_iters")?;
cmp_slice(a_params, b_params, cmp_param).qualified("params")?;
cmp_eq(a_is_memoize_wrapper, b_is_memoize_wrapper).qualified("is_memoize_wrapper")?;
cmp_eq(a_is_memoize_wrapper_lsb, b_is_memoize_wrapper_lsb)
.qualified("is_memoize_wrapper_lsb")?;
cmp_eq(a_doc_comment, b_doc_comment).qualified("doc_comment")?;
cmp_eq(a_stack_depth, b_stack_depth).qualified("stack_depth")?;
cmp_eq(a_return_type_info, b_return_type_info).qualified("return_type_info")?;
cmp_eq(a_upper_bounds, b_upper_bounds).qualified("upper_bounds")?;
cmp_eq(a_shadowed_tparams, b_shadowed_tparams).qualified("shadowed_tparams")?;
cmp_set_t(a_decl_vars, b_decl_vars).qualified("decl_vars")?;
if a_body_instrs.len() != b_body_instrs.len() {
bail!(
"Mismatch in instruct lengths: {} vs {}",
a_body_instrs.len(),
b_body_instrs.len()
);
}
for (idx, (a_instr, b_instr)) in a_body_instrs.iter().zip(b_body_instrs.iter()).enumerate() {
cmp_instr(a_instr, b_instr)
.indexed(&idx.to_string())
.qualified("body_instrs")?;
}
Ok(())
}
/// This is unique because only a few FCAFlags are printed -- those specified in
/// as-base-hhas.h.
/// T126391106 -- BCP drops information
fn cmp_fcallargflags(a: &hhbc::FCallArgsFlags, b: &hhbc::FCallArgsFlags) -> Result {
use hhbc::FCallArgsFlags;
let mut not_printed = FCallArgsFlags::SkipRepack;
not_printed.add(FCallArgsFlags::SkipCoeffectsCheck);
not_printed.add(FCallArgsFlags::ExplicitContext);
not_printed.add(FCallArgsFlags::HasInOut);
not_printed.add(FCallArgsFlags::EnforceInOut);
not_printed.add(FCallArgsFlags::EnforceReadonly);
not_printed.add(FCallArgsFlags::HasAsyncEagerOffset);
not_printed.add(FCallArgsFlags::NumArgsStart);
let mut a = a.clone();
let mut b = b.clone();
a.repr &= !(not_printed.repr);
b.repr &= !(not_printed.repr);
cmp_eq(&a, &b)?;
Ok(())
}
fn cmp_fcallargs(a: &hhbc::FCallArgs<'_>, b: &hhbc::FCallArgs<'_>) -> Result {
let hhbc::FCallArgs {
flags: a_flags,
async_eager_target: a_aet,
num_args: a_num_args,
num_rets: a_num_rets,
inouts: a_inouts,
readonly: a_readonly,
context: a_context,
} = a;
let hhbc::FCallArgs {
flags: b_flags,
async_eager_target: b_aet,
num_args: b_num_args,
num_rets: b_num_rets,
inouts: b_inouts,
readonly: b_readonly,
context: b_context,
} = b;
cmp_fcallargflags(a_flags, b_flags).qualified("fcallargflags")?;
cmp_eq(a_aet, b_aet)?;
cmp_eq(a_num_args, b_num_args)?;
cmp_eq(a_num_rets, b_num_rets)?;
cmp_eq(a_inouts, b_inouts)?;
cmp_eq(a_readonly, b_readonly)?;
cmp_eq(a_context, b_context)?;
Ok(())
}
fn cmp_fcall_instr(a: &Opcode<'_>, b: &Opcode<'_>) -> Result {
match (a, b) {
(hhbc::Opcode::FCallClsMethod(fa, a1, a2), hhbc::Opcode::FCallClsMethod(fb, b1, b2)) => {
cmp_fcallargs(fa, fb)?;
cmp_eq(a1, b1)?;
cmp_eq(a2, b2)?;
}
(hhbc::Opcode::FCallClsMethodD(fa, a1, a2), hhbc::Opcode::FCallClsMethodD(fb, b1, b2)) => {
cmp_fcallargs(fa, fb)?;
cmp_eq(a1, b1)?;
cmp_eq(a2, b2)?;
}
(hhbc::Opcode::FCallClsMethodS(fa, a1, a2), hhbc::Opcode::FCallClsMethodS(fb, b1, b2)) => {
cmp_fcallargs(fa, fb)?;
cmp_eq(a1, b1)?;
cmp_eq(a2, b2)?;
}
(hhbc::Opcode::FCallObjMethod(fa, a1, a2), hhbc::Opcode::FCallObjMethod(fb, b1, b2)) => {
cmp_fcallargs(fa, fb)?;
cmp_eq(a1, b1)?;
cmp_eq(a2, b2)?;
}
(
hhbc::Opcode::FCallClsMethodM(fa, a1, a2, a3),
hhbc::Opcode::FCallClsMethodM(fb, b1, b2, b3),
) => {
cmp_fcallargs(fa, fb)?;
cmp_eq(a1, b1)?;
cmp_eq(a2, b2)?;
cmp_eq(a3, b3)?;
}
(
hhbc::Opcode::FCallClsMethodSD(fa, a1, a2, a3),
hhbc::Opcode::FCallClsMethodSD(fb, b1, b2, b3),
) => {
cmp_fcallargs(fa, fb)?;
cmp_eq(a1, b1)?;
cmp_eq(a2, b2)?;
cmp_eq(a3, b3)?;
}
(
hhbc::Opcode::FCallObjMethodD(fa, a1, a2, a3),
hhbc::Opcode::FCallObjMethodD(fb, b1, b2, b3),
) => {
cmp_fcallargs(fa, fb)?;
cmp_eq(a1, b1)?;
cmp_eq(a2, b2)?;
cmp_eq(a3, b3)?;
}
(hhbc::Opcode::FCallCtor(fa, a1), hhbc::Opcode::FCallCtor(fb, b1)) => {
cmp_fcallargs(fa, fb)?;
cmp_eq(a1, b1)?;
}
(hhbc::Opcode::FCallFuncD(fa, a1), hhbc::Opcode::FCallFuncD(fb, b1)) => {
cmp_fcallargs(fa, fb)?;
cmp_eq(a1, b1)?;
}
(hhbc::Opcode::FCallFunc(fa), hhbc::Opcode::FCallFunc(fb)) => {
cmp_fcallargs(fa, fb)?;
}
_ => bail!(
"Instruct mismatch: {} vs {}",
a.variant_name(),
b.variant_name()
),
};
Ok(())
}
fn cmp_instr(a: &Instruct<'_>, b: &Instruct<'_>) -> Result {
if a == b {
return Ok(());
}
if let (Instruct::Opcode(a), Instruct::Opcode(b)) = (a, b) {
match a {
hhbc::Opcode::FCallClsMethod(..)
| hhbc::Opcode::FCallClsMethodM(..)
| hhbc::Opcode::FCallClsMethodD(..)
| hhbc::Opcode::FCallClsMethodS(..)
| hhbc::Opcode::FCallClsMethodSD(..)
| hhbc::Opcode::FCallCtor(..)
| hhbc::Opcode::FCallFunc(..)
| hhbc::Opcode::FCallFuncD(..)
| hhbc::Opcode::FCallObjMethod(..)
| hhbc::Opcode::FCallObjMethodD(..) => {
return cmp_fcall_instr(a, b);
}
_ => bail!(
"Instruct mismatch: {} vs {}",
a.variant_name(),
b.variant_name()
),
}
}
bail!(
"Instruct mismatch: {} vs {}",
a.variant_name(),
b.variant_name()
)
}
fn cmp_param(a: &Param<'_>, b: &Param<'_>) -> Result {
let Param {
name: a_name,
is_variadic: a_is_variadic,
is_inout: a_is_inout,
is_readonly: a_is_readonly,
user_attributes: a_user_attributes,
type_info: a_type_info,
default_value: a_default_value,
} = a;
let Param {
name: b_name,
is_variadic: b_is_variadic,
is_inout: b_is_inout,
is_readonly: b_is_readonly,
user_attributes: b_user_attributes,
type_info: b_type_info,
default_value: b_default_value,
} = b;
cmp_eq(a_name, b_name).qualified("name")?;
cmp_eq(a_is_variadic, b_is_variadic).qualified("is_variadic")?;
cmp_eq(a_is_inout, b_is_inout).qualified("is_inout")?;
cmp_eq(a_is_readonly, b_is_readonly).qualified("is_readonly")?;
// T126391106 -- BCP sorts attributes of parameters before printing.
cmp_attributes(a_user_attributes, b_user_attributes).qualified("user_attributes")?;
cmp_eq(a_type_info, b_type_info).qualified("type_info")?;
cmp_option(
a_default_value.as_ref().into_option(),
b_default_value.as_ref().into_option(),
|a, b| cmp_eq(&a.expr, &b.expr),
)
.qualified("default_value")?;
Ok(())
}
fn cmp_class(a: &Class<'_>, b: &Class<'_>) -> Result {
let Class {
attributes: a_attributes,
base: a_base,
implements: a_implements,
enum_includes: a_enum_includes,
name: a_name,
span: a_span,
uses: a_uses,
enum_type: a_enum_type,
methods: a_methods,
properties: a_properties,
constants: a_constants,
type_constants: a_type_constants,
ctx_constants: a_ctx_constants,
requirements: a_requirements,
upper_bounds: a_upper_bounds,
doc_comment: a_doc_comment,
flags: a_flags,
} = a;
let Class {
attributes: b_attributes,
base: b_base,
implements: b_implements,
enum_includes: b_enum_includes,
name: b_name,
span: b_span,
uses: b_uses,
enum_type: b_enum_type,
methods: b_methods,
properties: b_properties,
constants: b_constants,
type_constants: b_type_constants,
ctx_constants: b_ctx_constants,
requirements: b_requirements,
upper_bounds: b_upper_bounds,
doc_comment: b_doc_comment,
flags: b_flags,
} = b;
cmp_eq(a_name, b_name).qualified("name")?;
cmp_attributes(a_attributes, b_attributes).qualified("attributes")?;
cmp_eq(a_base, b_base).qualified("base")?;
cmp_eq(a_implements, b_implements).qualified("implements")?;
cmp_eq(a_enum_includes, b_enum_includes).qualified("enum_includes")?;
cmp_eq(a_span, b_span).qualified("span")?;
cmp_eq(a_uses, b_uses).qualified("uses")?;
cmp_option(
a_enum_type.as_ref().into_option(),
b_enum_type.as_ref().into_option(),
cmp_eq,
)
.qualified("enum_type")?;
cmp_map_t(a_properties, b_properties, cmp_properties).qualified("properties")?;
cmp_map_t(a_constants, b_constants, cmp_constant).qualified("constants")?;
cmp_map_t(a_type_constants, b_type_constants, cmp_eq).qualified("type_constants")?;
cmp_map_t(a_ctx_constants, b_ctx_constants, cmp_eq).qualified("ctx_constants")?;
cmp_map_t(a_requirements, b_requirements, |a, b| {
cmp_eq(&a.kind, &b.kind)
})
.qualified("requirements")?;
cmp_map_t(a_upper_bounds, b_upper_bounds, |a, b| {
cmp_slice(&a.bounds, &b.bounds, cmp_eq)
})
.qualified("upper_bounds")?;
cmp_eq(a_doc_comment, b_doc_comment).qualified("doc_comment")?;
cmp_eq(a_flags, b_flags).qualified("flags")?;
cmp_map_t(a_methods, b_methods, cmp_method).qualified("methods")?;
Ok(())
}
fn cmp_properties(a: &Property<'_>, b: &Property<'_>) -> Result {
let Property {
name: a_name,
flags: a_flags,
attributes: a_attributes,
visibility: a_visibility,
initial_value: a_initial_value,
type_info: a_type_info,
doc_comment: a_doc_comment,
} = a;
let Property {
name: b_name,
flags: b_flags,
attributes: b_attributes,
visibility: b_visibility,
initial_value: b_initial_value,
type_info: b_type_info,
doc_comment: b_doc_comment,
} = b;
cmp_eq(a_name, b_name).qualified("name")?;
cmp_eq(a_flags, b_flags).qualified("flags")?;
cmp_attributes(a_attributes, b_attributes).qualified("attributes")?;
cmp_eq(a_visibility, b_visibility).qualified("visibilitiy")?;
cmp_initial_value(a_initial_value, b_initial_value).qualified("initial value")?;
cmp_eq(a_type_info, b_type_info).qualified("type info")?;
cmp_eq(a_doc_comment, b_doc_comment).qualified("doc_comment")?;
Ok(())
}
// T126391106: BCP/HCU is not consistent -- if there is no initial value the underlying
// HCU may have Just(Null) or Nothing in that slot.
fn cmp_initial_value(a: &Maybe<TypedValue<'_>>, b: &Maybe<TypedValue<'_>>) -> Result {
match (a, b) {
(Maybe::Nothing, Maybe::Just(TypedValue::Null))
| (Maybe::Just(TypedValue::Null), Maybe::Nothing) => Ok(()),
_ => cmp_eq(a, b),
}
}
fn cmp_constant(a: &Constant<'_>, b: &Constant<'_>) -> Result {
let Constant {
name: a_name,
value: a_value,
attrs: a_attrs,
} = a;
let Constant {
name: b_name,
value: b_value,
attrs: b_attrs,
} = b;
cmp_eq(a_name, b_name).qualified("name")?;
cmp_option(
a_value.as_ref().into_option(),
b_value.as_ref().into_option(),
cmp_eq,
)
.qualified("value")?;
cmp_eq(a_attrs, b_attrs).qualified("attrs")?;
Ok(())
}
fn cmp_fatal(a: &Fatal<'_>, b: &Fatal<'_>) -> Result {
cmp_eq(&a.op, &b.op).qualified("op")?;
cmp_eq(&a.loc, &b.loc).qualified("loc")?;
cmp_eq(&a.message, &b.message).qualified("message")?;
Ok(())
}
fn is_pure(sc: &[naming_special_names_rust::coeffects::Ctx], usc: &[Str<'_>]) -> bool {
(sc.len() == 1
&& sc.contains(&naming_special_names_rust::coeffects::Ctx::Pure)
&& usc.is_empty())
|| (sc.is_empty() && usc.len() == 1 && usc.iter().all(|usc| usc.as_bstr() == "pure"))
}
fn cmp_static_coeffects(
a_sc: &[naming_special_names_rust::coeffects::Ctx],
a_usc: &[Str<'_>],
b_sc: &[naming_special_names_rust::coeffects::Ctx],
b_usc: &[Str<'_>],
) -> Result {
// T126548142 -- odd "pure" behavior
if is_pure(a_sc, a_usc) && is_pure(b_sc, b_usc) {
Ok(())
} else {
cmp_eq(a_sc, b_sc).qualified("Static coeffecients")?;
cmp_eq(a_usc, b_usc).qualified("Unenforced static coeffecients")?;
Ok(())
}
}
pub(crate) fn cmp_coeffects(a: &hhbc::Coeffects<'_>, b: &hhbc::Coeffects<'_>) -> Result {
let hhbc::Coeffects {
static_coeffects: a_sc,
unenforced_static_coeffects: a_usc,
fun_param: a_fp,
cc_param: a_cp,
cc_this: a_ct,
cc_reified: a_cr,
closure_parent_scope: a_cps,
generator_this: a_gt,
caller: a_c,
} = a;
let hhbc::Coeffects {
static_coeffects: b_sc,
unenforced_static_coeffects: b_usc,
fun_param: b_fp,
cc_param: b_cp,
cc_this: b_ct,
cc_reified: b_cr,
closure_parent_scope: b_cps,
generator_this: b_gt,
caller: b_c,
} = b;
cmp_static_coeffects(a_sc, a_usc, b_sc, b_usc)?;
cmp_eq(a_fp, b_fp)?;
cmp_eq(a_cp, b_cp)?;
cmp_eq(a_ct, b_ct)?;
cmp_eq(a_cr, b_cr)?;
cmp_eq(&a_cps, &b_cps)?;
cmp_eq(&a_gt, &b_gt)?;
cmp_eq(&a_c, &b_c)?;
Ok(())
}
fn cmp_function(a: &Function<'_>, b: &Function<'_>) -> Result {
let Function {
attributes: a_attributes,
name: a_name,
body: a_body,
span: a_span,
coeffects: a_coeffects,
flags: a_flags,
attrs: a_attrs,
} = a;
let Function {
attributes: b_attributes,
name: b_name,
body: b_body,
span: b_span,
coeffects: b_coeffects,
flags: b_flags,
attrs: b_attrs,
} = b;
cmp_eq(a_name, b_name).qualified("name")?;
cmp_attributes(a_attributes, b_attributes).qualified("attributes")?;
cmp_body(a_body, b_body).qualified("body")?;
cmp_eq(a_span, b_span).qualified("span")?;
cmp_coeffects(a_coeffects, b_coeffects).qualified("coeffects")?;
cmp_eq(a_flags, b_flags).qualified("flags")?;
cmp_eq(a_attrs, b_attrs).qualified("attrs")?;
Ok(())
}
fn cmp_method(a: &Method<'_>, b: &Method<'_>) -> Result {
let Method {
attributes: a_attributes,
visibility: a_visibility,
name: a_name,
body: a_body,
span: a_span,
coeffects: a_coeffects,
flags: a_flags,
attrs: a_attrs,
} = a;
let Method {
attributes: b_attributes,
visibility: b_visibility,
name: b_name,
body: b_body,
span: b_span,
coeffects: b_coeffects,
flags: b_flags,
attrs: b_attrs,
} = b;
cmp_attributes(a_attributes, b_attributes).qualified("attributes")?;
cmp_eq(a_visibility, b_visibility).qualified("visibility")?;
cmp_eq(a_name, b_name).qualified("name")?;
cmp_body(a_body, b_body).qualified("body")?;
cmp_eq(a_span, b_span).qualified("span")?;
cmp_coeffects(a_coeffects, b_coeffects).qualified("coeffects")?;
cmp_eq(a_flags, b_flags).qualified("flags")?;
cmp_eq(a_attrs, b_attrs).qualified("attrs")?;
Ok(())
}
fn cmp_rule(a: &Rule<'_>, b: &Rule<'_>) -> Result {
let Rule {
kind: a_kind,
name: a_name,
} = a;
let Rule {
kind: b_kind,
name: b_name,
} = b;
cmp_eq(a_kind, b_kind).qualified("kind")?;
cmp_eq(a_name, b_name).qualified("name")?;
Ok(())
}
fn cmp_module(a: &Module<'_>, b: &Module<'_>) -> Result {
let Module {
attributes: a_attributes,
name: a_name,
span: a_span,
doc_comment: a_doc_comment,
exports: a_exports,
imports: a_imports,
} = a;
let Module {
attributes: b_attributes,
name: b_name,
span: b_span,
doc_comment: b_doc_comment,
exports: b_exports,
imports: b_imports,
} = b;
cmp_eq(a_name, b_name).qualified("name")?;
cmp_attributes(a_attributes, b_attributes).qualified("attributes")?;
cmp_eq(a_span, b_span).qualified("span")?;
cmp_eq(a_doc_comment, b_doc_comment).qualified("doc_comment")?;
cmp_option(
a_exports.as_ref().into_option(),
b_exports.as_ref().into_option(),
|a, b| cmp_slice(a, b, cmp_rule),
)
.qualified("exports")?;
cmp_option(
a_imports.as_ref().into_option(),
b_imports.as_ref().into_option(),
|a, b| cmp_slice(a, b, cmp_rule),
)
.qualified("imports")?;
Ok(())
}
/// Compares two include paths. a can be a relative path and b an aboslute path as long as
/// a is the end of b
fn cmp_include(a: &hhbc::IncludePath<'_>, b: &hhbc::IncludePath<'_>) -> Result {
if a != b {
match (a, b) {
(hhbc::IncludePath::SearchPathRelative(a_bs), hhbc::IncludePath::Absolute(b_bs)) => {
let a_bs = a_bs.as_bstr();
let b_bs = b_bs.as_bstr();
if b_bs.ends_with(a_bs) {
Ok(())
} else {
bail!("Mismatch {:?} vs {:?}", a, b)
}
}
(hhbc::IncludePath::IncludeRootRelative(_, _), hhbc::IncludePath::Absolute(_)) => {
Ok(())
}
_ => bail!("Mismatch {:?} vs {:?}", a, b),
}
} else {
Ok(())
}
}
fn cmp_symbol_refs(a: &SymbolRefs<'_>, b: &SymbolRefs<'_>) -> Result {
let SymbolRefs {
includes: a_includes,
constants: a_constants,
functions: a_functions,
classes: a_classes,
} = a;
let SymbolRefs {
includes: b_includes,
constants: b_constants,
functions: b_functions,
classes: b_classes,
} = b;
cmp_includes(a_includes, b_includes).qualified("includes")?;
cmp_slice(a_constants, b_constants, cmp_eq).qualified("constants")?;
cmp_slice(a_functions, b_functions, cmp_eq).qualified("functions")?;
cmp_slice(a_classes, b_classes, cmp_eq).qualified("classes")?;
Ok(())
}
/// T126391106: BCP drops information -- &s TCF with nullable before printing.
fn cmp_type_constraint_flags(
a: &hhvm_types_ffi::ffi::TypeConstraintFlags,
b: &hhvm_types_ffi::ffi::TypeConstraintFlags,
) -> Result {
use hhvm_types_ffi::ffi::TypeConstraintFlags;
let a_flags = *a & TypeConstraintFlags::Nullable;
let b_flags = *b & TypeConstraintFlags::Nullable;
cmp_eq(&a_flags, &b_flags).qualified("TypeConstraintFlags")?;
Ok(())
}
// T126391106: BCP doesn't disambiguate a constraint name of Just("") and Nothing
fn cmp_type_constraint_name(a: &Maybe<Str<'_>>, b: &Maybe<Str<'_>>) -> Result {
match (a, b) {
(Maybe::Nothing, Maybe::Just(s)) | (Maybe::Just(s), Maybe::Nothing) => {
if s.as_bstr() == "" {
Ok(())
} else {
bail!("Constraint name mismatch: {:?} vs {:?}", a, b)
}
}
(a, b) => cmp_eq(a, b),
}
}
fn cmp_type_constraint(a: &hhbc::Constraint<'_>, b: &hhbc::Constraint<'_>) -> Result {
let hhbc::Constraint {
name: a_name,
flags: a_flags,
} = a;
let hhbc::Constraint {
name: b_name,
flags: b_flags,
} = b;
cmp_type_constraint_name(a_name, b_name).qualified("constraints")?;
cmp_type_constraint_flags(a_flags, b_flags)?;
Ok(())
}
/// User_type isn't printed in typedef's typeinfo.
fn cmp_typedef_typeinfo(a: &TypeInfo<'_>, b: &TypeInfo<'_>) -> Result {
let TypeInfo {
user_type: _a_user_type,
type_constraint: a_constraint,
} = a;
let TypeInfo {
user_type: _b_user_type,
type_constraint: b_constraint,
} = b;
cmp_type_constraint(a_constraint, b_constraint).qualified("constraints")?;
Ok(())
}
fn cmp_typedef(a: &Typedef<'_>, b: &Typedef<'_>) -> Result {
let Typedef {
name: a_name,
attributes: a_attributes,
type_info_union: a_type_info_union,
type_structure: a_type_structure,
span: a_span,
attrs: a_attrs,
case_type: a_case_type,
} = a;
let Typedef {
name: b_name,
attributes: b_attributes,
type_info_union: b_type_info_union,
type_structure: b_type_structure,
span: b_span,
attrs: b_attrs,
case_type: b_case_type,
} = b;
cmp_eq(a_name, b_name).qualified("name")?;
cmp_attributes(a_attributes, b_attributes).qualified("attributes")?;
cmp_slice(a_type_info_union, b_type_info_union, cmp_typedef_typeinfo)
.qualified("type_info_union")?;
cmp_eq(a_type_structure, b_type_structure).qualified("type_structure")?;
cmp_eq(a_span, b_span).qualified("span")?;
cmp_eq(a_attrs, b_attrs).qualified("attrs")?;
cmp_eq(a_case_type, b_case_type).qualified("case_type")?;
Ok(())
}
fn cmp_unit(a_unit: &Unit<'_>, b_unit: &Unit<'_>) -> Result {
let Unit {
adata: a_adata,
functions: a_functions,
classes: a_classes,
modules: a_modules,
typedefs: a_typedefs,
file_attributes: a_file_attributes,
module_use: a_module_use,
symbol_refs: a_symbol_refs,
constants: a_constants,
fatal: a_fatal,
missing_symbols: _,
error_symbols: _,
} = a_unit;
let Unit {
adata: b_adata,
functions: b_functions,
classes: b_classes,
modules: b_modules,
typedefs: b_typedefs,
file_attributes: b_file_attributes,
module_use: b_module_use,
symbol_refs: b_symbol_refs,
constants: b_constants,
fatal: b_fatal,
missing_symbols: _,
error_symbols: _,
} = b_unit;
cmp_map_t(a_adata, b_adata, cmp_eq).qualified("adata")?;
cmp_map_t(a_typedefs, b_typedefs, cmp_typedef).qualified("typedefs")?;
cmp_attributes(a_file_attributes, b_file_attributes).qualified("file_attributes")?;
cmp_option(
a_fatal.as_ref().into_option(),
b_fatal.as_ref().into_option(),
cmp_fatal,
)
.qualified("fatal")?;
cmp_map_t(a_constants, b_constants, cmp_constant).qualified("constants")?;
cmp_symbol_refs(a_symbol_refs, b_symbol_refs).qualified("symbol_refs")?;
cmp_map_t(a_modules, b_modules, cmp_module).qualified("modules")?;
cmp_option(
a_module_use.as_ref().into_option(),
b_module_use.as_ref().into_option(),
cmp_eq,
)
.qualified("module_use")?;
cmp_map_t(
a_functions.as_arena_ref(),
b_functions.as_arena_ref(),
cmp_function,
)
.qualified("functions")?;
cmp_map_t(
a_classes.as_arena_ref(),
b_classes.as_arena_ref(),
cmp_class,
)
.qualified("classes")?;
Ok(())
}
/// Fancy version of `PartialEq::eq(a, b)` which also tries to report exactly
/// where the mismatch occurred.
pub(crate) fn cmp_hack_c_unit(a: &Unit<'_>, b: &Unit<'_>) -> Result {
cmp_unit(a, b).with_raw(|| "unit".to_string())
} |
Rust | hhvm/hphp/hack/src/hackc/cli/compile.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::cell::RefCell;
use std::fs::File;
use std::io::stdout;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use anyhow::Context;
use anyhow::Result;
use clap::Args;
use clap::Parser;
use compile::EnvFlags;
use compile::NativeEnv;
use compile::Profile;
use decl_parser::DeclParser;
use decl_parser::DeclParserOptions;
use decl_provider::ConstDecl;
use decl_provider::DeclProvider;
use decl_provider::Error;
use decl_provider::FunDecl;
use decl_provider::ModuleDecl;
use decl_provider::SelfProvider;
use decl_provider::TypeDecl;
use direct_decl_parser::Decls;
use hackrs_test_utils::serde_store::StoreOpts;
use hackrs_test_utils::store::make_shallow_decl_store;
use hhvm_options::HhvmOptions;
use multifile_rust as multifile;
use naming_provider::SqliteNamingTable;
use options::Hhvm;
use options::ParserOptions;
use parking_lot::Mutex;
use parser_core_types::source_text::SourceText;
use pos::ConstName;
use pos::FunName;
use pos::RelativePathCtx;
use pos::ToOxidized;
use pos::TypeName;
use rayon::prelude::*;
use relative_path::Prefix;
use relative_path::RelativePath;
use shallow_decl_provider::LazyShallowDeclProvider;
use shallow_decl_provider::ShallowDeclProvider;
use tempdir::TempDir;
use ty::reason::NReason;
use ty::reason::Reason;
use crate::util::SyncWrite;
use crate::FileOpts;
#[derive(Args, Debug)]
pub struct Opts {
/// Output file. Creates it if necessary
#[clap(short = 'o')]
output_file: Option<PathBuf>,
#[command(flatten)]
files: FileOpts,
#[command(flatten)]
single_file_opts: SingleFileOpts,
}
#[derive(Parser, Debug)]
pub(crate) struct SingleFileOpts {
#[command(flatten)]
pub(crate) env_flags: EnvFlags,
#[command(flatten)]
hhvm_options: HhvmOptions,
/// Unwrap concurrent blocks as a regular sequence of awaits.
///
/// Currently, used only for infer/textual.
#[clap(long, action, hide(true))]
pub(crate) unwrap_concurrent: bool,
/// The level of verbosity (can be set multiple times)
#[clap(long = "verbose", action(clap::ArgAction::Count))]
pub(crate) verbosity: u8,
}
pub fn run(opts: &mut Opts) -> Result<()> {
if opts.single_file_opts.verbosity > 1 {
eprintln!("hackc compile options/flags: {:#?}", opts);
}
let writer: SyncWrite = match &opts.output_file {
None => Mutex::new(Box::new(stdout())),
Some(output_file) => Mutex::new(Box::new(File::create(output_file)?)),
};
let files = opts.files.gather_input_files()?;
// Collect a Vec first so we process all files - not just up to the first failure.
files
.into_par_iter()
.map(|path| process_one_file(&path, opts, &writer))
.collect::<Vec<_>>()
.into_iter()
.collect()
}
/// Process a single physical file by breaking it into multiple logical
/// files (using multifile) and then processing each of those with
/// process_single_file().
///
/// If an error occurs then continue to process as much as possible,
/// returning the first error that occured.
fn process_one_file(f: &Path, opts: &Opts, w: &SyncWrite) -> Result<()> {
let content = std::fs::read(f)?;
let files = multifile::to_files(f, content)?;
// Collect a Vec so we process all files - not just up to the first
// failure.
let results: Vec<Result<()>> = files
.into_iter()
.map(|(f, content)| {
let f = f.as_ref();
match process_single_file(
&opts.single_file_opts,
f.into(),
content,
&mut Profile::default(),
) {
Err(e) => {
writeln!(w.lock(), "Error in file {}: {}", f.display(), e)?;
Err(e)
}
Ok(output) => {
w.lock().write_all(&output)?;
Ok(())
}
}
})
.collect();
results.into_iter().collect()
}
pub(crate) fn native_env(filepath: RelativePath, opts: &SingleFileOpts) -> Result<NativeEnv> {
let hhvm_options = &opts.hhvm_options;
let hhvm_config = hhvm_options.to_config()?;
let parser_options = ParserOptions {
po_auto_namespace_map: auto_namespace_map().collect(),
po_unwrap_concurrent: opts.unwrap_concurrent,
..hhvm_config::parser_options(&hhvm_config)?
};
let hhbc_flags = hhvm_config::hhbc_flags(&hhvm_config)?;
Ok(NativeEnv {
filepath,
hhbc_flags,
hhvm: Hhvm {
include_roots: Default::default(),
renamable_functions: Default::default(),
non_interceptable_functions: Default::default(),
parser_options,
jit_enable_rename_function: hhvm_config::jit_enable_rename_function(&hhvm_config)?,
},
flags: opts.env_flags.clone(),
})
}
pub(crate) fn process_single_file(
opts: &SingleFileOpts,
filepath: PathBuf,
content: Vec<u8>,
profile: &mut Profile,
) -> Result<Vec<u8>> {
if opts.verbosity > 1 {
eprintln!("processing file: {}", filepath.display());
}
let filepath = RelativePath::make(Prefix::Dummy, filepath);
let source_text = SourceText::make(Arc::new(filepath.clone()), &content);
let env = native_env(filepath, opts)?;
let mut output = Vec::new();
let decl_arena = bumpalo::Bump::new();
let decl_provider = SelfProvider::wrap_existing_provider(
None,
env.to_decl_parser_options(),
source_text.clone(),
&decl_arena,
);
compile::from_text(&mut output, source_text, &env, decl_provider, profile)?;
if opts.verbosity >= 1 {
eprintln!("{}: {:#?}", env.filepath.path().display(), profile);
}
Ok(output)
}
pub(crate) fn compile_from_text(hackc_opts: &mut crate::Opts, w: &mut impl Write) -> Result<()> {
let files = hackc_opts.files.gather_input_files()?;
for path in files {
let source_text = std::fs::read(&path)
.with_context(|| format!("Unable to read file '{}'", path.display()))?;
let env = hackc_opts.native_env(path)?;
let decl_arena = bumpalo::Bump::new();
let text = SourceText::make(Arc::new(env.filepath.clone()), &source_text);
let decl_provider = SelfProvider::wrap_existing_provider(
None,
env.to_decl_parser_options(),
text,
&decl_arena,
);
let hhas = compile_impl(env, source_text, decl_provider)?;
w.write_all(&hhas)?;
}
Ok(())
}
fn compile_impl<'d>(
env: NativeEnv,
source_text: Vec<u8>,
decl_provider: Option<Arc<dyn DeclProvider<'d> + 'd>>,
) -> Result<Vec<u8>> {
let text = SourceText::make(Arc::new(env.filepath.clone()), &source_text);
let mut hhas = Vec::new();
compile::from_text(
&mut hhas,
text,
&env,
decl_provider,
&mut Default::default(), // profile
)?;
Ok(hhas)
}
pub(crate) fn daemon(hackc_opts: &mut crate::Opts) -> Result<()> {
crate::daemon_loop(|path, w| {
hackc_opts.files.filenames = vec![path];
compile_from_text(hackc_opts, w)
})
}
pub(crate) fn test_decl_compile(hackc_opts: &mut crate::Opts, w: &mut impl Write) -> Result<()> {
let files = hackc_opts.files.gather_input_files()?;
for path in files {
let source_text = std::fs::read(&path)?;
// Parse decls
let decl_opts = hackc_opts.decl_opts();
let filename = RelativePath::make(Prefix::Root, path.clone());
let arena = bumpalo::Bump::new();
let parsed_file = direct_decl_parser::parse_decls_for_bytecode(
&decl_opts,
filename,
&source_text,
&arena,
);
let provider: Arc<SingleDeclProvider<'_, NReason>> = Arc::new(SingleDeclProvider::make(
&arena,
parsed_file.decls,
hackc_opts,
)?);
let env = hackc_opts.native_env(path)?;
let hhas = compile_impl(env, source_text, Some(provider.clone()))?;
if hackc_opts.log_decls_requested {
for a in provider.type_requests.borrow().iter() {
println!("type/{}: {}, {}", a.depth, a.symbol, a.found);
}
println!();
} else {
w.write_all(&hhas)?;
}
}
Ok(())
}
pub(crate) fn test_decl_compile_daemon(hackc_opts: &mut crate::Opts) -> Result<()> {
crate::daemon_loop(|path, w| {
hackc_opts.files.filenames = vec![path];
test_decl_compile(hackc_opts, w)
})
}
// TODO (T118266805): get these from nearest .hhconfig enclosing each file.
pub(crate) fn auto_namespace_map() -> impl Iterator<Item = (String, String)> {
[
("Async", "HH\\Lib\\Async"),
("C", "FlibSL\\C"),
("Dict", "FlibSL\\Dict"),
("File", "HH\\Lib\\File"),
("IO", "HH\\Lib\\IO"),
("Keyset", "FlibSL\\Keyset"),
("Locale", "FlibSL\\Locale"),
("Math", "FlibSL\\Math"),
("OS", "HH\\Lib\\OS"),
("PHP", "FlibSL\\PHP"),
("PseudoRandom", "FlibSL\\PseudoRandom"),
("Regex", "FlibSL\\Regex"),
("SecureRandom", "FlibSL\\SecureRandom"),
("Str", "FlibSL\\Str"),
("Vec", "FlibSL\\Vec"),
]
.into_iter()
.map(|(k, v)| (k.into(), v.into()))
}
#[derive(Debug)]
enum DeclsHolder<'a> {
ByRef(Decls<'a>),
Ser(Vec<u8>),
}
#[derive(Debug)]
struct Access {
symbol: String,
depth: u64,
found: bool,
}
#[derive(Debug)]
struct SingleDeclProvider<'a, R: Reason> {
arena: &'a bumpalo::Bump,
decls: DeclsHolder<'a>,
shallow_decl_provider: Option<Arc<dyn ShallowDeclProvider<R>>>,
type_requests: RefCell<Vec<Access>>,
func_requests: RefCell<Vec<Access>>,
const_requests: RefCell<Vec<Access>>,
module_requests: RefCell<Vec<Access>>,
}
impl<'a, R: Reason> DeclProvider<'a> for SingleDeclProvider<'a, R> {
fn type_decl(&self, symbol: &str, depth: u64) -> Result<TypeDecl<'a>, Error> {
let decl = {
let decl = self.find_decl(|decls| decl_provider::find_type_decl(decls, symbol));
match (&decl, self.shallow_decl_provider.as_ref()) {
(Ok(_), _) => decl,
(Err(Error::NotFound), Some(shallow_decl_provider)) => {
if let Ok(Some(type_decl)) =
shallow_decl_provider.get_type(TypeName::new(symbol))
{
match type_decl {
shallow_decl_provider::TypeDecl::Class(c) => {
Ok(decl_provider::TypeDecl::Class(c.to_oxidized(self.arena)))
}
shallow_decl_provider::TypeDecl::Typedef(ty) => {
Ok(decl_provider::TypeDecl::Typedef(ty.to_oxidized(self.arena)))
}
}
} else {
decl
}
}
(_, _) => decl,
}
};
Self::record_access(&self.type_requests, symbol, depth, decl.is_ok());
decl
}
fn func_decl(&self, symbol: &str) -> Result<&'a FunDecl<'a>, Error> {
let decl = {
let decl = self.find_decl(|decls| decl_provider::find_func_decl(decls, symbol));
match (&decl, self.shallow_decl_provider.as_ref()) {
(Ok(_), _) => decl,
(Err(Error::NotFound), Some(shallow_decl_provider)) => {
if let Ok(Some(fun_decl)) = shallow_decl_provider.get_fun(FunName::new(symbol))
{
Ok(fun_decl.to_oxidized(self.arena))
} else {
decl
}
}
(_, _) => decl,
}
};
Self::record_access(&self.func_requests, symbol, 0, decl.is_ok());
decl
}
fn const_decl(&self, symbol: &str) -> Result<&'a ConstDecl<'a>, Error> {
let decl = {
let decl = self.find_decl(|decls| decl_provider::find_const_decl(decls, symbol));
match (&decl, self.shallow_decl_provider.as_ref()) {
(Ok(_), _) => decl,
(Err(Error::NotFound), Some(shallow_decl_provider)) => {
if let Ok(Some(const_decl)) =
shallow_decl_provider.get_const(ConstName::new(symbol))
{
Ok(const_decl.to_oxidized(self.arena))
} else {
decl
}
}
(_, _) => decl,
}
};
Self::record_access(&self.const_requests, symbol, 0, decl.is_ok());
decl
}
fn module_decl(&self, symbol: &str) -> Result<&'a ModuleDecl<'a>, Error> {
let decl = self.find_decl(|decls| decl_provider::find_module_decl(decls, symbol));
// TODO: ShallowDeclProvider doesn't have a get_module equivalent
Self::record_access(&self.module_requests, symbol, 0, decl.is_ok());
decl
}
}
fn make_naming_table_powered_shallow_decl_provider<R: Reason>(
hackc_opts: &crate::Opts,
) -> Result<impl ShallowDeclProvider<R>> {
let hhi_root = TempDir::new("rupro_decl_repo_hhi")?;
hhi::write_hhi_files(hhi_root.path()).unwrap();
let root = hackc_opts
.naming_table_root
.as_ref()
.ok_or_else(|| anyhow::Error::msg("Did not find naming table root path"))?
.clone();
let ctx = Arc::new(RelativePathCtx {
root,
hhi: hhi_root.path().into(),
dummy: PathBuf::new(),
tmp: PathBuf::new(),
});
let file_provider: Arc<dyn file_provider::FileProvider> = Arc::new(
file_provider::DiskProvider::new(Arc::clone(&ctx), Some(hhi_root)),
);
let parser = DeclParser::new(
file_provider,
DeclParserOptions::default(),
false, // deregister_php_stdlib
);
let shallow_decl_store = make_shallow_decl_store::<R>(StoreOpts::Unserialized);
let naming_table_path = hackc_opts
.naming_table
.as_ref()
.ok_or_else(|| anyhow::Error::msg("Did not find naming table"))?
.clone();
Ok(LazyShallowDeclProvider::new(
Arc::new(shallow_decl_store),
Arc::new(SqliteNamingTable::new(naming_table_path).unwrap()),
parser,
))
}
impl<'a, R: Reason> SingleDeclProvider<'a, R> {
fn make(arena: &'a bumpalo::Bump, decls: Decls<'a>, hackc_opts: &crate::Opts) -> Result<Self> {
Ok(SingleDeclProvider {
arena,
decls: match hackc_opts.use_serialized_decls {
false => DeclsHolder::ByRef(decls),
true => DeclsHolder::Ser(decl_provider::serialize_decls(&decls)?),
},
shallow_decl_provider: if hackc_opts.naming_table.is_some()
&& hackc_opts.naming_table_root.is_some()
{
Some(Arc::new(make_naming_table_powered_shallow_decl_provider(
hackc_opts,
)?))
} else {
None
},
type_requests: Default::default(),
func_requests: Default::default(),
const_requests: Default::default(),
module_requests: Default::default(),
})
}
fn find_decl<T>(
&self,
mut find: impl FnMut(&Decls<'a>) -> Result<T, Error>,
) -> Result<T, Error> {
match &self.decls {
DeclsHolder::ByRef(decls) => find(decls),
DeclsHolder::Ser(data) => find(&decl_provider::deserialize_decls(self.arena, data)?),
}
}
fn record_access(log: &RefCell<Vec<Access>>, symbol: &str, depth: u64, found: bool) {
log.borrow_mut().push(Access {
symbol: symbol.into(),
depth,
found,
});
}
} |
Rust | hhvm/hphp/hack/src/hackc/cli/crc.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::borrow::Cow;
use std::fs;
use std::hash::Hash;
use std::hash::Hasher;
use std::path::Path;
use std::path::PathBuf;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use std::time::Duration;
use std::time::Instant;
use anyhow::bail;
use anyhow::Result;
use clap::Args;
use multifile_rust as multifile;
use parking_lot::Mutex;
use rayon::prelude::*;
use crate::compile::SingleFileOpts;
use crate::profile;
use crate::profile::DurationEx;
use crate::profile::MaxValue;
use crate::profile::StatusTicker;
use crate::profile::Timing;
use crate::util::SyncWrite;
#[derive(Args, Debug)]
pub struct Opts {
#[allow(dead_code)]
#[command(flatten)]
single_file_opts: SingleFileOpts,
/// Number of parallel worker threads. By default, or if set to 0, use num-cpu threads.
#[clap(long, default_value = "0")]
num_threads: usize,
#[command(flatten)]
files: crate::FileOpts,
}
fn process_one_file(
writer: &SyncWrite,
f: &Path,
compile_opts: &SingleFileOpts,
profile: &mut compile::Profile,
) -> Result<()> {
let content = fs::read(f)?;
let files = multifile::to_files(f, content)?;
for (f, content) in files {
let f = f.as_ref();
let result = std::panic::catch_unwind(|| {
let mut profile1 = compile::Profile::default();
let result =
crate::compile::process_single_file(compile_opts, f.into(), content, &mut profile1);
(result, profile1)
});
match result {
Ok((Err(e), profile1)) => {
// No panic - but called function failed.
*profile = compile::Profile::fold(std::mem::take(profile), profile1);
writeln!(writer.lock(), "{}: error ({})", f.display(), e)?;
bail!("failed");
}
Ok((Ok(output), profile1)) => {
// No panic and called function succeeded.
*profile = compile::Profile::fold(std::mem::take(profile), profile1);
let mut hasher = std::collections::hash_map::DefaultHasher::new();
output.hash(&mut hasher);
let crc = hasher.finish();
writeln!(writer.lock(), "{}: {:016x}", f.display(), crc)?;
}
Err(_) => {
// Called function panic'd.
writeln!(writer.lock(), "{}: panic", f.display())?;
bail!("panic");
}
}
}
Ok(())
}
#[derive(Default)]
struct ProfileAcc {
parser_profile: crate::profile::ParserProfile,
codegen_bytes: u64,
max_rewrite: MaxValue<u64>,
max_emitter: MaxValue<u64>,
total_t: Timing,
codegen_t: Timing,
bc_to_ir_t: Timing,
ir_to_bc_t: Timing,
printing_t: Timing,
}
impl ProfileAcc {
fn fold(mut self, other: Self) -> Self {
self.fold_with(other);
self
}
fn fold_with(&mut self, other: Self) {
self.parser_profile.fold_with(other.parser_profile);
self.codegen_bytes += other.codegen_bytes;
self.max_rewrite.fold_with(other.max_rewrite);
self.max_emitter.fold_with(other.max_emitter);
self.total_t.fold_with(other.total_t);
self.codegen_t.fold_with(other.codegen_t);
self.bc_to_ir_t.fold_with(other.bc_to_ir_t);
self.ir_to_bc_t.fold_with(other.ir_to_bc_t);
self.printing_t.fold_with(other.printing_t);
}
fn from_compile<'a>(
profile: compile::Profile,
total_t: Duration,
path: impl Into<Cow<'a, Path>>,
) -> Self {
let path = path.into();
let total_t = Timing::from_duration(total_t, path.clone());
let codegen_t = Timing::from_duration(profile.codegen_t, path.clone());
let bc_to_ir_t = Timing::from_duration(profile.bc_to_ir_t, path.clone());
let ir_to_bc_t = Timing::from_duration(profile.ir_to_bc_t, path.clone());
let printing_t = Timing::from_duration(profile.printing_t, path.clone());
let parser_profile =
crate::profile::ParserProfile::from_parser(profile.parser_profile, path.as_ref());
ProfileAcc {
total_t,
codegen_t,
bc_to_ir_t,
ir_to_bc_t,
printing_t,
codegen_bytes: profile.codegen_bytes,
max_rewrite: MaxValue::new(profile.rewrite_peak, path.to_path_buf()),
max_emitter: MaxValue::new(profile.emitter_peak, path.to_path_buf()),
parser_profile,
}
}
fn report_final(&self, wall: Duration, count: usize, total: usize) -> std::io::Result<()> {
if total >= 10 {
let wall_per_sec = if !wall.is_zero() {
((count as f64) / wall.as_secs_f64()) as usize
} else {
0
};
// Done, print final stats.
eprintln!(
"\rProcessed {count} in {wall} ({wall_per_sec}/s) arenas={arenas:.3}MiB ",
wall = wall.display(),
arenas = self.codegen_bytes as f64 / (1024 * 1024) as f64,
);
}
let mut w = std::io::stderr();
let p = &self.parser_profile;
profile::report_stat(&mut w, "", "total time", &self.total_t)?;
profile::report_stat(&mut w, " ", "ast-gen time", &p.total_t)?;
profile::report_stat(&mut w, " ", "parsing time", &p.parsing_t)?;
profile::report_stat(&mut w, " ", "lowering time", &p.lowering_t)?;
profile::report_stat(&mut w, " ", "elaboration time", &p.elaboration_t)?;
profile::report_stat(&mut w, " ", "error check time", &p.error_t)?;
profile::report_stat(&mut w, " ", "codegen time", &self.codegen_t)?;
profile::report_stat(&mut w, " ", "bc_to_ir time", &self.bc_to_ir_t)?;
profile::report_stat(&mut w, " ", "ir_to_bc time", &self.ir_to_bc_t)?;
profile::report_stat(&mut w, " ", "printing time", &self.printing_t)?;
p.parse_peak.report(&mut w, "parser stack peak")?;
p.lower_peak.report(&mut w, "lowerer stack peak")?;
p.error_peak.report(&mut w, "check_error stack peak")?;
self.max_rewrite.report(&mut w, "rewrite stack peak")?;
self.max_emitter.report(&mut w, "emitter stack peak")?;
Ok(())
}
}
fn crc_files(
writer: &SyncWrite,
files: &[PathBuf],
num_threads: usize,
compile_opts: &SingleFileOpts,
) -> Result<()> {
let total = files.len();
let passed = Arc::new(AtomicBool::new(true));
let status_ticker = StatusTicker::new(total);
let count_one_file = |acc: ProfileAcc, f: &PathBuf| -> ProfileAcc {
let mut profile = compile::Profile::default();
status_ticker.start_file(f);
let total_t = Instant::now();
let file_passed = process_one_file(writer, f.as_path(), compile_opts, &mut profile).is_ok();
if !file_passed {
passed.store(false, Ordering::Release);
}
status_ticker.finish_file(f);
acc.fold(ProfileAcc::from_compile(profile, total_t.elapsed(), f))
};
let profile = if num_threads == 1 {
files.iter().fold(ProfileAcc::default(), count_one_file)
} else {
files
.par_iter()
.with_max_len(1)
.fold(ProfileAcc::default, count_one_file)
.reduce(ProfileAcc::default, |x, y| x.fold(y))
};
let (count, duration) = status_ticker.finish();
profile.report_final(duration, count, total)?;
eprintln!();
if !passed.load(Ordering::Acquire) {
bail!("Failed to complete");
}
Ok(())
}
pub fn run(opts: Opts) -> Result<()> {
let writer: SyncWrite = Mutex::new(Box::new(std::io::stdout()));
let files = opts.files.collect_input_files(opts.num_threads)?;
crc_files(&writer, &files, opts.num_threads, &opts.single_file_opts)?;
Ok(())
} |
Rust | hhvm/hphp/hack/src/hackc/cli/decls.rs | // Copyright (c) Meta Platforms, Inc. and affiliates.
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::io::Write;
use std::path::PathBuf;
use anyhow::Result;
use clap::Args;
use direct_decl_parser::ParsedFile;
use hash::IndexMap;
use relative_path::Prefix;
use relative_path::RelativePath;
/// Decls subcommand options
#[derive(Args, Debug, Default)]
pub(crate) struct Opts {
#[command(flatten)]
pub files: crate::FileOpts,
}
/// Write a serialized object to stdout containing Decls for each input file.
pub(crate) fn binary_decls(hackc_opts: crate::Opts, opts: Opts) -> Result<()> {
let filenames = opts.files.gather_input_files()?;
let dp_opts = hackc_opts.decl_opts();
let mut parsed_files: IndexMap<PathBuf, ParsedFile<'_>> = Default::default();
let arena = bumpalo::Bump::new();
for path in filenames {
// Parse decls
let text = std::fs::read(&path)?;
let filename = RelativePath::make(Prefix::Root, path.clone());
let parsed_file =
direct_decl_parser::parse_decls_for_bytecode(&dp_opts, filename, &text, &arena);
parsed_files.insert(path.to_path_buf(), parsed_file);
}
let mut data = Vec::new();
decl_provider::serialize_batch_decls(&mut data, &parsed_files)?;
std::io::stdout().write_all(&data)?;
Ok(())
}
pub(crate) fn json_decls(hackc_opts: crate::Opts, opts: Opts) -> Result<()> {
let filenames = opts.files.gather_input_files()?;
let dp_opts = hackc_opts.decl_opts();
for path in filenames {
// Parse decls
let text = std::fs::read(&path)?;
let arena = bumpalo::Bump::new();
let filename = RelativePath::make(Prefix::Root, path.clone());
let parsed_file =
direct_decl_parser::parse_decls_for_bytecode(&dp_opts, filename, &text, &arena);
serde_json::to_writer_pretty(&mut std::io::stdout(), &parsed_file)?;
}
Ok(())
} |
Rust | hhvm/hphp/hack/src/hackc/cli/elaborate.rs | // Copyright (c) Meta Platforms, Inc. and affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::collections::HashSet;
use std::path::Path;
use std::sync::Arc;
use aast_parser::AastParser;
use anyhow::anyhow;
use anyhow::Context;
use oxidized::naming_phase_error::NamingPhaseError;
use oxidized::typechecker_options::TypecheckerOptions;
use parser_core_types::indexed_source_text::IndexedSourceText;
use parser_core_types::source_text::SourceText;
use rayon::prelude::*;
use relative_path::Prefix;
use relative_path::RelativePath;
use crate::FileOpts;
#[derive(clap::Args, Debug)]
pub struct Opts {
#[command(flatten)]
files: FileOpts,
}
pub fn run(opts: Opts) -> anyhow::Result<()> {
let files = opts.files.gather_input_files()?;
let single_file = files.len() == 1;
// Process all files, collect fatal errors
let errs: Vec<anyhow::Error> = files
.into_par_iter()
.map(|path| process_one_file(single_file, &path, &opts))
.filter_map(|result| result.err())
.collect();
if errs.is_empty() {
Ok(())
} else {
for err in &errs {
eprintln!("fatal error: {err}");
}
Err(anyhow!("encountered {} fatal errors", errs.len()))
}
}
fn process_one_file(single_file: bool, path: &Path, _: &Opts) -> anyhow::Result<()> {
let content =
std::fs::read(path).with_context(|| format!("failed to read {}", path.display()))?;
let rel_path = Arc::new(RelativePath::make(Prefix::Dummy, path.to_path_buf()));
let source_text = IndexedSourceText::new(SourceText::make(Arc::clone(&rel_path), &content));
let mut parser_result =
AastParser::from_text(&Default::default(), &source_text, HashSet::default())
.map_err(|e| anyhow!("failed to parse {}: {:#?}", path.display(), e))?;
let tco = TypecheckerOptions::default();
let errs = elab::elaborate_program(&tco, &rel_path, &mut parser_result.aast);
print_parse_result(single_file, path, &parser_result, &errs)?;
Ok(())
}
fn print_parse_result(
single_file: bool,
path: &Path,
parser_result: &aast_parser::ParserResult,
naming_errors: &[NamingPhaseError],
) -> std::io::Result<()> {
use std::io::Write;
if !parser_result.syntax_errors.is_empty()
|| !parser_result.lowerer_parsing_errors.is_empty()
|| !parser_result.errors.is_empty()
|| !parser_result.lint_errors.is_empty()
|| !naming_errors.is_empty()
{
let file_name = path.file_name().unwrap().to_string_lossy();
let mut stdout = std::io::stdout().lock();
let w = &mut stdout;
if !single_file {
writeln!(w, "{}", file_name)?;
}
write_errs(w, "Syntax", &parser_result.syntax_errors)?;
write_errs(w, "Lowering", &parser_result.lowerer_parsing_errors)?;
write_errs(w, "Parse", &parser_result.errors)?;
write_errs(w, "Lint", &parser_result.lint_errors)?;
write_errs(w, "Naming", naming_errors)?;
}
if single_file {
println!("{:#?}", &parser_result.aast);
}
Ok(())
}
fn write_errs<W: std::io::Write, T: std::fmt::Debug>(
w: &mut W,
error_kind: &'static str,
errs: &[T],
) -> std::io::Result<()> {
if errs.is_empty() {
return Ok(());
}
writeln!(w, "{error_kind} errors: {:#?}", errs)
} |
Rust | hhvm/hphp/hack/src/hackc/cli/expr_trees.rs | // Copyright (c) Meta Platforms, Inc. and affiliates.
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use anyhow::Result;
use clap::Args;
use relative_path::Prefix;
use relative_path::RelativePath;
use crate::FileOpts;
#[derive(Args, Debug, Default)]
pub(crate) struct Opts {
#[command(flatten)]
pub files: FileOpts,
}
pub(crate) fn desugar_expr_trees(hackc_opts: &crate::Opts, opts: Opts) -> Result<()> {
for path in opts.files.gather_input_files()? {
compile::dump_expr_tree::desugar_and_print(
RelativePath::make(Prefix::Dummy, path),
&hackc_opts.env_flags,
);
}
Ok(())
} |
Rust | hhvm/hphp/hack/src/hackc/cli/facts.rs | // Copyright (c) Meta Platforms, Inc. and affiliates.
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::io::Write;
use anyhow::Result;
use clap::Args;
use facts::Facts;
use relative_path::Prefix;
use relative_path::RelativePath;
use serde_json::json;
use serde_json::Value;
/// Facts subcommand options
#[derive(Args, Debug, Default)]
pub(crate) struct Opts {
#[command(flatten)]
pub files: crate::FileOpts,
}
/// Write a JSON object to stdout containing Facts for each input file.
/// If input-file-list was specified or if there are multiple CLI files,
/// the result is a JSON object that maps filenames to facts. Otherwise
/// the result is just the single file's Facts.
pub(crate) fn extract_facts(
hackc_opts: &crate::Opts,
opts: Opts,
w: &mut impl Write,
) -> Result<()> {
// If --input-file-list, output a json wrapper object mapping
// filenames to facts objects
let is_batch = !hackc_opts.daemon && opts.files.is_batch_mode();
let filenames = opts.files.gather_input_files()?;
let mut file_to_facts = serde_json::Map::with_capacity(filenames.len());
for path in filenames {
let dp_opts = hackc_opts.decl_opts();
// Parse decls
let text = std::fs::read(&path)?;
let filename = RelativePath::make(Prefix::Root, path.clone());
let arena = bumpalo::Bump::new();
let parsed_file =
direct_decl_parser::parse_decls_for_bytecode(&dp_opts, filename, &text, &arena);
// Decls to facts
if parsed_file.has_first_pass_parse_errors {
// Swallowing errors is bad.
continue;
}
let facts = Facts::from_decls(&parsed_file);
let json = json!(facts);
file_to_facts.insert(path.to_str().unwrap().to_owned(), json);
}
if is_batch {
serde_json::to_writer(w, &Value::Object(file_to_facts))?;
} else if let Some((_, facts)) = file_to_facts.into_iter().next() {
serde_json::to_writer_pretty(w, &facts)?;
}
Ok(())
}
pub(crate) fn run_flag(hackc_opts: &mut crate::Opts, w: &mut impl Write) -> Result<()> {
let facts_opts = Opts {
files: std::mem::take(&mut hackc_opts.files),
..Default::default()
};
extract_facts(hackc_opts, facts_opts, w)
}
pub(crate) fn daemon(hackc_opts: &mut crate::Opts) -> Result<()> {
crate::daemon_loop(|path, w| {
hackc_opts.files.filenames = vec![path];
run_flag(hackc_opts, w)
})
} |
Rust | hhvm/hphp/hack/src/hackc/cli/hackc.rs | // Copyright (c) Meta Platforms, Inc. and affiliates.
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
mod asm;
mod asm_ir;
mod cmp_ir;
mod cmp_unit;
mod compile;
mod crc;
mod decls;
mod elaborate;
mod expr_trees;
mod facts;
mod infer;
mod parse;
mod profile;
mod util;
mod verify;
use std::io::BufRead;
use std::path::Path;
use std::path::PathBuf;
use std::time::Instant;
use ::compile::EnvFlags;
use ::compile::NativeEnv;
use anyhow::Result;
use byte_unit::Byte;
use clap::Args;
use clap::Parser;
use hhvm_options::HhvmOptions;
use log::info;
use options::Hhvm;
use options::ParserOptions;
use oxidized::decl_parser_options::DeclParserOptions;
use crate::profile::DurationEx;
/// Hack Compiler
#[derive(Parser, Debug, Default)]
#[command(author = "hphp_hphpi")]
struct Opts {
#[clap(subcommand)]
command: Option<Command>,
/// Runs in daemon mode for testing purposes. Do not rely on for production
#[clap(long)]
daemon: bool,
#[command(flatten)]
flag_commands: FlagCommands,
#[command(flatten)]
hhvm_options: HhvmOptions,
#[command(flatten)]
files: FileOpts,
#[command(flatten)]
pub(crate) env_flags: EnvFlags,
/// Number of parallel worker threads for subcommands that support parallelism,
/// otherwise ignored. If 0, use available parallelism, typically num-cpus.
#[clap(long, default_value("0"))]
num_threads: usize,
/// Stack size to use for parallel worker threads. Supports unit suffixes like KB, MiB, etc.
#[clap(long, default_value("32 MiB"))]
stack_size: Byte,
/// Instead of printing the unit, print a list of the decls requested during compilation.
/// (only used by --test-compile-with-decls)
#[clap(long)]
pub(crate) log_decls_requested: bool,
/// Use serialized decl instead of decl pointer as the decl provider API
/// (only used by --test-compile-with-decls)
#[clap(long)]
pub(crate) use_serialized_decls: bool,
#[clap(long)]
pub(crate) naming_table: Option<PathBuf>,
#[clap(long)]
pub(crate) naming_table_root: Option<PathBuf>,
/// [Experimental] Enable Type-Directed Bytecode Compilation
#[clap(long)]
type_directed: bool,
}
/// Hack Compiler
#[derive(Args, Debug, Default)]
struct FileOpts {
/// Input file(s)
filenames: Vec<PathBuf>,
/// Read a list of files (one-per-line) from this file
#[clap(long)]
input_file_list: Option<PathBuf>,
/// change to directory DIR
#[clap(long, short = 'C')]
directory: Option<PathBuf>,
}
#[derive(Parser, Debug)]
enum Command {
/// Assemble HHAS file(s) into Unit. Prints those HCUs' HHAS representation.
Assemble(asm::Opts),
/// Assemble IR assembly file(s) into Unit and print it.
AssembleIr(asm_ir::Opts),
/// Compute bincode-serialized decls for a set of Hack source files.
BinaryDecls(decls::Opts),
/// Compile one Hack source file or a list of files to HHAS
Compile(compile::Opts),
/// Elaborate one Hack source file or a list of files.
Elaborate(elaborate::Opts),
/// Compile Hack source files or directories and produce a single CRC per
/// input file.
Crc(crc::Opts),
/// Compute JSON-serialized decls for a set of Hack source files.
JsonDecls(decls::Opts),
/// Print the source code with expression tree literals desugared.
/// Best effort debugging tool.
DesugarExprTrees(expr_trees::Opts),
/// Compute JSON facts for a set of Hack source files.
Facts(facts::Opts),
/// Emit Infer SIL.
CompileInfer(infer::Opts),
/// Render the source text parse tree for each given file.
Parse(parse::Opts),
/// Parse many files whose filenames are read from stdin, discard parser output.
ParseBench(parse::BenchOpts),
/// Compile Hack source files or directories and check for compilation errors.
Verify(verify::Opts),
}
/// Which command are we running? Using bool opts for compatibility with test harnesses.
/// New commands should be defined as subcommands using the Command enum.
#[derive(Parser, Debug, Default)]
struct FlagCommands {
/// Parse decls from source text, transform them into facts, and print the facts
/// in JSON format.
#[clap(long)]
extract_facts_from_decls: bool,
/// Compile file with decls from the same file available during compilation.
#[clap(long)]
test_compile_with_decls: bool,
}
impl FileOpts {
pub fn gather_input_files(&self) -> Result<Vec<PathBuf>> {
use std::io::BufReader;
let mut files: Vec<PathBuf> = Default::default();
if let Some(list_path) = self.input_file_list.as_ref() {
for line in BufReader::new(std::fs::File::open(list_path)?).lines() {
let line = line?;
let name = if let Some(directory) = self.directory.as_ref() {
directory.join(Path::new(&line))
} else {
PathBuf::from(line)
};
files.push(name);
}
}
for name in &self.filenames {
let name = if let Some(directory) = self.directory.as_ref() {
directory.join(name)
} else {
name.to_path_buf()
};
files.push(name);
}
Ok(files)
}
pub fn collect_input_files(&self, num_threads: usize) -> Result<Vec<PathBuf>> {
info!("Collecting files");
let gather_t = Instant::now();
let files = self.gather_input_files()?;
let files = crate::util::collect_files(&files, None, num_threads)?;
let gather_t = gather_t.elapsed();
info!("{} files found in {}", files.len(), gather_t.display());
Ok(files)
}
pub fn is_batch_mode(&self) -> bool {
self.input_file_list.is_some() || self.filenames.len() > 1
}
}
impl Opts {
pub fn decl_opts(&self) -> DeclParserOptions {
DeclParserOptions {
auto_namespace_map: compile::auto_namespace_map().collect(),
disable_xhp_element_mangling: false,
interpret_soft_types_as_like_types: true,
allow_new_attribute_syntax: true,
enable_xhp_class_modifier: false,
php5_compat_mode: true,
hhvm_compat_mode: true,
keep_user_attributes: true,
..Default::default()
}
}
pub fn native_env(&self, path: PathBuf) -> Result<NativeEnv> {
let hhvm_options = &self.hhvm_options;
let hhvm_config = hhvm_options.to_config()?;
let parser_options = ParserOptions {
po_auto_namespace_map: compile::auto_namespace_map().collect(),
..hhvm_config::parser_options(&hhvm_config)?
};
let hhbc_flags = hhvm_config::hhbc_flags(&hhvm_config)?;
Ok(NativeEnv {
filepath: relative_path::RelativePath::make(relative_path::Prefix::Dummy, path),
hhvm: Hhvm {
include_roots: Default::default(),
renamable_functions: Default::default(),
non_interceptable_functions: Default::default(),
parser_options,
jit_enable_rename_function: hhvm_config::jit_enable_rename_function(&hhvm_config)?,
},
flags: self.env_flags.clone(),
hhbc_flags,
})
}
}
/// Facebook main: Perform some Facebook-specific initialization.
#[cfg(fbcode_build)]
#[cli::main("hackc", error_logging)]
fn main(_fb: fbinit::FacebookInit, opts: Opts) -> Result<()> {
// tracing-log is EXTREMELY SLOW. Running a verify over www is about 10x
// slower using tracing-log vs env_logger!
// tracing_log::LogTracer::init()?;
env_logger::init();
hackc_main(opts)
}
/// non-Facebook main
#[cfg(not(fbcode_build))]
fn main() -> Result<()> {
// In non-FB mode we convert tracing into logging (using tracing's 'log'
// feature) - so init logs like normal.
env_logger::init();
let opts = Opts::parse();
hackc_main(opts)
}
fn hackc_main(mut opts: Opts) -> Result<()> {
// Some subcommands need worker threads with larger than default stacks,
// even when using Stacker. In particular, various derived traits (e.g. Drop)
// on AAST nodes are inherently recursive.
rayon::ThreadPoolBuilder::new()
.num_threads(opts.num_threads)
.stack_size(opts.stack_size.get_bytes().try_into()?)
.build_global()
.unwrap();
match opts.command.take() {
Some(Command::Assemble(opts)) => asm::run(opts),
Some(Command::AssembleIr(opts)) => asm_ir::run(opts),
Some(Command::BinaryDecls(decls_opts)) => decls::binary_decls(opts, decls_opts),
Some(Command::JsonDecls(decls_opts)) => decls::json_decls(opts, decls_opts),
Some(Command::CompileInfer(opts)) => infer::run(opts),
Some(Command::Crc(opts)) => crc::run(opts),
Some(Command::Parse(parse_opts)) => parse::run(parse_opts),
Some(Command::ParseBench(bench_opts)) => parse::run_bench_command(bench_opts),
Some(Command::Verify(opts)) => verify::run(opts),
Some(Command::Elaborate(opts)) => elaborate::run(opts),
// Expr trees
Some(Command::DesugarExprTrees(et_opts)) => expr_trees::desugar_expr_trees(&opts, et_opts),
// Facts
Some(Command::Facts(facts_opts)) => {
facts::extract_facts(&opts, facts_opts, &mut std::io::stdout())
}
None if opts.daemon && opts.flag_commands.extract_facts_from_decls => {
facts::daemon(&mut opts)
}
None if opts.flag_commands.extract_facts_from_decls => {
facts::run_flag(&mut opts, &mut std::io::stdout())
}
// Test Decls-in-Compilation
None if opts.daemon && opts.flag_commands.test_compile_with_decls => {
compile::test_decl_compile_daemon(&mut opts)
}
None if opts.flag_commands.test_compile_with_decls => {
compile::test_decl_compile(&mut opts, &mut std::io::stdout())
}
// Compile to hhas
Some(Command::Compile(mut opts)) => compile::run(&mut opts),
None if opts.daemon => compile::daemon(&mut opts),
None => compile::compile_from_text(&mut opts, &mut std::io::stdout()),
}
}
/// In daemon mode, hackc blocks waiting for a filename on stdin.
/// Then, using the originally invoked options, dispatches that file to be compiled.
fn daemon_loop(mut f: impl FnMut(PathBuf, &mut Vec<u8>) -> Result<()>) -> Result<()> {
use std::io::Write;
for line in std::io::stdin().lock().lines() {
let mut buf = Vec::new();
f(Path::new(&line?).to_path_buf(), &mut buf)?;
// Account for utf-8 encoding and text streams with the python test runner:
// https://stackoverflow.com/questions/3586923/counting-unicode-characters-in-c
let mut w = std::io::stdout();
let num_chars = buf.iter().filter(|&b| (b & 0xc0) != 0x80).count() + 1;
writeln!(w, "{num_chars}")?;
w.write_all(&buf)?;
w.write_all(b"\n")?;
w.flush()?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
/// Just make sure json parsing produces a proper list.
/// If the alias map length changes, keep this test in sync.
#[test]
fn test_auto_namespace_map() {
let dp_opts = Opts::default().decl_opts();
assert_eq!(dp_opts.auto_namespace_map.len(), 15);
}
} |
Rust | hhvm/hphp/hack/src/hackc/cli/infer.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::fs;
use std::io;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use anyhow::Result;
use clap::Args;
use compile::Profile;
use decl_provider::SelfProvider;
use parking_lot::Mutex;
use parser_core_types::source_text::SourceText;
use rayon::prelude::*;
use relative_path::Prefix;
use relative_path::RelativePath;
use crate::compile::SingleFileOpts;
use crate::util::SyncWrite;
use crate::FileOpts;
#[derive(Args, Debug)]
pub struct Opts {
/// Output file. Creates it if necessary
#[clap(short = 'o')]
output_file: Option<PathBuf>,
#[command(flatten)]
files: FileOpts,
#[command(flatten)]
single_file_opts: SingleFileOpts,
/// Skip emitting 'standard' builtins.
#[clap(long)]
no_builtins: bool,
/// (DEPRECATED) Attempt to keep going instead of panicking on unimplemented code. This is the
/// default now and can be reversed via `no_keep_going` flag.
#[clap(long)]
keep_going: bool,
/// Panic on unimplemented code instead of generating stub instructions.
#[clap(long)]
fail_fast: bool,
/// Skip files that contain unimplemented code that can't be fully translated.
#[clap(long)]
skip_unimplemented: bool,
/// Keep memoization attributes. The default is to remove them prior to the codegen as it
/// simplifies the analysis.
#[clap(long)]
keep_memo: bool,
}
pub fn run(mut opts: Opts) -> Result<()> {
textual::KEEP_GOING.store(!opts.fail_fast, std::sync::atomic::Ordering::Release);
// Always unwrap concurrent blocks for infer use-cases. We can make it configurable later on if
// needed.
opts.single_file_opts.unwrap_concurrent = true;
let writer: SyncWrite = match &opts.output_file {
None => Mutex::new(Box::new(io::stdout())),
Some(output_file) => Mutex::new(Box::new(fs::File::create(output_file)?)),
};
let files = opts.files.gather_input_files()?;
writeln!(writer.lock(), "// TEXTUAL UNIT COUNT {}", files.len())?;
if !opts.fail_fast || opts.skip_unimplemented {
files
.into_par_iter()
.for_each(|path| match process_single_file(&path, &opts, &writer) {
Ok(_) => (),
Err(err) => {
eprintln!("Failed to compile {}: {}", path.display(), err)
}
})
} else {
files
.into_par_iter()
.try_for_each(|path| process_single_file(&path, &opts, &writer))?
}
Ok(())
}
fn process_single_file(path: &Path, opts: &Opts, writer: &SyncWrite) -> Result<()> {
match convert_single_file(path, opts) {
Ok(textual) => writer.lock().write_all(&textual).map_err(|e| e.into()),
Err(err) => Err(err),
}
}
fn convert_single_file(path: &Path, opts: &Opts) -> Result<Vec<u8>> {
let content = fs::read(path)?;
let action = || {
let pre_alloc = bumpalo::Bump::default();
build_ir(&pre_alloc, path, &content, opts).and_then(|unit| {
let mut output = Vec::new();
textual::textual_writer(&mut output, path, unit, opts.no_builtins)?;
Ok(output)
})
};
if !opts.fail_fast || opts.skip_unimplemented {
with_catch_panics(action)
} else {
action()
}
}
fn build_ir<'a, 'arena>(
alloc: &'arena bumpalo::Bump,
path: &'a Path,
content: &[u8],
opts: &'a Opts,
) -> Result<ir::Unit<'arena>> {
let filepath = RelativePath::make(Prefix::Dummy, path.to_path_buf());
let source_text = SourceText::make(Arc::new(filepath.clone()), content);
let env = crate::compile::native_env(filepath, &opts.single_file_opts)?;
let mut profile = Profile::default();
let decl_arena = bumpalo::Bump::new();
let decl_provider = SelfProvider::wrap_existing_provider(
None,
env.to_decl_parser_options(),
source_text.clone(),
&decl_arena,
);
let unit = compile::unit_from_text_with_opts(
alloc,
source_text,
&env,
decl_provider,
&mut profile,
&elab::CodegenOpts {
textual_remove_memoize: !opts.keep_memo,
},
)?;
let ir = bc_to_ir::bc_to_ir(&unit, path);
Ok(ir)
}
fn with_catch_panics<R>(action: impl FnOnce() -> Result<R> + std::panic::UnwindSafe) -> Result<R> {
match std::panic::catch_unwind(action) {
Ok(result) => result,
Err(e) => {
let msg = panic_message::panic_message(&e).to_string();
let err = anyhow::anyhow!(msg);
Err(err)
}
}
} |
Rust | hhvm/hphp/hack/src/hackc/cli/parse.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::collections::HashSet;
use std::io::stdin;
use std::io::BufRead;
use std::io::BufReader;
use std::io::Write;
use std::path::PathBuf;
use std::sync::Arc;
use aast_parser::AastParser;
use anyhow::Context;
use anyhow::Result;
use clap::builder::TypedValueParser;
use clap::Args;
use parser_core_types::indexed_source_text::IndexedSourceText;
use parser_core_types::parser_env::ParserEnv;
use parser_core_types::source_text::SourceText;
use rayon::prelude::*;
use relative_path::Prefix;
use relative_path::RelativePath;
use strum::Display;
use strum::EnumString;
use strum::EnumVariantNames;
use strum::VariantNames;
#[derive(Args, Clone, Debug)]
pub struct BenchOpts {
#[clap(default_value_t, long, value_parser = clap::builder::PossibleValuesParser::new(ParserKind::VARIANTS).map(|s| s.parse::<ParserKind>().unwrap()))]
parser: ParserKind,
}
#[derive(Clone, Copy, Debug, Display, EnumString, EnumVariantNames)]
enum ParserKind {
Aast,
Positioned,
PositionedByRef,
PositionedWithFullTrivia,
DirectDecl,
}
impl Default for ParserKind {
fn default() -> Self {
Self::Positioned
}
}
pub fn run_bench_command(bench_opts: BenchOpts) -> Result<()> {
BufReader::new(stdin())
.lines()
.collect::<std::io::Result<Vec<_>>>()
.context("could not read line from input file list")?
.into_par_iter()
.try_for_each(|line| {
let path = PathBuf::from(line.trim());
let content = std::fs::read(&path)?;
let env = ParserEnv::default();
let filepath = RelativePath::make(Prefix::Dummy, path);
let source_text = SourceText::make(Arc::new(filepath.clone()), &content);
match bench_opts.parser {
ParserKind::PositionedWithFullTrivia => {
let stdout = std::io::stdout();
let w = stdout.lock();
let mut s = serde_json::Serializer::new(w);
let arena = bumpalo::Bump::new();
let src = IndexedSourceText::new(source_text);
positioned_full_trivia_parser::parse_script_to_json(&arena, &mut s, &src, env)?
}
ParserKind::PositionedByRef => {
let arena = bumpalo::Bump::new();
let (_, _, _) =
positioned_by_ref_parser::parse_script(&arena, &source_text, env);
}
ParserKind::Positioned => {
let (_, _, _) = positioned_parser::parse_script(&source_text, env);
}
ParserKind::DirectDecl => {
let arena = bumpalo::Bump::new();
let opts = Default::default();
let _ = direct_decl_parser::parse_decls_for_typechecking(
&opts, filepath, &content, &arena,
);
}
ParserKind::Aast => {
let indexed_source_text = IndexedSourceText::new(source_text);
let env = aast_parser::rust_aast_parser_types::Env::default();
let _ = AastParser::from_text(&env, &indexed_source_text, HashSet::default());
}
}
Ok(())
})
}
#[derive(Args, Debug)]
pub(crate) struct Opts {
#[command(flatten)]
pub files: crate::FileOpts,
/// Print compact JSON instead of formatted & indented JSON.
#[clap(long)]
compact: bool,
}
fn parse(path: PathBuf, w: &mut impl Write, pretty: bool) -> Result<()> {
let source_text = std::fs::read(&path)?;
// TODO T118266805: These should come from config files.
let env = ParserEnv {
codegen: true,
hhvm_compat_mode: true,
php5_compat_mode: true,
allow_new_attribute_syntax: true,
interpret_soft_types_as_like_types: true,
..Default::default()
};
let filepath = RelativePath::make(Prefix::Dummy, path);
let source_text = SourceText::make(Arc::new(filepath), &source_text);
let indexed_source = IndexedSourceText::new(source_text);
let arena = bumpalo::Bump::new();
let json = if pretty {
let mut serializer = serde_json::Serializer::pretty(vec![]);
positioned_full_trivia_parser::parse_script_to_json(
&arena,
&mut serializer,
&indexed_source,
env,
)?;
serializer.into_inner()
} else {
let mut serializer = serde_json::Serializer::new(vec![]);
positioned_full_trivia_parser::parse_script_to_json(
&arena,
&mut serializer,
&indexed_source,
env,
)?;
serializer.into_inner()
};
w.write_all(&json)?;
Ok(())
}
pub(crate) fn run(opts: Opts) -> Result<()> {
let filenames = opts.files.gather_input_files()?;
let mut w = std::io::stdout();
for path in filenames {
parse(path, &mut w, !opts.compact)?;
w.write_all(b"\n")?;
w.flush()?;
}
Ok(())
} |
Rust | hhvm/hphp/hack/src/hackc/cli/profile.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::borrow::Cow;
use std::fmt;
use std::fmt::Display;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use std::thread::JoinHandle;
use std::time::Duration;
use std::time::Instant;
use hash::HashMap;
use parking_lot::Mutex;
#[derive(Debug)]
pub(crate) struct Timing {
total: Duration,
histogram: hdrhistogram::Histogram<u64>,
worst: Option<(Duration, PathBuf)>,
}
impl Timing {
pub(crate) fn time<'a, T>(
path: impl Into<Cow<'a, Path>>,
f: impl FnOnce() -> T,
) -> (T, Timing) {
let (r, t) = profile_rust::time(f);
(r, Timing::from_duration(t, path))
}
pub(crate) fn from_duration<'a>(time: Duration, path: impl Into<Cow<'a, Path>>) -> Self {
let mut histogram = hdrhistogram::Histogram::new(3).unwrap();
histogram.record(time.as_micros() as u64).unwrap();
Timing {
total: time,
histogram,
worst: Some((time, path.into().into_owned())),
}
}
pub(crate) fn total(&self) -> Duration {
self.total
}
fn is_empty(&self) -> bool {
self.histogram.is_empty()
}
fn mean(&self) -> Duration {
Duration::from_micros(self.histogram.mean() as u64)
}
fn max(&self) -> Duration {
Duration::from_micros(self.histogram.max())
}
fn value_at_percentile(&self, q: f64) -> Duration {
Duration::from_micros(self.histogram.value_at_percentile(q))
}
fn worst(&self) -> Option<&Path> {
self.worst.as_ref().map(|(_, path)| path.as_path())
}
pub(crate) fn fold_with(&mut self, rhs: Self) {
self.total += rhs.total;
self.histogram.add(rhs.histogram).unwrap();
self.worst = match (self.worst.take(), rhs.worst) {
(None, None) => None,
(lhs @ Some(_), None) => lhs,
(None, rhs @ Some(_)) => rhs,
(Some(lhs), Some(rhs)) => {
if lhs.0 > rhs.0 {
Some(lhs)
} else {
Some(rhs)
}
}
};
}
}
impl std::default::Default for Timing {
fn default() -> Self {
Self {
total: Duration::from_secs(0),
histogram: hdrhistogram::Histogram::new(3).unwrap(),
worst: None,
}
}
}
pub(crate) trait DurationEx {
fn display(&self) -> DurationDisplay;
}
impl DurationEx for Duration {
fn display(&self) -> DurationDisplay {
DurationDisplay(*self)
}
}
pub(crate) struct DurationDisplay(Duration);
impl Display for DurationDisplay {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.0 > Duration::from_secs(2) {
write!(f, "{:.3}s", self.0.as_secs_f64())
} else if self.0 > Duration::from_millis(2) {
write!(f, "{:.3}ms", (self.0.as_micros() as f64) / 1_000.0)
} else {
write!(f, "{}us", self.0.as_micros())
}
}
}
pub(crate) fn to_hms(time: usize) -> String {
if time >= 5400 {
// > 90m
format!(
"{:02}h:{:02}m:{:02}s",
time / 3600,
(time % 3600) / 60,
time % 60
)
} else if time > 90 {
// > 90s
format!("{:02}m:{:02}s", time / 60, time % 60)
} else {
format!("{}s", time)
}
}
pub(crate) fn report_stat(
w: &mut impl std::io::Write,
indent: &str,
what: &str,
timing: &Timing,
) -> std::io::Result<()> {
if timing.is_empty() {
return Ok(());
}
write!(
w,
"{}{}: total: {}, avg: {}",
indent,
what,
timing.total.display(),
timing.mean().display()
)?;
write!(w, ", P50: {}", timing.value_at_percentile(50.0).display())?;
write!(w, ", P90: {}", timing.value_at_percentile(90.0).display())?;
write!(w, ", P99: {}", timing.value_at_percentile(99.0).display())?;
writeln!(w, ", max: {}", timing.max().display())?;
if let Some(worst) = timing.worst() {
eprintln!("{} (max in {})", indent, worst.display());
}
Ok(())
}
struct StatusSharedData {
count: usize,
finished: bool,
last_long_run_check: Instant,
// start time for each active file
processing: HashMap<PathBuf, Instant>,
start: Instant,
total: usize,
}
impl StatusSharedData {
fn report_status(&mut self) {
let wall = self.start.elapsed();
let count = self.count;
if self.total < 10 {
return;
}
let wall_per_sec = if !wall.is_zero() {
((count as f64) / wall.as_secs_f64()) as usize
} else {
0
};
let remaining = if wall_per_sec > 0 {
let left = (self.total - count) / wall_per_sec;
format!(", {} remaining", to_hms(left))
} else {
"".into()
};
eprint!(
"\rProcessed {count} / {total} in {wall:.3} ({wall_per_sec}/s{remaining}) ",
total = self.total,
wall = wall.display(),
);
if self.last_long_run_check.elapsed().as_secs() > 10 {
let mut lead = "\nWARNING: Long-running files:\n";
for (name, start) in self.processing.iter_mut() {
let elapsed = start.elapsed();
if elapsed.as_secs() > 10 {
eprintln!("{lead} {} ({})", name.display(), elapsed.display());
lead = "";
}
}
self.last_long_run_check = Instant::now();
}
}
}
pub(crate) struct StatusTicker {
shared: Arc<Mutex<StatusSharedData>>,
handle: JoinHandle<()>,
}
impl StatusTicker {
pub(crate) fn new(total: usize) -> Self {
let shared = Arc::new(Mutex::new(StatusSharedData {
count: 0,
finished: false,
last_long_run_check: Instant::now(),
processing: Default::default(),
start: Instant::now(),
total,
}));
let handle = Self::run_thread(&shared);
Self { handle, shared }
}
fn run_thread(shared: &Arc<Mutex<StatusSharedData>>) -> JoinHandle<()> {
let shared = Arc::clone(shared);
std::thread::spawn(move || {
loop {
let mut shared = shared.lock();
if shared.finished {
break;
}
shared.report_status();
drop(shared);
std::thread::sleep(Duration::from_millis(1000));
}
})
}
pub(crate) fn finish(self) -> (usize, Duration) {
let mut shared = self.shared.lock();
shared.finished = true;
let count = shared.count;
let duration = shared.start.elapsed();
drop(shared);
self.handle.join().unwrap();
(count, duration)
}
pub(crate) fn start_file(&self, path: &Path) {
let mut shared = self.shared.lock();
shared.processing.insert(path.to_path_buf(), Instant::now());
}
pub(crate) fn finish_file(&self, path: &Path) {
let mut shared = self.shared.lock();
shared.count += 1;
shared.processing.remove(path);
}
}
#[derive(Debug)]
pub(crate) enum MaxValue<T: Ord> {
Unset,
Set(T, PathBuf),
}
impl<T: Ord> std::default::Default for MaxValue<T> {
fn default() -> Self {
Self::Unset
}
}
impl<T: Ord> MaxValue<T> {
pub(crate) fn new<'s>(value: T, file: impl Into<Cow<'s, Path>>) -> Self {
Self::Set(value, file.into().to_path_buf())
}
pub(crate) fn fold_with(&mut self, other: Self) {
match (self, other) {
(_, Self::Unset) => {}
(lhs @ Self::Unset, value) => {
*lhs = value;
}
(Self::Set(a, file_a), Self::Set(b, file_b)) => {
if *a < b {
*a = b;
*file_a = file_b;
}
}
}
}
pub(crate) fn value(&self) -> &T {
match self {
Self::Unset => panic!("unset value"),
Self::Set(value, _) => value,
}
}
pub(crate) fn file(&self) -> &Path {
match self {
Self::Unset => panic!("unset value"),
Self::Set(_, file) => file,
}
}
}
impl<T: Ord + Display> MaxValue<T> {
pub(crate) fn report(&self, w: &mut impl std::io::Write, why: &str) -> std::io::Result<()> {
writeln!(w, "{} {} (in {})", why, self.value(), self.file().display())
}
}
#[derive(Debug, Default)]
pub(crate) struct ParserProfile {
pub parse_peak: MaxValue<u64>,
pub lower_peak: MaxValue<u64>,
pub error_peak: MaxValue<u64>,
pub arena_bytes: u64,
pub parsing_t: Timing,
pub lowering_t: Timing,
pub elaboration_t: Timing,
pub error_t: Timing,
pub total_t: Timing,
}
impl ParserProfile {
pub fn from_parser<'s>(
parser: aast_parser::ParserProfile,
file: impl Into<Cow<'s, Path>>,
) -> Self {
let file = file.into();
let aast_parser::ParserProfile {
parse_peak,
lower_peak,
error_peak,
arena_bytes,
parsing_t,
lowering_t,
elaboration_t,
error_t,
total_t,
} = parser;
Self {
parse_peak: MaxValue::new(parse_peak, file.to_path_buf()),
lower_peak: MaxValue::new(lower_peak, file.to_path_buf()),
error_peak: MaxValue::new(error_peak, file.to_path_buf()),
arena_bytes,
parsing_t: Timing::from_duration(parsing_t, file.to_path_buf()),
lowering_t: Timing::from_duration(lowering_t, file.to_path_buf()),
elaboration_t: Timing::from_duration(elaboration_t, file.to_path_buf()),
error_t: Timing::from_duration(error_t, file.to_path_buf()),
total_t: Timing::from_duration(total_t, file.to_path_buf()),
}
}
pub fn fold_with(&mut self, other: Self) {
self.parse_peak.fold_with(other.parse_peak);
self.lower_peak.fold_with(other.lower_peak);
self.error_peak.fold_with(other.error_peak);
self.arena_bytes += other.arena_bytes;
self.parsing_t.fold_with(other.parsing_t);
self.lowering_t.fold_with(other.lowering_t);
self.elaboration_t.fold_with(other.elaboration_t);
self.error_t.fold_with(other.error_t);
self.total_t.fold_with(other.total_t);
}
} |
Rust | hhvm/hphp/hack/src/hackc/cli/util.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::ffi::OsStr;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use anyhow::bail;
use anyhow::Result;
use parking_lot::Mutex;
pub type SyncWrite = Mutex<Box<dyn Write + Sync + Send>>;
/// Took this from https://docs.rs/once_cell/latest/once_cell/index.html#lazily-compiled-regex
/// with this macro we can avoid re-initializing regexes, which are expensive to do
#[macro_export]
macro_rules! regex {
($re:literal $(,)?) => {{
static RE: once_cell::sync::OnceCell<Regex> = once_cell::sync::OnceCell::new();
RE.get_or_init(|| Regex::new($re).unwrap())
}};
}
pub(crate) fn collect_files(
paths: &[PathBuf],
limit: Option<usize>,
_num_threads: usize,
) -> Result<Vec<PathBuf>> {
fn is_php_file_name(file: &OsStr) -> bool {
use std::os::unix::ffi::OsStrExt;
let file = file.as_bytes();
file.ends_with(b".php") || file.ends_with(b".hack")
}
let mut files: Vec<(u64, PathBuf)> = paths
.iter()
.map(|path| {
if !path.exists() {
bail!("File or directory '{}' not found", path.display());
}
use jwalk::DirEntry;
use jwalk::Result;
use jwalk::WalkDir;
fn on_read_dir(
_: Option<usize>,
path: &Path,
_: &mut (),
children: &mut Vec<Result<DirEntry<((), ())>>>,
) {
children.retain(|dir_entry_result| {
dir_entry_result.as_ref().map_or(false, |dir_entry| {
let file_type = &dir_entry.file_type;
if file_type.is_file() {
is_php_file_name(dir_entry.file_name())
} else {
// The HHVM server files contain some weird
// multi-file-in-one tests that confuse the
// comparator (because you end up with two classes
// of the same name, etc) so skip them unless
// they're explicitly given. Hopefully this doesn't
// exclude something from outside HHVM somehow.
!(dir_entry.file_name() == "server" && path.ends_with("test"))
}
})
});
}
let walker = WalkDir::new(path).process_read_dir(on_read_dir);
let mut files = Vec::new();
for dir_entry in walker {
let dir_entry = dir_entry?;
if dir_entry.file_type.is_file() {
let len = dir_entry.metadata()?.len();
files.push((len, dir_entry.path()));
}
}
Ok(files)
})
.collect::<Result<Vec<_>>>()?
.into_iter()
.flatten()
.collect();
// Sort largest first process outliers first, then by path.
files.sort_unstable_by(|(len1, path1), (len2, path2)| {
len1.cmp(len2).reverse().then(path1.cmp(path2))
});
let mut files: Vec<PathBuf> = files.into_iter().map(|(_, path)| path).collect();
if let Some(limit) = limit {
if files.len() > limit {
files.resize_with(limit, || unreachable!());
}
}
Ok(files)
} |
Rust | hhvm/hphp/hack/src/hackc/cli/verify.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::cell::RefCell;
use std::fs;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use anyhow::ensure;
use clap::Args;
use clap::Parser;
use decl_provider::SelfProvider;
use hash::HashMap;
use hash::HashSet;
use itertools::Itertools;
use multifile_rust as multifile;
use parser_core_types::source_text::SourceText;
use rayon::prelude::*;
use regex::Regex;
use relative_path::Prefix;
use relative_path::RelativePath;
use thiserror::Error;
use crate::compile::SingleFileOpts;
use crate::profile;
use crate::profile::DurationEx;
use crate::profile::StatusTicker;
use crate::profile::Timing;
use crate::regex;
// Several of these would be better as the underlying error (anyhow::Error or
// std::io::Error) but then we couldn't derive Hash or Eq.
#[derive(Error, Debug, Hash, PartialEq, Eq)]
enum VerifyError {
#[error("assemble error {0}")]
AssembleError(String),
#[error("compile error {0}")]
CompileError(String),
#[error("i/o error: {0}")]
IoError(String),
#[error("units mismatch: {0}")]
IrUnitMismatchError(String),
#[error("multifile error: {0}")]
MultifileError(String),
#[error("panic {0}")]
Panic(String),
#[error("printing error: {0}")]
PrintError(String),
#[error("unable to read file: {0}")]
ReadError(String),
#[error("units mismatch: {0}")]
UnitMismatchError(crate::cmp_unit::CmpError),
#[error("semantic units mismatch: {0}")]
SemanticUnitMismatchError(String),
}
impl From<std::io::Error> for VerifyError {
fn from(err: std::io::Error) -> Self {
VerifyError::IoError(err.to_string())
}
}
type Result<T, E = VerifyError> = std::result::Result<T, E>;
thread_local! {
pub static PANIC_MSG: RefCell<Option<String>> = RefCell::new(None);
}
#[derive(Args, Debug)]
struct CommonOpts {
#[command(flatten)]
files: crate::FileOpts,
/// Print full error messages
#[clap(short = 'l')]
long_msg: bool,
#[allow(dead_code)]
#[command(flatten)]
single_file_opts: SingleFileOpts,
/// Number of parallel worker threads. By default, or if set to 0, use num-cpu threads.
#[clap(long, default_value = "0")]
num_threads: usize,
/// If true then panics will abort the process instead of being caught.
#[clap(long)]
panic_fuse: bool,
/// Print all errors
#[clap(short = 'a')]
show_all: bool,
}
#[derive(Args, Debug)]
struct AssembleOpts {
#[command(flatten)]
common: CommonOpts,
}
impl AssembleOpts {
fn verify_file(&self, path: &Path, content: Vec<u8>, profile: &mut ProfileAcc) -> Result<()> {
let pre_alloc = bumpalo::Bump::default();
let mut compile_profile = compile::Profile::default();
let (env, pre_unit) = compile_php_file(
&pre_alloc,
path,
content,
&self.common.single_file_opts,
&mut compile_profile,
)?;
let mut output: Vec<u8> = Vec::new();
let mut print_profile = compile::Profile::default();
compile::unit_to_string(&env, &mut output, &pre_unit, &mut print_profile)
.map_err(|err| VerifyError::PrintError(err.to_string()))?;
let post_alloc = bumpalo::Bump::default();
let (asm_result, assemble_t) =
Timing::time(path, || assemble::assemble_from_bytes(&post_alloc, &output));
let (post_unit, _) = asm_result.map_err(|err| {
VerifyError::AssembleError(truncate_pos_err(err.root_cause().to_string()))
})?;
let (result, verify_t) = Timing::time(path, || {
crate::cmp_unit::cmp_hack_c_unit(&pre_unit, &post_unit)
});
let total_t = compile_profile.codegen_t
+ compile_profile.parser_profile.total_t
+ print_profile.printing_t
+ assemble_t.total()
+ verify_t.total();
profile.fold_with(ProfileAcc {
total_t: Timing::from_duration(total_t, path),
codegen_t: Timing::from_duration(compile_profile.codegen_t, path),
parsing_t: Timing::from_duration(compile_profile.parser_profile.parsing_t, path),
lowering_t: Timing::from_duration(compile_profile.parser_profile.lowering_t, path),
printing_t: Timing::from_duration(print_profile.printing_t, path),
assemble_t,
verify_t,
..Default::default()
});
result.map_err(VerifyError::UnitMismatchError)
}
}
#[derive(Args, Debug)]
struct IrOpts {
#[command(flatten)]
common: CommonOpts,
}
impl IrOpts {
fn verify_file(&self, path: &Path, content: Vec<u8>, profile: &mut ProfileAcc) -> Result<()> {
let pre_alloc = bumpalo::Bump::default();
let mut compile_profile = compile::Profile::default();
let (_env, pre_unit) = compile_php_file(
&pre_alloc,
path,
content,
&self.common.single_file_opts,
&mut compile_profile,
)?;
let post_alloc = bumpalo::Bump::default();
let (ir, bc_to_ir_t) = Timing::time(path, || bc_to_ir::bc_to_ir(&pre_unit, path));
ir.strings.debug_for_each(|_id, s| {
if !profile.global_strings.contains(s) {
profile.global_strings.insert(s.to_owned());
}
});
self.verify_print_roundtrip(&ir)?;
let (post_unit, ir_to_bc_t) = Timing::time(path, || ir_to_bc::ir_to_bc(&post_alloc, ir));
let (result, verify_t) =
Timing::time(path, || sem_diff::sem_diff_unit(&pre_unit, &post_unit));
let total_t = compile_profile.codegen_t
+ compile_profile.parser_profile.total_t
+ bc_to_ir_t.total()
+ ir_to_bc_t.total()
+ verify_t.total();
profile.fold_with(ProfileAcc {
total_t: Timing::from_duration(total_t, path),
codegen_t: Timing::from_duration(compile_profile.codegen_t, path),
parsing_t: Timing::from_duration(compile_profile.parser_profile.parsing_t, path),
lowering_t: Timing::from_duration(compile_profile.parser_profile.lowering_t, path),
bc_to_ir_t,
ir_to_bc_t,
verify_t,
..Default::default()
});
result.map_err(|err| VerifyError::SemanticUnitMismatchError(err.root_cause().to_string()))
}
fn verify_print_roundtrip(&self, ir: &ir::Unit<'_>) -> Result<()> {
let mut as_string = String::new();
ir::print::print_unit(&mut as_string, ir, false)
.map_err(|err| VerifyError::PrintError(err.to_string()))?;
let alloc2 = bumpalo::Bump::default();
let strings2 = Arc::new(ir::StringInterner::default());
let ir2 = ir::assemble::unit_from_string(&as_string, Arc::clone(&strings2), &alloc2)
.map_err(|err| {
let mut err = err.root_cause().to_string();
let err = if let Some(idx) = err.find(':') {
err.split_off(idx)
} else {
err
};
VerifyError::AssembleError(err)
})?;
crate::cmp_ir::cmp_ir(ir, &ir2)
.map_err(|err| VerifyError::IrUnitMismatchError(err.to_string()))
}
}
#[derive(Args, Debug)]
struct InferOpts {
#[clap(flatten)]
common: CommonOpts,
/// Attempt to keep going instead of panicking on unimplemented code.
#[clap(long)]
keep_going: bool,
}
impl InferOpts {
fn setup(&self) {
textual::KEEP_GOING.store(self.keep_going, std::sync::atomic::Ordering::Release);
}
fn verify_file(&self, path: &Path, content: Vec<u8>, profile: &mut ProfileAcc) -> Result<()> {
// For Infer verify we just make sure that the file can compile without
// errors.
let alloc = bumpalo::Bump::default();
let mut compile_profile = compile::Profile::default();
let (_env, unit) = compile_php_file(
&alloc,
path,
content,
&self.common.single_file_opts,
&mut compile_profile,
)?;
let (ir, bc_to_ir_t) = Timing::time(path, || bc_to_ir::bc_to_ir(&unit, path));
let (result, textual_t) = Timing::time(path, || {
let mut out = Vec::new();
textual::textual_writer(&mut out, path, ir, false)
});
let total_t = compile_profile.codegen_t
+ compile_profile.parser_profile.total_t
+ bc_to_ir_t.total()
+ textual_t.total();
profile.fold_with(ProfileAcc {
total_t: Timing::from_duration(total_t, path),
codegen_t: Timing::from_duration(compile_profile.codegen_t, path),
parsing_t: Timing::from_duration(compile_profile.parser_profile.parsing_t, path),
lowering_t: Timing::from_duration(compile_profile.parser_profile.lowering_t, path),
bc_to_ir_t,
..Default::default()
});
result.map_err(|err| VerifyError::CompileError(format!("{err:?}")))
}
}
#[derive(Parser, Debug)]
enum Mode {
/// Compile files and save the resulting HHAS and interior hhbc::Unit. Assemble the HHAS files and save the resulting Unit. Compare Unit.
Assemble(AssembleOpts),
Infer(InferOpts),
Ir(IrOpts),
}
impl Mode {
fn common(&self) -> &CommonOpts {
match self {
Mode::Assemble(AssembleOpts { common, .. })
| Mode::Infer(InferOpts { common, .. })
| Mode::Ir(IrOpts { common, .. }) => common,
}
}
fn common_mut(&mut self) -> &mut CommonOpts {
match self {
Mode::Assemble(AssembleOpts { common, .. })
| Mode::Infer(InferOpts { common, .. })
| Mode::Ir(IrOpts { common, .. }) => common,
}
}
fn setup(&self) {
match self {
Mode::Assemble(_) | Mode::Ir(_) => {}
Mode::Infer(opts) => opts.setup(),
}
}
fn verify_file(&self, path: &Path, content: Vec<u8>, profile: &mut ProfileAcc) -> Result<()> {
match self {
Mode::Assemble(opts) => opts.verify_file(path, content, profile),
Mode::Infer(opts) => opts.verify_file(path, content, profile),
Mode::Ir(opts) => opts.verify_file(path, content, profile),
}
}
}
#[derive(Parser, Debug)]
pub struct Opts {
#[clap(subcommand)]
mode: Mode,
}
fn compile_php_file<'a, 'arena>(
alloc: &'arena bumpalo::Bump,
path: &'a Path,
content: Vec<u8>,
single_file_opts: &'a SingleFileOpts,
profile: &mut compile::Profile,
) -> Result<(compile::NativeEnv, hhbc::Unit<'arena>)> {
let filepath = RelativePath::make(Prefix::Dummy, path.to_path_buf());
let source_text = SourceText::make(Arc::new(filepath.clone()), &content);
let env = crate::compile::native_env(filepath, single_file_opts)
.map_err(|err| VerifyError::CompileError(err.to_string()))?;
let decl_arena = bumpalo::Bump::new();
let decl_provider = SelfProvider::wrap_existing_provider(
None,
env.to_decl_parser_options(),
source_text.clone(),
&decl_arena,
);
let unit = compile::unit_from_text(alloc, source_text, &env, decl_provider, profile)
.map_err(|err| VerifyError::CompileError(err.to_string()))?;
Ok((env, unit))
}
/// Truncates "Pos { line: 5, col: 2}" to "Pos ...", because in verify tool this isn't important
fn truncate_pos_err(err_str: String) -> String {
let pos_reg = regex!(r"Pos \{ line: \d+, col: \d+ \}");
pos_reg.replace(err_str.as_str(), "Pos {...}").to_string()
}
fn with_catch_panics<F>(profile: &mut ProfileAcc, long_msg: bool, action: F) -> Result<()>
where
F: FnOnce(&mut ProfileAcc) -> Result<()> + std::panic::UnwindSafe,
{
let result = std::panic::catch_unwind(|| {
let mut inner_profile = ProfileAcc::default();
let ok = action(&mut inner_profile);
(ok, inner_profile)
});
match result {
Ok((e, inner_profile)) => {
*profile = inner_profile;
e
}
Err(err) => {
let msg = if let Some(msg) = PANIC_MSG.with(|tls| tls.borrow_mut().take()) {
msg
} else {
panic_message::panic_message(&err).to_string()
};
let msg = truncate_pos_err(msg);
let mut msg = msg.replace('\n', "\\n");
if !long_msg && msg.len() > 80 {
msg.truncate(77);
msg.push_str("...");
}
Err(VerifyError::Panic(msg))
}
}
}
struct ProfileAcc {
passed: bool,
error_histogram: HashMap<VerifyError, (usize, PathBuf)>,
assemble_t: Timing,
bc_to_ir_t: Timing,
codegen_t: Timing,
ir_to_bc_t: Timing,
parsing_t: Timing,
lowering_t: Timing,
printing_t: Timing,
total_t: Timing,
verify_t: Timing,
global_strings: HashSet<Vec<u8>>,
}
impl std::default::Default for ProfileAcc {
fn default() -> Self {
Self {
passed: true,
error_histogram: Default::default(),
assemble_t: Default::default(),
bc_to_ir_t: Default::default(),
codegen_t: Default::default(),
ir_to_bc_t: Default::default(),
parsing_t: Default::default(),
lowering_t: Default::default(),
printing_t: Default::default(),
total_t: Default::default(),
verify_t: Default::default(),
global_strings: Default::default(),
}
}
}
impl ProfileAcc {
fn fold_with(&mut self, other: Self) {
self.passed = self.passed && other.passed;
for (err, (n, example)) in other.error_histogram {
self.error_histogram
.entry(err)
.or_insert_with(|| (0, example))
.0 += n;
}
self.assemble_t.fold_with(other.assemble_t);
self.bc_to_ir_t.fold_with(other.bc_to_ir_t);
self.codegen_t.fold_with(other.codegen_t);
self.ir_to_bc_t.fold_with(other.ir_to_bc_t);
self.parsing_t.fold_with(other.parsing_t);
self.lowering_t.fold_with(other.lowering_t);
self.printing_t.fold_with(other.printing_t);
self.total_t.fold_with(other.total_t);
self.verify_t.fold_with(other.verify_t);
match (
self.global_strings.is_empty(),
other.global_strings.is_empty(),
) {
(false, false) => {
self.global_strings.extend(other.global_strings.into_iter());
}
(true, false) => {
self.global_strings = other.global_strings;
}
(_, true) => {}
}
}
fn fold(mut self, other: Self) -> Self {
self.fold_with(other);
self
}
fn report_final(
&self,
wall: Duration,
count: usize,
total: usize,
show_all: bool,
) -> Result<()> {
if total >= 10 {
let wall_per_sec = if !wall.is_zero() {
((count as f64) / wall.as_secs_f64()) as usize
} else {
0
};
eprintln!(
"\rProcessed {count} files in {wall} ({wall_per_sec}/s)",
wall = wall.display(),
);
}
if self.passed {
println!("All files passed.");
} else {
println!("Failed to complete");
}
let num_show = if show_all {
self.error_histogram.len()
} else {
20
};
// The # of files that failed are sum of error_histogram's values' usize field
if !self.error_histogram.is_empty() {
println!(
"{}/{} files passed ({:.1}%)",
total - self.num_failed(),
total,
(100.0 - (self.num_failed() * 100) as f64 / total as f64)
);
println!("Failure histogram:");
for (k, v) in self
.error_histogram
.iter()
.sorted_by(|a, b| a.1.0.cmp(&b.1.0).reverse())
.take(num_show)
{
println!(" {:3} ({}): {}", v.0, v.1.display(), k);
}
if self.error_histogram.len() > 20 {
println!(
" (and {} unreported)",
self.error_histogram.len() - num_show
);
}
println!();
}
let mut w = std::io::stdout();
profile::report_stat(&mut w, "", "total time", &self.total_t)?;
profile::report_stat(&mut w, " ", "parsing time", &self.parsing_t)?;
profile::report_stat(&mut w, " ", "lowering time", &self.lowering_t)?;
profile::report_stat(&mut w, " ", "codegen time", &self.codegen_t)?;
profile::report_stat(&mut w, " ", "printing time", &self.printing_t)?;
profile::report_stat(&mut w, " ", "assemble time", &self.assemble_t)?;
profile::report_stat(&mut w, " ", "bc_to_ir time", &self.bc_to_ir_t)?;
profile::report_stat(&mut w, " ", "ir_to_bc time", &self.ir_to_bc_t)?;
profile::report_stat(&mut w, " ", "verify time", &self.verify_t)?;
if !self.global_strings.is_empty() {
let mut hist: hdrhistogram::Histogram<u64> = hdrhistogram::Histogram::new(3).unwrap();
let mut total = 0;
for s in self.global_strings.iter() {
let len = s.len() as u64;
total += len;
hist.record(len).unwrap();
}
writeln!(w)?;
writeln!(w, "String Interning:")?;
writeln!(w, " {} unique strings, {total} bytes total", hist.len())?;
write!(w, " min: {}B", hist.min())?;
write!(w, ", P50: {}B", hist.value_at_percentile(50.0))?;
write!(w, ", P90: {}B", hist.value_at_percentile(90.0))?;
write!(w, ", P99: {}B", hist.value_at_percentile(99.0))?;
writeln!(w, ", max: {}B", hist.max())?;
}
Ok(())
}
fn record_error(mut self, err: VerifyError, f: &Path) -> Self {
self.passed = false;
self.error_histogram
.entry(err)
.or_insert_with(|| (0, f.to_path_buf()))
.0 += 1;
self
}
fn num_failed(&self) -> usize {
self.error_histogram
.values()
.fold(0, |acc, (val, _)| acc + val)
}
}
fn verify_one_file(path: &Path, mode: &Mode) -> ProfileAcc {
let mut acc = ProfileAcc::default();
let content = match fs::read(path) {
Ok(content) => content,
Err(err) => {
return acc.record_error(VerifyError::ReadError(err.to_string()), path);
}
};
let files = match multifile::to_files(path, content) {
Ok(files) => files,
Err(err) => {
return acc.record_error(VerifyError::MultifileError(err.to_string()), path);
}
};
for (path, content) in files {
let mut file_profile = ProfileAcc::default();
let result = if mode.common().panic_fuse {
mode.verify_file(&path, content, &mut file_profile)
} else {
with_catch_panics(&mut file_profile, mode.common().long_msg, |file_profile| {
mode.verify_file(&path, content, file_profile)
})
};
acc = acc.fold(file_profile);
if let Err(err) = result {
return acc.record_error(err, &path);
}
}
acc
}
fn verify_files(files: &[PathBuf], mode: &Mode) -> anyhow::Result<()> {
let total = files.len();
let status_ticker = StatusTicker::new(total);
let verify_one_file_ = |acc: ProfileAcc, f: &PathBuf| -> ProfileAcc {
status_ticker.start_file(f);
let profile = verify_one_file(f, mode);
status_ticker.finish_file(f);
acc.fold(profile)
};
println!("Files: {}", files.len());
let profile = if mode.common().num_threads == 1 {
files.iter().fold(ProfileAcc::default(), verify_one_file_)
} else {
files
.par_iter()
.with_max_len(1)
.fold(ProfileAcc::default, verify_one_file_)
.reduce(ProfileAcc::default, ProfileAcc::fold)
};
let (count, duration) = status_ticker.finish();
profile.report_final(duration, count, total, mode.common().show_all)?;
ensure!(
profile.passed,
"{} files failed to verify",
profile.num_failed()
);
Ok(())
}
pub fn run(mut opts: Opts) -> anyhow::Result<()> {
let num_threads = opts.mode.common().num_threads;
opts.mode.setup();
let files = opts
.mode
.common_mut()
.files
.collect_input_files(num_threads)?;
if files.len() == 1 {
opts.mode.common_mut().panic_fuse = true;
}
let mut old_hook = None;
if !opts.mode.common().panic_fuse {
old_hook = Some(std::panic::take_hook());
std::panic::set_hook(Box::new(|info| {
let msg = panic_message::panic_info_message(info);
let msg = if let Some(loc) = info.location() {
let mut file = loc.file().to_string();
if file.len() > 20 {
file.replace_range(0..file.len() - 17, "...");
}
format!("{}@{}: {}", file, loc.line(), msg)
} else {
format!("<unknown>: {}", msg)
};
PANIC_MSG.with(|tls| {
*tls.borrow_mut() = Some(msg);
});
}));
}
verify_files(&files, &opts.mode)?;
if let Some(old_hook) = old_hook {
std::panic::set_hook(old_hook);
}
Ok(())
} |
Rust | hhvm/hphp/hack/src/hackc/compile/closure_convert.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::borrow::Cow;
use std::sync::Arc;
use env::emitter::Emitter;
use error::Error;
use error::Result;
use global_state::ClosureEnclosingClassInfo;
use global_state::GlobalState;
use hack_macros::hack_expr;
use hash::IndexSet;
use hhbc::Coeffects;
use hhbc_string_utils as string_utils;
use itertools::Itertools;
use naming_special_names_rust::members;
use naming_special_names_rust::pseudo_consts;
use naming_special_names_rust::pseudo_functions;
use naming_special_names_rust::special_idents;
use naming_special_names_rust::superglobals;
use options::Options;
use oxidized::aast_visitor;
use oxidized::aast_visitor::visit_mut;
use oxidized::aast_visitor::AstParams;
use oxidized::aast_visitor::NodeMut;
use oxidized::aast_visitor::VisitorMut;
use oxidized::ast::Abstraction;
use oxidized::ast::Block;
use oxidized::ast::CallExpr;
use oxidized::ast::CaptureLid;
use oxidized::ast::ClassGetExpr;
use oxidized::ast::ClassHint;
use oxidized::ast::ClassId;
use oxidized::ast::ClassId_;
use oxidized::ast::ClassName;
use oxidized::ast::ClassVar;
use oxidized::ast::Class_;
use oxidized::ast::ClassishKind;
use oxidized::ast::Contexts;
use oxidized::ast::Def;
use oxidized::ast::Efun;
use oxidized::ast::EmitId;
use oxidized::ast::Expr;
use oxidized::ast::Expr_;
use oxidized::ast::FunDef;
use oxidized::ast::FunKind;
use oxidized::ast::FunParam;
use oxidized::ast::Fun_;
use oxidized::ast::FuncBody;
use oxidized::ast::Hint;
use oxidized::ast::Hint_;
use oxidized::ast::Id;
use oxidized::ast::Lid;
use oxidized::ast::LocalId;
use oxidized::ast::Method_;
use oxidized::ast::Pos;
use oxidized::ast::ReifyKind;
use oxidized::ast::Sid;
use oxidized::ast::Stmt;
use oxidized::ast::Stmt_;
use oxidized::ast::Tparam;
use oxidized::ast::TypeHint;
use oxidized::ast::UserAttribute;
use oxidized::ast::UserAttributes;
use oxidized::ast::Visibility;
use oxidized::ast_defs::ParamKind;
use oxidized::ast_defs::PropOrMethod;
use oxidized::file_info::Mode;
use oxidized::local_id;
use oxidized::namespace_env;
use oxidized::s_map::SMap;
use unique_id_builder::get_unique_id_for_function;
use unique_id_builder::get_unique_id_for_main;
use unique_id_builder::get_unique_id_for_method;
#[derive(Default)]
struct Variables {
/// all variables declared/used in the scope
all_vars: IndexSet<String>,
/// names of parameters if scope correspond to a function
parameter_names: IndexSet<String>,
/// If this is a long lambda then the list of explicitly captured vars (if
/// any).
explicit_capture: IndexSet<String>,
}
struct ClassSummary<'b> {
extends: &'b [ClassHint],
kind: ClassishKind,
mode: Mode,
name: &'b ClassName,
span: &'b Pos,
tparams: &'b [Tparam],
}
struct FunctionSummary<'b, 'arena> {
// Unfortunately hhbc::Coeffects has to be owned for now.
coeffects: Coeffects<'arena>,
fun_kind: FunKind,
mode: Mode,
name: &'b Sid,
span: &'b Pos,
tparams: &'b [Tparam],
}
struct LambdaSummary<'b, 'arena> {
// Unfortunately hhbc::Coeffects has to be owned for now.
coeffects: Coeffects<'arena>,
explicit_capture: Option<&'b [CaptureLid]>,
fun_kind: FunKind,
span: &'b Pos,
}
struct MethodSummary<'b, 'arena> {
// Unfortunately hhbc::Coeffects has to be owned for now.
coeffects: Coeffects<'arena>,
fun_kind: FunKind,
name: &'b Sid,
span: &'b Pos,
static_: bool,
tparams: &'b [Tparam],
}
enum ScopeSummary<'b, 'arena> {
TopLevel,
Class(ClassSummary<'b>),
Function(FunctionSummary<'b, 'arena>),
Method(MethodSummary<'b, 'arena>),
Lambda(LambdaSummary<'b, 'arena>),
}
impl<'b, 'arena> ScopeSummary<'b, 'arena> {
fn span(&self) -> Option<&Pos> {
match self {
ScopeSummary::TopLevel => None,
ScopeSummary::Class(cd) => Some(cd.span),
ScopeSummary::Function(fd) => Some(fd.span),
ScopeSummary::Method(md) => Some(md.span),
ScopeSummary::Lambda(ld) => Some(ld.span),
}
}
}
/// The environment for a scope. This tracks the summary information and
/// variables used within a scope.
struct Scope<'b, 'arena> {
parent: Option<&'b Scope<'b, 'arena>>,
/// Number of closures created in the current function
closure_cnt_per_fun: u32,
/// Are we immediately in a using statement?
in_using: bool,
/// What is the current context?
summary: ScopeSummary<'b, 'arena>,
/// What variables are defined in this scope?
variables: Variables,
}
impl<'b, 'arena> Scope<'b, 'arena> {
fn toplevel(defs: &[Def]) -> Result<Self> {
let all_vars = compute_vars(&[], &defs)?;
Ok(Self {
in_using: false,
closure_cnt_per_fun: 0,
parent: None,
summary: ScopeSummary::TopLevel,
variables: Variables {
all_vars,
..Variables::default()
},
})
}
fn as_class_summary(&self) -> Option<&ClassSummary<'_>> {
self.walk_scope().find_map(|scope| match &scope.summary {
ScopeSummary::Class(cd) => Some(cd),
_ => None,
})
}
fn check_if_in_async_context(&self) -> Result<()> {
let check_valid_fun_kind = |name, kind: FunKind| {
if !kind.is_async() {
Err(Error::fatal_parse(
&self.span_or_none(),
format!(
"Function '{}' contains 'await' but is not declared as async.",
string_utils::strip_global_ns(name)
),
))
} else {
Ok(())
}
};
let check_lambda = |is_async: bool| {
if !is_async {
Err(Error::fatal_parse(
&self.span_or_none(),
"Await may only appear in an async function",
))
} else {
Ok(())
}
};
match &self.summary {
ScopeSummary::TopLevel => Err(Error::fatal_parse(
&self.span_or_none(),
"'await' can only be used inside a function",
)),
ScopeSummary::Lambda(ld) => check_lambda(ld.fun_kind.is_async()),
ScopeSummary::Class(_) => Ok(()), /* Syntax error, wont get here */
ScopeSummary::Function(fd) => check_valid_fun_kind(&fd.name.1, fd.fun_kind),
ScopeSummary::Method(md) => check_valid_fun_kind(&md.name.1, md.fun_kind),
}
}
fn class_tparams(&self) -> &[Tparam] {
self.as_class_summary().map_or(&[], |cd| cd.tparams)
}
fn coeffects_of_scope<'c>(&'c self) -> Option<&'c Coeffects<'arena>> {
for scope in self.walk_scope() {
match &scope.summary {
ScopeSummary::Class(_) => break,
ScopeSummary::Method(md) => return Some(&md.coeffects),
ScopeSummary::Function(fd) => return Some(&fd.coeffects),
ScopeSummary::Lambda(ld) => {
if !ld.coeffects.get_static_coeffects().is_empty() {
return Some(&ld.coeffects);
}
}
ScopeSummary::TopLevel => {}
}
}
None
}
fn fun_tparams(&self) -> &[Tparam] {
for scope in self.walk_scope() {
match &scope.summary {
ScopeSummary::Class(_) => break,
ScopeSummary::Function(fd) => return fd.tparams,
ScopeSummary::Method(md) => return md.tparams,
_ => {}
}
}
&[]
}
fn is_in_debugger_eval_fun(&self) -> bool {
let mut cur = Some(self);
while let Some(scope) = cur {
match &scope.summary {
ScopeSummary::Lambda(_) => {}
ScopeSummary::Function(fd) => return fd.name.1 == "include",
_ => break,
}
cur = scope.parent;
}
false
}
fn is_static(&self) -> bool {
for scope in self.walk_scope() {
match &scope.summary {
ScopeSummary::Function(_) => return true,
ScopeSummary::Method(md) => return md.static_,
ScopeSummary::Lambda(_) => {}
ScopeSummary::Class(_) | ScopeSummary::TopLevel => unreachable!(),
}
}
unreachable!();
}
fn make_scope_name(&self, ns: &Arc<namespace_env::Env>) -> String {
let mut parts = Vec::new();
let mut iter = self.walk_scope();
while let Some(scope) = iter.next() {
match &scope.summary {
ScopeSummary::Class(cd) => {
parts.push(make_class_name(cd.name));
break;
}
ScopeSummary::Function(fd) => {
let fname = strip_id(fd.name);
parts.push(fname.into());
for sub_scope in iter {
match &sub_scope.summary {
ScopeSummary::Class(cd) => {
parts.push("::".into());
parts.push(make_class_name(cd.name));
break;
}
_ => {}
}
}
break;
}
ScopeSummary::Method(x) => {
parts.push(strip_id(x.name).to_string());
if !parts.last().map_or(false, |x| x.ends_with("::")) {
parts.push("::".into())
};
}
ScopeSummary::Lambda(_) | ScopeSummary::TopLevel => {}
}
}
if parts.is_empty() {
if let Some(n) = &ns.name {
format!("{}\\", n)
} else {
String::new()
}
} else {
parts.reverse();
parts.join("")
}
}
/// Create a new Env which uses `self` as its parent.
fn new_child<'s>(
&'s self,
summary: ScopeSummary<'s, 'arena>,
variables: Variables,
) -> Result<Scope<'s, 'arena>> {
Ok(Scope {
in_using: self.in_using,
closure_cnt_per_fun: self.closure_cnt_per_fun,
parent: Some(self),
summary,
variables,
})
}
fn scope_fmode(&self) -> Mode {
for scope in self.walk_scope() {
match &scope.summary {
ScopeSummary::Class(cd) => return cd.mode,
ScopeSummary::Function(fd) => return fd.mode,
_ => {}
}
}
Mode::Mstrict
}
fn should_capture_var(&self, var: &str) -> bool {
// variable used in lambda should be captured if is:
// - not contained in lambda parameter list
if self.variables.parameter_names.contains(var) {
return false;
};
// AND
// - it exists in one of enclosing scopes
for scope in self.walk_scope().skip(1) {
let vars = &scope.variables;
if vars.all_vars.contains(var)
|| vars.parameter_names.contains(var)
|| vars.explicit_capture.contains(var)
{
return true;
}
match &scope.summary {
ScopeSummary::Lambda(ld) => {
// A lambda contained within an anonymous function (a 'long'
// lambda) shouldn't capture variables from outside the
// anonymous function unless they're explicitly mentioned in
// the function's use clause.
if ld.explicit_capture.is_some() {
return false;
}
}
ScopeSummary::TopLevel => {}
_ => return false,
}
}
false
}
fn span(&self) -> Option<&Pos> {
self.summary.span()
}
fn span_or_none<'s>(&'s self) -> Cow<'s, Pos> {
if let Some(pos) = self.span() {
Cow::Borrowed(pos)
} else {
Cow::Owned(Pos::NONE)
}
}
fn walk_scope<'s>(&'s self) -> ScopeIter<'b, 's, 'arena> {
ScopeIter(Some(self))
}
fn with_in_using<F, R>(&mut self, in_using: bool, mut f: F) -> R
where
F: FnMut(&mut Self) -> R,
{
let old_in_using = self.in_using;
self.in_using = in_using;
let r = f(self);
self.in_using = old_in_using;
r
}
}
struct ScopeIter<'b, 'c, 'arena>(Option<&'c Scope<'b, 'arena>>);
impl<'b, 'c, 'arena> Iterator for ScopeIter<'b, 'c, 'arena> {
type Item = &'c Scope<'c, 'arena>;
fn next(&mut self) -> Option<Self::Item> {
if let Some(cur) = self.0.take() {
self.0 = cur.parent;
Some(cur)
} else {
None
}
}
}
#[derive(Clone, Default)]
struct CaptureState {
this_: bool,
// Free variables computed so far
vars: IndexSet<String>,
generics: IndexSet<String>,
}
/// ReadOnlyState is split from State because it can be a simple ref in
/// ClosureVisitor.
struct ReadOnlyState<'a> {
// Empty namespace as constructed by parser
empty_namespace: Arc<namespace_env::Env>,
/// For debugger eval
for_debugger_eval: bool,
/// Global compiler/hack options
options: &'a Options,
}
/// Mutable state used during visiting in ClosureVisitor. It's mutable and owned
/// so it needs to be moved as we push and pop scopes.
struct State<'arena> {
capture_state: CaptureState,
// Closure classes
closures: Vec<Class_>,
// accumulated information about program
global_state: GlobalState<'arena>,
/// Hoisted meth_caller functions
named_hoisted_functions: SMap<FunDef>,
// The current namespace environment
namespace: Arc<namespace_env::Env>,
}
impl<'arena> State<'arena> {
fn initial_state(empty_namespace: Arc<namespace_env::Env>) -> Self {
Self {
capture_state: Default::default(),
closures: vec![],
global_state: GlobalState::default(),
named_hoisted_functions: SMap::new(),
namespace: empty_namespace,
}
}
fn record_function_state(&mut self, key: String, coeffects_of_scope: Coeffects<'arena>) {
if !coeffects_of_scope.get_static_coeffects().is_empty() {
self.global_state
.lambda_coeffects_of_scope
.insert(key, coeffects_of_scope);
}
}
/// Clear the variables, upon entering a lambda
fn enter_lambda(&mut self) {
self.capture_state.vars = Default::default();
self.capture_state.this_ = false;
self.capture_state.generics = Default::default();
}
fn set_namespace(&mut self, namespace: Arc<namespace_env::Env>) {
self.namespace = namespace;
}
/// Add a variable to the captured variables
fn add_var<'s>(&mut self, scope: &Scope<'_, '_>, var: impl Into<Cow<'s, str>>) {
let var = var.into();
// Don't bother if it's $this, as this is captured implicitly
if var == special_idents::THIS {
self.capture_state.this_ = true;
} else if scope.should_capture_var(&var)
&& (var != special_idents::DOLLAR_DOLLAR)
&& !superglobals::is_superglobal(&var)
{
// If it's bound as a parameter or definite assignment, don't add it
// Also don't add the pipe variable and superglobals
self.capture_state.vars.insert(var.into_owned());
}
}
fn add_generic(&mut self, scope: &mut Scope<'_, '_>, var: &str) {
let reified_var_position = |is_fun| {
let is_reified_var =
|param: &Tparam| param.reified != ReifyKind::Erased && param.name.1 == var;
if is_fun {
scope.fun_tparams().iter().position(is_reified_var)
} else {
scope.class_tparams().iter().position(is_reified_var)
}
};
if let Some(i) = reified_var_position(true) {
let var = string_utils::reified::captured_name(true, i);
self.capture_state.generics.insert(var);
} else if let Some(i) = reified_var_position(false) {
let var = string_utils::reified::captured_name(false, i);
self.capture_state.generics.insert(var);
}
}
}
fn compute_vars(
params: &[FunParam],
body: &impl aast_visitor::Node<AstParams<(), String>>,
) -> Result<IndexSet<String>> {
hhbc::decl_vars::vars_from_ast(params, &body, false).map_err(Error::unrecoverable)
}
fn get_parameter_names(params: &[FunParam]) -> IndexSet<String> {
params.iter().map(|p| p.name.to_string()).collect()
}
fn strip_id(id: &Id) -> &str {
string_utils::strip_global_ns(&id.1)
}
fn make_class_name(name: &ClassName) -> String {
string_utils::mangle_xhp_id(strip_id(name).to_string())
}
fn make_closure_name(scope: &Scope<'_, '_>, state: &State<'_>) -> String {
let per_fun_idx = scope.closure_cnt_per_fun;
let name = scope.make_scope_name(&state.namespace);
string_utils::closures::mangle_closure(&name, per_fun_idx)
}
fn make_closure(
p: Pos,
scope: &Scope<'_, '_>,
state: &State<'_>,
ro_state: &ReadOnlyState<'_>,
lambda_vars: Vec<String>,
fun_tparams: Vec<Tparam>,
class_tparams: Vec<Tparam>,
is_static: bool,
mode: Mode,
fd: &Fun_,
) -> Class_ {
let md = Method_ {
span: fd.span.clone(),
annotation: fd.annotation,
final_: false,
abstract_: false,
static_: is_static,
readonly_this: fd.readonly_this.is_some(),
visibility: Visibility::Public,
name: Id(p.clone(), members::__INVOKE.into()),
tparams: fun_tparams,
where_constraints: vec![],
params: fd.params.clone(),
ctxs: fd.ctxs.clone(),
unsafe_ctxs: None, // TODO(T70095684)
body: fd.body.clone(),
fun_kind: fd.fun_kind,
user_attributes: fd.user_attributes.clone(),
readonly_ret: fd.readonly_ret,
ret: fd.ret.clone(),
external: false,
doc_comment: fd.doc_comment.clone(),
};
let make_class_var = |name: &str| ClassVar {
final_: false,
xhp_attr: None,
abstract_: false,
readonly: false, // readonly on closure_convert
visibility: Visibility::Private,
type_: TypeHint((), None),
id: Id(p.clone(), name.into()),
expr: None,
user_attributes: Default::default(),
doc_comment: None,
is_promoted_variadic: false,
is_static: false,
span: p.clone(),
};
let cvl = lambda_vars
.iter()
.map(|name| make_class_var(string_utils::locals::strip_dollar(name)));
Class_ {
span: p.clone(),
annotation: fd.annotation,
mode,
user_attributes: Default::default(),
file_attributes: vec![],
final_: false,
is_xhp: false,
has_xhp_keyword: false,
kind: ClassishKind::Cclass(Abstraction::Concrete),
name: Id(p.clone(), make_closure_name(scope, state)),
tparams: class_tparams,
extends: vec![Hint(
p.clone(),
Box::new(Hint_::Happly(Id(p.clone(), "Closure".into()), vec![])),
)],
uses: vec![],
xhp_attr_uses: vec![],
xhp_category: None,
reqs: vec![],
implements: vec![],
where_constraints: vec![],
consts: vec![],
typeconsts: vec![],
vars: cvl.collect(),
methods: vec![md],
xhp_children: vec![],
xhp_attrs: vec![],
namespace: Arc::clone(&ro_state.empty_namespace),
enum_: None,
doc_comment: None,
emit_id: Some(EmitId::Anonymous),
// TODO(T116039119): Populate value with presence of internal attribute
internal: false,
// TODO: closures should have the visibility of the module they are defined in
module: None,
docs_url: None,
}
}
/// Translate special identifiers `__CLASS__`, `__METHOD__` and `__FUNCTION__`
/// into literal strings. It's necessary to do this before closure conversion
/// because the enclosing class will be changed.
fn convert_id(scope: &Scope<'_, '_>, Id(p, s): Id) -> Expr_ {
let ret = Expr_::mk_string;
let name = |c: &ClassName| {
Expr_::mk_string(string_utils::mangle_xhp_id(strip_id(c).to_string()).into())
};
match s {
_ if s.eq_ignore_ascii_case(pseudo_consts::G__TRAIT__) => match scope.as_class_summary() {
Some(cd) if cd.kind == ClassishKind::Ctrait => name(cd.name),
_ => ret("".into()),
},
_ if s.eq_ignore_ascii_case(pseudo_consts::G__CLASS__) => match scope.as_class_summary() {
Some(cd) if cd.kind != ClassishKind::Ctrait => name(cd.name),
Some(_) => Expr_::mk_id(Id(p, s)),
None => ret("".into()),
},
_ if s.eq_ignore_ascii_case(pseudo_consts::G__METHOD__) => {
let (prefix, is_trait) = match scope.as_class_summary() {
None => ("".into(), false),
Some(cd) => (
string_utils::mangle_xhp_id(strip_id(cd.name).to_string()) + "::",
cd.kind == ClassishKind::Ctrait,
),
};
// for lambdas nested in trait methods HHVM replaces __METHOD__
// with enclosing method name - do the same and bubble up from lambdas *
let id_scope = if is_trait {
scope.walk_scope().find(|x| {
let scope_is_in_lambda = match &x.summary {
ScopeSummary::Lambda(_) => true,
_ => false,
};
!scope_is_in_lambda
})
} else {
scope.walk_scope().next()
};
match id_scope.map(|x| &x.summary) {
Some(ScopeSummary::Function(fd)) => ret((prefix + strip_id(fd.name)).into()),
Some(ScopeSummary::Method(md)) => ret((prefix + strip_id(md.name)).into()),
Some(ScopeSummary::Lambda(_)) => ret((prefix + "{closure}").into()),
// PHP weirdness: __METHOD__ inside a class outside a method returns class name
Some(ScopeSummary::Class(cd)) => ret(strip_id(cd.name).into()),
_ => ret("".into()),
}
}
_ if s.eq_ignore_ascii_case(pseudo_consts::G__FUNCTION__) => match &scope.summary {
ScopeSummary::Function(fd) => ret(strip_id(fd.name).into()),
ScopeSummary::Method(md) => ret(strip_id(md.name).into()),
ScopeSummary::Lambda(_) => ret("{closure}".into()),
_ => ret("".into()),
},
_ if s.eq_ignore_ascii_case(pseudo_consts::G__LINE__) => {
// If the expression goes on multi lines, we return the last line
let (_, line, _, _) = p.info_pos_extended();
Expr_::mk_int(line.to_string())
}
_ => Expr_::mk_id(Id(p, s)),
}
}
fn make_class_info(c: &ClassSummary<'_>) -> ClosureEnclosingClassInfo {
ClosureEnclosingClassInfo {
kind: c.kind,
name: c.name.1.clone(),
parent_class_name: match c.extends {
[x] => x.as_happly().map(|(id, _args)| id.1.clone()),
_ => None,
},
}
}
pub fn make_fn_param(pos: Pos, lid: &LocalId, is_variadic: bool, is_inout: bool) -> FunParam {
FunParam {
annotation: (),
type_hint: TypeHint((), None),
is_variadic,
pos: pos.clone(),
name: local_id::get_name(lid).clone(),
expr: None,
callconv: if is_inout {
ParamKind::Pinout(pos)
} else {
ParamKind::Pnormal
},
readonly: None, // TODO
user_attributes: Default::default(),
visibility: None,
}
}
fn make_dyn_meth_caller_lambda(pos: &Pos, cexpr: &Expr, fexpr: &Expr, force: bool) -> Expr_ {
let pos = || pos.clone();
let obj_var = Box::new(Lid(pos(), local_id::make_unscoped("$o")));
let meth_var = Box::new(Lid(pos(), local_id::make_unscoped("$m")));
let obj_lvar = Expr((), pos(), Expr_::Lvar(obj_var.clone()));
let meth_lvar = Expr((), pos(), Expr_::Lvar(meth_var.clone()));
// AST for: return $o-><func>(...$args);
let args_var = local_id::make_unscoped("$args");
let variadic_param = make_fn_param(pos(), &args_var, true, false);
let invoke_method = hack_expr!(
pos = pos(),
r#"#obj_lvar->#meth_lvar(...#{lvar(args_var)})"#
);
let attrs = if force {
UserAttributes(vec![UserAttribute {
name: Id(pos(), "__DynamicMethCallerForce".into()),
params: vec![],
}])
} else {
Default::default()
};
let ctxs = Some(Contexts(
pos(),
vec![Hint::new(
pos(),
Hint_::mk_happly(Id(pos(), string_utils::coeffects::CALLER.into()), vec![]),
)],
));
let fd = Fun_ {
span: pos(),
annotation: (),
readonly_this: None, // TODO: readonly_this in closure_convert
readonly_ret: None, // TODO: readonly_ret in closure convert
ret: TypeHint((), None),
params: vec![
make_fn_param(pos(), &obj_var.1, false, false),
make_fn_param(pos(), &meth_var.1, false, false),
variadic_param,
],
ctxs,
unsafe_ctxs: None,
body: FuncBody {
fb_ast: Block(vec![Stmt(
pos(),
Stmt_::Return(Box::new(Some(invoke_method))),
)]),
},
fun_kind: FunKind::FSync,
user_attributes: attrs,
external: false,
doc_comment: None,
};
let force_val = if force { Expr_::True } else { Expr_::False };
let force_val_expr = Expr((), pos(), force_val);
let efun = Expr(
(),
pos(),
Expr_::mk_efun(Efun {
fun: fd,
use_: vec![],
closure_class_name: None,
}),
);
let fun_handle = hack_expr!(
pos = pos(),
r#"\__SystemLib\dynamic_meth_caller(#{clone(cexpr)}, #{clone(fexpr)}, #efun, #force_val_expr)"#
);
fun_handle.2
}
fn add_reified_property(tparams: &[Tparam], vars: &mut Vec<ClassVar>) {
if !tparams.iter().all(|t| t.reified == ReifyKind::Erased) {
let p = Pos::NONE;
// varray/vec that holds a list of type structures
// this prop will be initilized during runtime
let hint = Hint(
p.clone(),
Box::new(Hint_::Happly(Id(p.clone(), "\\HH\\varray".into()), vec![])),
);
vars.insert(
0,
ClassVar {
final_: false,
xhp_attr: None,
is_promoted_variadic: false,
doc_comment: None,
abstract_: false,
readonly: false,
visibility: Visibility::Private,
type_: TypeHint((), Some(hint)),
id: Id(p.clone(), string_utils::reified::PROP_NAME.into()),
expr: None,
user_attributes: Default::default(),
is_static: false,
span: p,
},
)
}
}
struct ClosureVisitor<'a, 'b, 'arena> {
alloc: &'arena bumpalo::Bump,
state: Option<State<'arena>>,
ro_state: &'a ReadOnlyState<'a>,
// We need 'b to be a real lifetime so that our `type Params` can refer to
// it - but we don't actually have any fields that use it - so we need a
// Phantom.
phantom: std::marker::PhantomData<&'b ()>,
}
impl<'ast, 'a: 'b, 'b, 'arena: 'a> VisitorMut<'ast> for ClosureVisitor<'a, 'b, 'arena> {
type Params = AstParams<Scope<'b, 'arena>, Error>;
fn object(&mut self) -> &mut dyn VisitorMut<'ast, Params = Self::Params> {
self
}
fn visit_method_(&mut self, scope: &mut Scope<'b, 'arena>, md: &mut Method_) -> Result<()> {
let cd = scope.as_class_summary().ok_or_else(|| {
Error::unrecoverable("unexpected scope shape - method is not inside the class")
})?;
let variables = Self::compute_variables_from_fun(&md.params, &md.body.fb_ast, None)?;
let coeffects = Coeffects::from_ast(
self.alloc,
md.ctxs.as_ref(),
&md.params,
&md.tparams,
scope.class_tparams(),
);
let si = ScopeSummary::Method(MethodSummary {
coeffects,
fun_kind: md.fun_kind,
name: &md.name,
span: &md.span,
static_: md.static_,
tparams: &md.tparams,
});
self.with_subscope(scope, si, variables, |self_, scope| {
md.body.recurse(scope, self_)?;
let uid = get_unique_id_for_method(&cd.name.1, &md.name.1);
self_
.state_mut()
.record_function_state(uid, Coeffects::default());
visit_mut(self_, scope, &mut md.params)?;
Ok(())
})?;
Ok(())
}
fn visit_class_(&mut self, scope: &mut Scope<'b, 'arena>, cd: &mut Class_) -> Result<()> {
let variables = Variables::default();
let si = ScopeSummary::Class(ClassSummary {
extends: &cd.extends,
kind: cd.kind,
mode: cd.mode,
name: &cd.name,
span: &cd.span,
tparams: &cd.tparams,
});
self.with_subscope(scope, si, variables, |self_, scope| -> Result<()> {
visit_mut(self_, scope, &mut cd.methods)?;
visit_mut(self_, scope, &mut cd.consts)?;
visit_mut(self_, scope, &mut cd.vars)?;
visit_mut(self_, scope, &mut cd.xhp_attrs)?;
visit_mut(self_, scope, &mut cd.user_attributes)?;
add_reified_property(&cd.tparams, &mut cd.vars);
Ok(())
})?;
Ok(())
}
fn visit_def(&mut self, scope: &mut Scope<'b, 'arena>, def: &mut Def) -> Result<()> {
match def {
// need to handle it ourselvses, because visit_fun_ is
// called both for toplevel functions and lambdas
Def::Fun(fd) => {
let variables =
Self::compute_variables_from_fun(&fd.fun.params, &fd.fun.body.fb_ast, None)?;
let coeffects = Coeffects::from_ast(
self.alloc,
fd.fun.ctxs.as_ref(),
&fd.fun.params,
&fd.tparams,
&[],
);
let si = ScopeSummary::Function(FunctionSummary {
coeffects,
fun_kind: fd.fun.fun_kind,
mode: fd.mode,
name: &fd.name,
span: &fd.fun.span,
tparams: &fd.tparams,
});
self.with_subscope(scope, si, variables, |self_, scope| {
fd.fun.body.recurse(scope, self_)?;
let uid = get_unique_id_for_function(&fd.name.1);
self_
.state_mut()
.record_function_state(uid, Coeffects::default());
visit_mut(self_, scope, &mut fd.fun.params)?;
visit_mut(self_, scope, &mut fd.fun.user_attributes)?;
Ok(())
})?;
Ok(())
}
_ => def.recurse(scope, self),
}
}
fn visit_hint_(&mut self, scope: &mut Scope<'b, 'arena>, hint: &mut Hint_) -> Result<()> {
if let Hint_::Happly(id, _) = hint {
self.state_mut().add_generic(scope, id.name())
};
hint.recurse(scope, self)
}
fn visit_stmt_(&mut self, scope: &mut Scope<'b, 'arena>, stmt: &mut Stmt_) -> Result<()> {
match stmt {
Stmt_::Awaitall(x) => {
scope.check_if_in_async_context()?;
x.recurse(scope, self)
}
Stmt_::Do(x) => {
let (b, e) = &mut **x;
scope.with_in_using(false, |scope| visit_mut(self, scope, b))?;
self.visit_expr(scope, e)
}
Stmt_::While(x) => {
let (e, b) = &mut **x;
self.visit_expr(scope, e)?;
scope.with_in_using(false, |scope| visit_mut(self, scope, b))
}
Stmt_::Foreach(x) => {
if x.1.is_await_as_v() || x.1.is_await_as_kv() {
scope.check_if_in_async_context()?
}
x.recurse(scope, self)
}
Stmt_::For(x) => {
let (e1, e2, e3, b) = &mut **x;
for e in e1 {
self.visit_expr(scope, e)?;
}
if let Some(e) = e2 {
self.visit_expr(scope, e)?;
}
scope.with_in_using(false, |scope| visit_mut(self, scope, b))?;
for e in e3 {
self.visit_expr(scope, e)?;
}
Ok(())
}
Stmt_::Switch(x) => {
let (e, cl, dfl) = &mut **x;
self.visit_expr(scope, e)?;
scope.with_in_using(false, |scope| visit_mut(self, scope, cl))?;
match dfl {
None => Ok(()),
Some(dfl) => scope.with_in_using(false, |scope| visit_mut(self, scope, dfl)),
}
}
Stmt_::Using(x) => {
if x.has_await {
scope.check_if_in_async_context()?;
}
for e in &mut x.exprs.1 {
self.visit_expr(scope, e)?;
}
scope.with_in_using(true, |scope| visit_mut(self, scope, &mut x.block))?;
Ok(())
}
_ => stmt.recurse(scope, self),
}
}
fn visit_expr(
&mut self,
scope: &mut Scope<'b, 'arena>,
Expr(_, pos, e): &mut Expr,
) -> Result<()> {
stack_limit::maybe_grow(|| {
*e = match strip_unsafe_casts(e) {
Expr_::Efun(x) => self.convert_lambda(scope, x.fun, Some(x.use_))?,
Expr_::Lfun(x) => self.convert_lambda(scope, x.0, None)?,
Expr_::Lvar(id_orig) => {
let id = if self.ro_state.for_debugger_eval
&& local_id::get_name(&id_orig.1) == special_idents::THIS
&& scope.is_in_debugger_eval_fun()
{
Box::new(Lid(id_orig.0, (0, "$__debugger$this".to_string())))
} else {
id_orig
};
self.state_mut().add_var(scope, local_id::get_name(&id.1));
Expr_::Lvar(id)
}
Expr_::Id(id) if id.name().starts_with('$') => {
let state = self.state_mut();
state.add_var(scope, id.name());
state.add_generic(scope, id.name());
Expr_::Id(id)
}
Expr_::Id(id) => {
self.state_mut().add_generic(scope, id.name());
convert_id(scope, *id)
}
Expr_::Call(x) if is_dyn_meth_caller(&x) => {
self.visit_dyn_meth_caller(scope, x, &*pos)?
}
Expr_::Call(x)
if is_meth_caller(&x)
&& self.ro_state.options.hhbc.emit_meth_caller_func_pointers =>
{
self.visit_meth_caller_funcptr(scope, x, &*pos)?
}
Expr_::Call(x) if is_meth_caller(&x) => self.visit_meth_caller(scope, x)?,
Expr_::Call(x)
if (x.func)
.as_class_get()
.and_then(|(id, _, _)| id.as_ciexpr())
.and_then(|x| x.as_id())
.map_or(false, string_utils::is_parent)
|| (x.func)
.as_class_const()
.and_then(|(id, _)| id.as_ciexpr())
.and_then(|x| x.as_id())
.map_or(false, string_utils::is_parent) =>
{
self.state_mut().add_var(scope, "$this");
let mut res = Expr_::Call(x);
res.recurse(scope, self)?;
res
}
Expr_::ClassGet(mut x) => {
if let (ClassGetExpr::CGstring(id), PropOrMethod::IsMethod) = (&x.1, x.2) {
self.state_mut().add_var(scope, &id.1);
};
x.recurse(scope, self)?;
Expr_::ClassGet(x)
}
Expr_::Await(mut x) => {
scope.check_if_in_async_context()?;
x.recurse(scope, self)?;
Expr_::Await(x)
}
Expr_::ReadonlyExpr(mut x) => {
x.recurse(scope, self)?;
Expr_::ReadonlyExpr(x)
}
Expr_::ExpressionTree(mut x) => {
x.runtime_expr.recurse(scope, self)?;
Expr_::ExpressionTree(x)
}
mut x => {
x.recurse(scope, self)?;
x
}
};
Ok(())
})
}
}
impl<'a: 'b, 'b, 'arena: 'a + 'b> ClosureVisitor<'a, 'b, 'arena> {
/// Calls a function in the scope of a sub-Scope as a child of `scope`.
fn with_subscope<'s, F, R>(
&mut self,
scope: &'s Scope<'b, 'arena>,
si: ScopeSummary<'s, 'arena>,
variables: Variables,
f: F,
) -> Result<(R, u32)>
where
'b: 's,
F: FnOnce(&mut ClosureVisitor<'a, 's, 'arena>, &mut Scope<'s, 'arena>) -> Result<R>,
{
let mut scope = scope.new_child(si, variables)?;
let mut self_ = ClosureVisitor {
alloc: self.alloc,
ro_state: self.ro_state,
state: self.state.take(),
phantom: Default::default(),
};
let res = f(&mut self_, &mut scope);
self.state = self_.state;
Ok((res?, scope.closure_cnt_per_fun))
}
fn state(&self) -> &State<'arena> {
self.state.as_ref().unwrap()
}
fn state_mut(&mut self) -> &mut State<'arena> {
self.state.as_mut().unwrap()
}
#[inline(never)]
fn visit_dyn_meth_caller(
&mut self,
scope: &mut Scope<'b, 'arena>,
mut x: Box<CallExpr>,
pos: &Pos,
) -> Result<Expr_> {
let force = if let Expr_::Id(ref id) = x.func.2 {
strip_id(id).eq_ignore_ascii_case("hh\\dynamic_meth_caller_force")
} else {
false
};
if let [(pk_c, cexpr), (pk_f, fexpr)] = &mut *x.args {
error::ensure_normal_paramkind(pk_c)?;
error::ensure_normal_paramkind(pk_f)?;
let mut res = make_dyn_meth_caller_lambda(pos, cexpr, fexpr, force);
res.recurse(scope, self)?;
Ok(res)
} else {
let mut res = Expr_::Call(x);
res.recurse(scope, self)?;
Ok(res)
}
}
#[inline(never)]
fn visit_meth_caller_funcptr(
&mut self,
scope: &mut Scope<'b, 'arena>,
mut x: Box<CallExpr>,
pos: &Pos,
) -> Result<Expr_> {
if let [(pk_cls, Expr(_, pc, cls)), (pk_f, Expr(_, pf, func))] = &mut *x.args {
error::ensure_normal_paramkind(pk_cls)?;
error::ensure_normal_paramkind(pk_f)?;
match (&cls, func.as_string()) {
(Expr_::ClassConst(cc), Some(fname)) if string_utils::is_class(&(cc.1).1) => {
let mut cls_const = cls.as_class_const_mut();
let (cid, _) = match cls_const {
None => unreachable!(),
Some((ref mut cid, (_, cs))) => (cid, cs),
};
self.visit_class_id(scope, cid)?;
match &cid.2 {
cid if cid
.as_ciexpr()
.and_then(Expr::as_id)
.map_or(false, |id| !is_selflike_keyword(id)) =>
{
let alloc = bumpalo::Bump::new();
let id = cid.as_ciexpr().unwrap().as_id().unwrap();
let mangled_class_name =
hhbc::ClassName::from_ast_name_and_mangle(&alloc, id.as_ref());
let mangled_class_name = mangled_class_name.unsafe_as_str();
Ok(self.convert_meth_caller_to_func_ptr(
scope,
pos,
pc,
mangled_class_name,
pf,
// FIXME: This is not safe--string literals are binary
// strings. There's no guarantee that they're valid UTF-8.
unsafe { std::str::from_utf8_unchecked(fname.as_slice()) },
))
}
_ => Err(Error::fatal_parse(pc, "Invalid class")),
}
}
(Expr_::String(cls_name), Some(fname)) => Ok(self.convert_meth_caller_to_func_ptr(
scope,
pos,
pc,
// FIXME: This is not safe--string literals are binary strings.
// There's no guarantee that they're valid UTF-8.
unsafe { std::str::from_utf8_unchecked(cls_name.as_slice()) },
pf,
// FIXME: This is not safe--string literals are binary strings.
// There's no guarantee that they're valid UTF-8.
unsafe { std::str::from_utf8_unchecked(fname.as_slice()) },
)),
(_, Some(_)) => Err(Error::fatal_parse(
pc,
"Class must be a Class or string type",
)),
(_, _) => Err(Error::fatal_parse(
pf,
"Method name must be a literal string",
)),
}
} else {
let mut res = Expr_::Call(x);
res.recurse(scope, self)?;
Ok(res)
}
}
#[inline(never)]
fn visit_meth_caller(
&mut self,
scope: &mut Scope<'b, 'arena>,
mut x: Box<CallExpr>,
) -> Result<Expr_> {
if let [(pk_cls, Expr(_, pc, cls)), (pk_f, Expr(_, pf, func))] = &mut *x.args {
error::ensure_normal_paramkind(pk_cls)?;
error::ensure_normal_paramkind(pk_f)?;
match (&cls, func.as_string()) {
(Expr_::ClassConst(cc), Some(_)) if string_utils::is_class(&(cc.1).1) => {
let mut cls_const = cls.as_class_const_mut();
let cid = match cls_const {
None => unreachable!(),
Some((ref mut cid, (_, _))) => cid,
};
if cid
.as_ciexpr()
.and_then(Expr::as_id)
.map_or(false, |id| !is_selflike_keyword(id))
{
let mut res = Expr_::Call(x);
res.recurse(scope, self)?;
Ok(res)
} else {
Err(Error::fatal_parse(pc, "Invalid class"))
}
}
(Expr_::String(_), Some(_)) => {
let mut res = Expr_::Call(x);
res.recurse(scope, self)?;
Ok(res)
}
(_, Some(_)) => Err(Error::fatal_parse(
pc,
"Class must be a Class or string type",
)),
(_, _) => Err(Error::fatal_parse(
pf,
"Method name must be a literal string",
)),
}
} else {
let mut res = Expr_::Call(x);
res.recurse(scope, self)?;
Ok(res)
}
}
fn visit_class_id(&mut self, scope: &mut Scope<'b, 'arena>, cid: &mut ClassId) -> Result<()> {
if let ClassId(_, _, ClassId_::CIexpr(e)) = cid {
self.visit_expr(scope, e)?;
}
Ok(())
}
// Closure-convert a lambda expression, with use_vars_opt = Some vars
// if there is an explicit `use` clause.
fn convert_lambda(
&mut self,
scope: &mut Scope<'b, 'arena>,
mut fd: Fun_,
use_vars_opt: Option<Vec<CaptureLid>>,
) -> Result<Expr_> {
let is_long_lambda = use_vars_opt.is_some();
let state = self.state_mut();
// Remember the current capture and defined set across the lambda
let capture_state = state.capture_state.clone();
let coeffects_of_scope = scope
.coeffects_of_scope()
.map_or_else(Default::default, |co| co.clone());
state.enter_lambda();
if let Some(user_vars) = &use_vars_opt {
for CaptureLid(_, Lid(p, id)) in user_vars.iter() {
if local_id::get_name(id) == special_idents::THIS {
return Err(Error::fatal_parse(
p,
"Cannot use $this as lexical variable",
));
}
}
}
let explicit_capture: Option<IndexSet<String>> = use_vars_opt.as_ref().map(|vars| {
vars.iter()
.map(|CaptureLid(_, Lid(_, (_, name)))| name.to_string())
.collect()
});
let variables =
Self::compute_variables_from_fun(&fd.params, &fd.body.fb_ast, explicit_capture)?;
let coeffects = Coeffects::from_ast(self.alloc, fd.ctxs.as_ref(), &fd.params, &[], &[]);
let si = ScopeSummary::Lambda(LambdaSummary {
coeffects,
explicit_capture: use_vars_opt.as_deref(),
fun_kind: fd.fun_kind,
span: &fd.span,
});
let (_, closure_cnt_per_fun) =
self.with_subscope(scope, si, variables, |self_, scope| {
fd.body.recurse(scope, self_)?;
for param in &mut fd.params {
visit_mut(self_, scope, &mut param.type_hint)?;
}
visit_mut(self_, scope, &mut fd.ret)?;
Ok(())
})?;
scope.closure_cnt_per_fun = closure_cnt_per_fun + 1;
let state = self.state.as_mut().unwrap();
let current_generics = state.capture_state.generics.clone();
// TODO(hrust): produce real unique local ids
let fresh_lid = |name: String| CaptureLid((), Lid(Pos::NONE, (12345, name)));
let lambda_vars: Vec<&String> = state
.capture_state
.vars
.iter()
.chain(current_generics.iter())
// HHVM lists lambda vars in descending order - do the same
.sorted()
.rev()
.collect();
// Remove duplicates, (not efficient, but unlikely to be large),
// remove variables that are actually just parameters
let use_vars_opt: Option<Vec<CaptureLid>> = use_vars_opt.map(|use_vars| {
let params = &fd.params;
use_vars
.into_iter()
.rev()
.unique_by(|lid| lid.1.name().to_string())
.filter(|x| !params.iter().any(|y| x.1.name() == &y.name))
.collect::<Vec<_>>()
.into_iter()
.rev()
.collect()
});
// For lambdas with explicit `use` variables, we ignore the computed
// capture set and instead use the explicit set
let (lambda_vars, use_vars): (Vec<String>, Vec<CaptureLid>) = match use_vars_opt {
None => (
lambda_vars.iter().map(|x| x.to_string()).collect(),
lambda_vars
.iter()
.map(|x| fresh_lid(x.to_string()))
.collect(),
),
Some(use_vars) => {
// We still need to append the generics
(
use_vars
.iter()
.map(|x| x.1.name())
.chain(current_generics.iter())
.map(|x| x.to_string())
.collect(),
use_vars
.iter()
.cloned()
.chain(current_generics.iter().map(|x| fresh_lid(x.to_string())))
.collect(),
)
}
};
let fun_tparams = scope.fun_tparams().to_vec(); // hiddden .clone()
let class_tparams = scope.class_tparams().to_vec(); // hiddden .clone()
let is_static = if is_long_lambda {
// long lambdas are never static
false
} else {
// short lambdas can be made static if they don't capture this in
// any form (including any nested lambdas)
!state.capture_state.this_
};
// check if something can be promoted to static based on enclosing scope
let is_static = is_static || scope.is_static();
let pos = fd.span.clone();
let lambda_vars_clone = lambda_vars.clone();
let cd = make_closure(
pos,
scope,
state,
self.ro_state,
lambda_vars,
fun_tparams,
class_tparams,
is_static,
scope.scope_fmode(),
&fd,
);
let closure_class_name = cd.name.1.clone();
if is_long_lambda {
state
.global_state
.explicit_use_set
.insert(closure_class_name.clone());
}
if let Some(cd) = scope.as_class_summary() {
state
.global_state
.closure_enclosing_classes
.insert(closure_class_name.clone(), make_class_info(cd));
}
// Restore capture and defined set
// - adjust captured $this information if lambda that was just processed was
// converted into non-static one
state.capture_state = CaptureState {
this_: capture_state.this_ || !is_static,
..capture_state
};
state
.global_state
.closure_namespaces
.insert(closure_class_name.clone(), state.namespace.clone());
state.record_function_state(
get_unique_id_for_method(&cd.name.1, &cd.methods.first().unwrap().name.1),
coeffects_of_scope,
);
// Add lambda captured vars to current captured vars
for var in lambda_vars_clone.into_iter() {
state.add_var(scope, var)
}
for x in current_generics.iter() {
state.capture_state.generics.insert(x.to_string());
}
state.closures.push(cd);
let efun = Efun {
fun: fd,
use_: use_vars,
closure_class_name: Some(closure_class_name),
};
Ok(Expr_::mk_efun(efun))
}
fn convert_meth_caller_to_func_ptr(
&mut self,
scope: &Scope<'_, '_>,
pos: &Pos,
pc: &Pos,
cls: &str,
pf: &Pos,
fname: &str,
) -> Expr_ {
let pos = || pos.clone();
let cname = match scope.as_class_summary() {
Some(cd) => &cd.name.1,
None => "",
};
let mangle_name = string_utils::mangle_meth_caller(cls, fname);
let fun_handle = hack_expr!(
pos = pos(),
r#"\__SystemLib\meth_caller(#{str(clone(mangle_name))})"#
);
if self
.state()
.named_hoisted_functions
.contains_key(&mangle_name)
{
return fun_handle.2;
}
// AST for: invariant(is_a($o, <cls>), 'object must be an instance of <cls>');
let obj_var = Box::new(Lid(pos(), local_id::make_unscoped("$o")));
let obj_lvar = Expr((), pos(), Expr_::Lvar(obj_var.clone()));
let msg = format!("object must be an instance of ({})", cls);
let assert_invariant = hack_expr!(
pos = pos(),
r#"\HH\invariant(\is_a(#{clone(obj_lvar)}, #{str(clone(cls), pc)}), #{str(msg)})"#
);
// AST for: return $o-><func>(...$args);
let args_var = local_id::make_unscoped("$args");
let variadic_param = make_fn_param(pos(), &args_var, true, false);
let meth_caller_handle = hack_expr!(
pos = pos(),
r#"#obj_lvar->#{id(clone(fname), pf)}(...#{lvar(args_var)})"#
);
let f = Fun_ {
span: pos(),
annotation: (),
readonly_this: None, // TODO(readonly): readonly_this in closure_convert
readonly_ret: None,
ret: TypeHint((), None),
params: vec![
make_fn_param(pos(), &obj_var.1, false, false),
variadic_param,
],
ctxs: None,
unsafe_ctxs: None,
body: FuncBody {
fb_ast: Block(vec![
Stmt(pos(), Stmt_::Expr(Box::new(assert_invariant))),
Stmt(pos(), Stmt_::Return(Box::new(Some(meth_caller_handle)))),
]),
},
fun_kind: FunKind::FSync,
user_attributes: UserAttributes(vec![UserAttribute {
name: Id(pos(), "__MethCaller".into()),
params: vec![Expr((), pos(), Expr_::String(cname.into()))],
}]),
external: false,
doc_comment: None,
};
let fd = FunDef {
file_attributes: vec![],
namespace: Arc::clone(&self.ro_state.empty_namespace),
mode: scope.scope_fmode(),
name: Id(pos(), mangle_name.clone()),
fun: f,
// TODO(T116039119): Populate value with presence of internal attribute
internal: false,
// TODO: meth_caller should have the visibility of the module it is defined in
module: None,
tparams: vec![],
where_constraints: vec![],
};
self.state_mut()
.named_hoisted_functions
.insert(mangle_name, fd);
fun_handle.2
}
fn compute_variables_from_fun(
params: &[FunParam],
body: &[Stmt],
explicit_capture: Option<IndexSet<String>>,
) -> Result<Variables> {
let parameter_names = get_parameter_names(params);
let all_vars = compute_vars(params, &body)?;
let explicit_capture = explicit_capture.unwrap_or_default();
Ok(Variables {
parameter_names,
all_vars,
explicit_capture,
})
}
}
/// Swap *e with Expr_::Null, then return it with UNSAFE_CAST
/// and UNSAFE_NONNULL_CAST stripped off.
fn strip_unsafe_casts(e: &mut Expr_) -> Expr_ {
let null = Expr_::mk_null();
let mut e_owned = std::mem::replace(e, null);
/*
If this is a call of the form
HH\FIXME\UNSAFE_CAST(e, ...)
or
HH\FIXME\UNSAFE_NONNULL_CAST(e, ...)
then treat as a no-op by transforming it to
e
Repeat in case there are nested occurrences
*/
loop {
match e_owned {
// Must have at least one argument
Expr_::Call(mut x)
if !x.args.is_empty() && {
// Function name should be HH\FIXME\UNSAFE_CAST
// or HH\FIXME\UNSAFE_NONNULL_CAST
if let Expr_::Id(ref id) = (x.func).2 {
id.1 == pseudo_functions::UNSAFE_CAST
|| id.1 == pseudo_functions::UNSAFE_NONNULL_CAST
} else {
false
}
} =>
{
// Select first argument
let Expr(_, _, e) = x.args.swap_remove(0).1;
e_owned = e;
}
_ => break e_owned,
};
}
}
fn is_dyn_meth_caller(x: &CallExpr) -> bool {
if let Expr_::Id(ref id) = (x.func).2 {
let name = strip_id(id);
name.eq_ignore_ascii_case("hh\\dynamic_meth_caller")
|| name.eq_ignore_ascii_case("hh\\dynamic_meth_caller_force")
} else {
false
}
}
fn is_meth_caller(x: &CallExpr) -> bool {
if let Expr_::Id(ref id) = x.func.2 {
let name = strip_id(id);
name.eq_ignore_ascii_case("hh\\meth_caller") || name.eq_ignore_ascii_case("meth_caller")
} else {
false
}
}
fn is_selflike_keyword(id: &Id) -> bool {
string_utils::is_self(id) || string_utils::is_parent(id) || string_utils::is_static(id)
}
fn hoist_toplevel_functions(defs: &mut Vec<Def>) {
// Reorder the functions so that they appear first.
let (funs, nonfuns): (Vec<Def>, Vec<Def>) = defs.drain(..).partition(|x| x.is_fun());
defs.extend(funs);
defs.extend(nonfuns);
}
fn prepare_defs(defs: &mut [Def]) -> usize {
let mut class_count = 0;
let mut typedef_count = 0;
let mut const_count = 0;
for def in defs.iter_mut() {
match def {
Def::Class(x) => {
x.emit_id = Some(EmitId::EmitId(class_count));
class_count += 1;
}
Def::Typedef(x) => {
x.emit_id = Some(EmitId::EmitId(typedef_count));
typedef_count += 1;
}
Def::Constant(x) => {
x.emit_id = Some(EmitId::EmitId(const_count));
const_count += 1;
}
Def::Namespace(_) => {
// This should have already been flattened by rewrite_program.
unreachable!()
}
Def::FileAttributes(_)
| Def::Fun(_)
| Def::Module(_)
| Def::SetModule(_)
| Def::NamespaceUse(_)
| Def::SetNamespaceEnv(_)
| Def::Stmt(_) => {}
}
}
class_count as usize
}
pub fn convert_toplevel_prog<'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
defs: &mut Vec<Def>,
namespace_env: Arc<namespace_env::Env>,
) -> Result<()> {
prepare_defs(defs);
let mut scope = Scope::toplevel(defs.as_slice())?;
let ro_state = ReadOnlyState {
empty_namespace: Arc::clone(&namespace_env),
for_debugger_eval: e.for_debugger_eval,
options: e.options(),
};
let state = State::initial_state(namespace_env);
let mut visitor = ClosureVisitor {
alloc: e.alloc,
state: Some(state),
ro_state: &ro_state,
phantom: Default::default(),
};
for def in defs.iter_mut() {
visitor.visit_def(&mut scope, def)?;
match def {
Def::SetNamespaceEnv(x) => {
visitor.state_mut().set_namespace(Arc::clone(&*x));
}
Def::Class(_)
| Def::Constant(_)
| Def::FileAttributes(_)
| Def::Fun(_)
| Def::Module(_)
| Def::SetModule(_)
| Def::Namespace(_)
| Def::NamespaceUse(_)
| Def::Stmt(_)
| Def::Typedef(_) => {}
}
}
let mut state = visitor.state.take().unwrap();
state.record_function_state(get_unique_id_for_main(), Coeffects::default());
hoist_toplevel_functions(defs);
let named_fun_defs = state.named_hoisted_functions.into_values().map(Def::mk_fun);
defs.splice(0..0, named_fun_defs);
for class in state.closures.into_iter() {
defs.push(Def::mk_class(class));
}
*e.global_state_mut() = state.global_state;
Ok(())
} |
Rust | hhvm/hphp/hack/src/hackc/compile/compile.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
pub mod dump_expr_tree;
use std::collections::HashSet;
use std::fmt;
use std::sync::Arc;
use std::time::Duration;
use std::time::Instant;
use aast_parser::rust_aast_parser_types::Env as AastEnv;
use aast_parser::rust_aast_parser_types::ParserProfile;
use aast_parser::rust_aast_parser_types::ParserResult;
use aast_parser::AastParser;
use aast_parser::Error as AastError;
use anyhow::anyhow;
use anyhow::Result;
use bstr::ByteSlice;
use bytecode_printer::Context;
use decl_provider::DeclProvider;
use emit_unit::emit_unit;
use env::emitter::Emitter;
use error::Error;
use error::ErrorKind;
use hhbc::FatalOp;
use hhbc::Unit;
use options::HhbcFlags;
use options::Hhvm;
use options::Options;
use options::ParserOptions;
use oxidized::ast;
use oxidized::decl_parser_options::DeclParserOptions;
use oxidized::namespace_env::Env as NamespaceEnv;
use oxidized::naming_error::NamingError;
use oxidized::naming_phase_error::ExperimentalFeature;
use oxidized::naming_phase_error::NamingPhaseError;
use oxidized::nast_check_error::NastCheckError;
use oxidized::parsing_error::ParsingError;
use oxidized::pos::Pos;
use parser_core_types::indexed_source_text::IndexedSourceText;
use parser_core_types::source_text::SourceText;
use parser_core_types::syntax_error::ErrorType;
use relative_path::Prefix;
use relative_path::RelativePath;
use serde::Deserialize;
use serde::Serialize;
use thiserror::Error;
use types::readonly_check;
use types::readonly_nonlocal_infer;
/// Common input needed for compilation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NativeEnv {
pub filepath: RelativePath,
pub hhvm: Hhvm,
pub hhbc_flags: HhbcFlags,
pub flags: EnvFlags,
}
impl Default for NativeEnv {
fn default() -> Self {
Self {
filepath: RelativePath::make(Prefix::Dummy, Default::default()),
hhvm: Default::default(),
hhbc_flags: HhbcFlags::default(),
flags: EnvFlags::default(),
}
}
}
#[derive(Debug, Default, Clone, clap::Args, Serialize, Deserialize)]
pub struct EnvFlags {
/// Enable features only allowed in systemlib
#[clap(long)]
pub is_systemlib: bool,
/// Mutate the program as if we're in the debuger REPL
#[clap(long)]
pub for_debugger_eval: bool,
/// Disable namespace elaboration for toplevel definitions
#[clap(long)]
pub disable_toplevel_elaboration: bool,
/// Dump IR instead of HHAS
#[clap(long)]
pub dump_ir: bool,
/// Compile files using the IR pass
#[clap(long)]
pub enable_ir: bool,
}
impl NativeEnv {
fn to_options(&self) -> Options {
Options {
hhvm: Hhvm {
parser_options: ParserOptions {
po_disable_legacy_soft_typehints: false,
..self.hhvm.parser_options.clone()
},
..self.hhvm.clone()
},
hhbc: self.hhbc_flags.clone(),
..Default::default()
}
}
pub fn to_decl_parser_options(&self) -> DeclParserOptions {
let auto_namespace_map = self.hhvm.aliased_namespaces_cloned().collect();
// Keep in sync with RepoOptionsFlags::initDeclConfig() in runtime-option.cpp
let lang_flags = &self.hhvm.parser_options;
DeclParserOptions {
auto_namespace_map,
disable_xhp_element_mangling: lang_flags.po_disable_xhp_element_mangling,
interpret_soft_types_as_like_types: true,
allow_new_attribute_syntax: lang_flags.po_allow_new_attribute_syntax,
enable_xhp_class_modifier: lang_flags.po_enable_xhp_class_modifier,
php5_compat_mode: true,
hhvm_compat_mode: true,
keep_user_attributes: true,
..Default::default()
}
}
}
/// Compilation profile. All times are in seconds,
/// except when they are ignored and should not be reported,
/// such as in the case hhvm.log_extern_compiler_perf is false.
#[derive(Debug, Default)]
pub struct Profile {
pub parser_profile: ParserProfile,
/// Time in seconds spent in emitter.
pub codegen_t: Duration,
/// Time in seconds spent in bytecode_printer.
pub printing_t: Duration,
/// Time taken by bc_to_ir
pub bc_to_ir_t: Duration,
/// Time taken by ir_to_bc
pub ir_to_bc_t: Duration,
/// Emitter arena allocation volume in bytes.
pub codegen_bytes: u64,
/// Peak stack size during codegen
pub rewrite_peak: u64,
pub emitter_peak: u64,
/// Was the log_extern_compiler_perf flag set?
pub log_enabled: bool,
}
impl Profile {
pub fn fold(a: Self, b: Self) -> Profile {
Profile {
parser_profile: a.parser_profile.fold(b.parser_profile),
codegen_t: a.codegen_t + b.codegen_t,
printing_t: a.printing_t + b.printing_t,
codegen_bytes: a.codegen_bytes + b.codegen_bytes,
bc_to_ir_t: a.bc_to_ir_t + b.bc_to_ir_t,
ir_to_bc_t: a.ir_to_bc_t + b.ir_to_bc_t,
rewrite_peak: std::cmp::max(a.rewrite_peak, b.rewrite_peak),
emitter_peak: std::cmp::max(a.emitter_peak, b.emitter_peak),
log_enabled: a.log_enabled | b.log_enabled,
}
}
pub fn total_t(&self) -> Duration {
self.parser_profile.total_t
+ self.codegen_t
+ self.bc_to_ir_t
+ self.ir_to_bc_t
+ self.printing_t
}
}
/// Compile Hack source code, write HHAS text to `writer`.
/// Update `profile` with stats from any passes that run,
/// even if the compiler ultimately returns Err.
pub fn from_text<'decl>(
writer: &mut dyn std::io::Write,
source_text: SourceText<'_>,
native_env: &NativeEnv,
decl_provider: Option<Arc<dyn DeclProvider<'decl> + 'decl>>,
profile: &mut Profile,
) -> Result<()> {
let alloc = bumpalo::Bump::new();
let path = source_text.file_path().path().to_path_buf();
let mut emitter = create_emitter(native_env, decl_provider, &alloc);
let mut unit = emit_unit_from_text(
&mut emitter,
&native_env.flags,
source_text,
profile,
&elab::CodegenOpts::default(),
)?;
if native_env.flags.enable_ir {
let bc_to_ir_t = Instant::now();
let ir = bc_to_ir::bc_to_ir(&unit, &path);
profile.bc_to_ir_t = bc_to_ir_t.elapsed();
let ir_to_bc_t = Instant::now();
unit = ir_to_bc::ir_to_bc(&alloc, ir);
profile.ir_to_bc_t = ir_to_bc_t.elapsed();
}
unit_to_string(native_env, writer, &unit, profile)?;
profile.codegen_bytes = alloc.allocated_bytes() as u64;
Ok(())
}
fn rewrite_and_emit<'p, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
namespace_env: Arc<NamespaceEnv>,
ast: &'p mut ast::Program,
profile: &'p mut Profile,
) -> Result<Unit<'arena>, Error> {
// First rewrite and modify `ast` in place.
stack_limit::reset();
let result = rewrite_program::rewrite_program(emitter, ast, Arc::clone(&namespace_env));
profile.rewrite_peak = stack_limit::peak() as u64;
stack_limit::reset();
let unit = match result {
Ok(()) => {
// Rewrite ok, now emit.
emit_unit_from_ast(emitter, namespace_env, ast)
}
Err(e) => match e.into_kind() {
ErrorKind::IncludeTimeFatalException(fatal_op, pos, msg) => {
emit_unit::emit_fatal_unit(emitter.alloc, fatal_op, pos, msg)
}
ErrorKind::Unrecoverable(x) => Err(Error::unrecoverable(x)),
},
};
profile.emitter_peak = stack_limit::peak() as u64;
unit
}
pub fn unit_from_text<'arena, 'decl>(
alloc: &'arena bumpalo::Bump,
source_text: SourceText<'_>,
native_env: &NativeEnv,
decl_provider: Option<Arc<dyn DeclProvider<'decl> + 'decl>>,
profile: &mut Profile,
) -> Result<Unit<'arena>> {
unit_from_text_with_opts(
alloc,
source_text,
native_env,
decl_provider,
profile,
&elab::CodegenOpts::default(),
)
}
pub fn unit_from_text_with_opts<'arena, 'decl>(
alloc: &'arena bumpalo::Bump,
source_text: SourceText<'_>,
native_env: &NativeEnv,
decl_provider: Option<Arc<dyn DeclProvider<'decl> + 'decl>>,
profile: &mut Profile,
opts: &elab::CodegenOpts,
) -> Result<Unit<'arena>> {
let mut emitter = create_emitter(native_env, decl_provider, alloc);
emit_unit_from_text(&mut emitter, &native_env.flags, source_text, profile, opts)
}
pub fn unit_to_string(
native_env: &NativeEnv,
writer: &mut dyn std::io::Write,
program: &Unit<'_>,
profile: &mut Profile,
) -> Result<()> {
if native_env.flags.dump_ir {
let ir = bc_to_ir::bc_to_ir(program, native_env.filepath.path());
struct FmtFromIo<'a>(&'a mut dyn std::io::Write);
impl fmt::Write for FmtFromIo<'_> {
fn write_str(&mut self, s: &str) -> fmt::Result {
self.0.write_all(s.as_bytes()).map_err(|_| fmt::Error)
}
}
let print_result;
(print_result, profile.printing_t) = profile_rust::time(|| {
let verbose = false;
ir::print_unit(&mut FmtFromIo(writer), &ir, verbose)
});
print_result?;
} else {
let print_result;
(print_result, profile.printing_t) = profile_rust::time(|| {
let opts = NativeEnv::to_options(native_env);
bytecode_printer::print_unit(
&Context::new(Some(&native_env.filepath), opts.array_provenance()),
writer,
program,
)
});
print_result?;
}
Ok(())
}
fn emit_unit_from_ast<'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
namespace: Arc<NamespaceEnv>,
ast: &mut ast::Program,
) -> Result<Unit<'arena>, Error> {
emit_unit(emitter, namespace, ast)
}
fn check_readonly_and_emit<'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
namespace_env: Arc<NamespaceEnv>,
ast: &mut ast::Program,
profile: &mut Profile,
) -> Result<Unit<'arena>, Error> {
match &emitter.decl_provider {
// If a decl provider is available (DDB is enabled) *and*
// `Hack.Lang.ReadonlyNonlocalInference` is set, then we can rewrite the
// AST to automagically insert `readonly` annotations where needed.
Some(decl_provider) if emitter.options().hhbc.readonly_nonlocal_infer => {
let mut new_ast = readonly_nonlocal_infer::infer(ast, decl_provider.clone());
let res = readonly_check::check_program(&mut new_ast, false);
// Ignores all errors after the first...
if let Some(readonly_check::ReadOnlyError(pos, msg)) = res.into_iter().next() {
return emit_fatal(emitter.alloc, FatalOp::Parse, pos, msg);
}
*ast = new_ast;
}
None | Some(_) => (),
}
rewrite_and_emit(emitter, namespace_env, ast, profile)
}
fn create_namespace_env(emitter: &Emitter<'_, '_>) -> NamespaceEnv {
NamespaceEnv::empty(
emitter.options().hhvm.aliased_namespaces_cloned().collect(),
true, /* is_codegen */
emitter
.options()
.hhvm
.parser_options
.po_disable_xhp_element_mangling,
)
}
fn emit_unit_from_text<'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
flags: &EnvFlags,
source_text: SourceText<'_>,
profile: &mut Profile,
opts: &elab::CodegenOpts,
) -> Result<Unit<'arena>> {
profile.log_enabled = emitter.options().log_extern_compiler_perf();
let type_directed = emitter.decl_provider.is_some();
let namespace_env = Arc::new(create_namespace_env(emitter));
let path = source_text.file_path_rc();
let parse_result = parse_file(
emitter.options(),
source_text,
!flags.disable_toplevel_elaboration,
Arc::clone(&namespace_env),
flags.is_systemlib,
emitter.for_debugger_eval,
type_directed,
profile,
);
let ((unit, profile), codegen_t) = match parse_result {
Ok(mut ast) => {
match elab::elaborate_program_for_codegen(
Arc::clone(&namespace_env),
&path,
&mut ast,
opts,
) {
Ok(()) => profile_rust::time(move || {
(
check_readonly_and_emit(emitter, namespace_env, &mut ast, profile),
profile,
)
}),
Err(errs) => profile_rust::time(move || {
(
emit_fatal_naming_phase_error(emitter.alloc, &errs[0]),
profile,
)
}),
}
}
Err(ParseError(pos, msg, fatal_op)) => {
profile_rust::time(move || (emit_fatal(emitter.alloc, fatal_op, pos, msg), profile))
}
};
profile.codegen_t = codegen_t;
match unit {
Ok(unit) => Ok(unit),
Err(e) => Err(anyhow!("Unhandled Emitter error: {}", e)),
}
}
fn emit_fatal_naming_phase_error<'arena>(
alloc: &'arena bumpalo::Bump,
err: &NamingPhaseError,
) -> Result<Unit<'arena>, Error> {
match err {
NamingPhaseError::Naming(err) => emit_fatal_naming_error(alloc, err),
NamingPhaseError::NastCheck(err) => emit_fatal_nast_check_error(alloc, err),
NamingPhaseError::UnexpectedHint(_) => todo!(),
NamingPhaseError::MalformedAccess(_) => todo!(),
NamingPhaseError::ExperimentalFeature(err) => {
emit_fatal_experimental_feature_error(alloc, err)
}
NamingPhaseError::Parsing(err) => emit_fatal_parsing_error(alloc, err),
}
}
fn emit_fatal_naming_error<'arena>(
alloc: &'arena bumpalo::Bump,
err: &NamingError,
) -> Result<Unit<'arena>, Error> {
match err {
NamingError::UnsupportedTraitUseAs(_) => todo!(),
NamingError::UnsupportedInsteadOf(_) => todo!(),
NamingError::UnexpectedArrow { .. } => todo!(),
NamingError::MissingArrow { .. } => todo!(),
NamingError::DisallowedXhpType { .. } => todo!(),
NamingError::NameIsReserved { .. } => todo!(),
NamingError::DollardollarUnused(_) => todo!(),
NamingError::MethodNameAlreadyBound { .. } => todo!(),
NamingError::ErrorNameAlreadyBound { .. } => todo!(),
NamingError::UnboundName { .. } => todo!(),
NamingError::InvalidFunPointer { .. } => todo!(),
NamingError::Undefined { .. } => todo!(),
NamingError::UndefinedInExprTree { .. } => todo!(),
NamingError::ThisReserved(_) => todo!(),
NamingError::StartWithT(_) => todo!(),
NamingError::AlreadyBound { .. } => todo!(),
NamingError::UnexpectedTypedef { .. } => todo!(),
NamingError::FieldNameAlreadyBound(_) => todo!(),
NamingError::PrimitiveTopLevel(_) => todo!(),
NamingError::PrimitiveInvalidAlias { .. } => todo!(),
NamingError::DynamicNewInStrictMode(_) => todo!(),
NamingError::InvalidTypeAccessRoot { .. } => todo!(),
NamingError::DuplicateUserAttribute { .. } => todo!(),
NamingError::InvalidMemoizeLabel { .. } => todo!(),
NamingError::UnboundAttributeName { .. } => todo!(),
NamingError::ThisNoArgument(_) => todo!(),
NamingError::ObjectCast(_) => todo!(),
NamingError::ThisHintOutsideClass(_) => todo!(),
NamingError::ParentOutsideClass(_) => todo!(),
NamingError::SelfOutsideClass(_) => todo!(),
NamingError::StaticOutsideClass(_) => todo!(),
NamingError::ThisTypeForbidden { .. } => todo!(),
NamingError::NonstaticPropertyWithLsb(_) => todo!(),
NamingError::LowercaseThis { .. } => todo!(),
NamingError::ClassnameParam(_) => todo!(),
NamingError::TparamAppliedToType { .. } => todo!(),
NamingError::TparamWithTparam { .. } => todo!(),
NamingError::ShadowedTparam { .. } => todo!(),
NamingError::MissingTypehint(_) => todo!(),
NamingError::ExpectedVariable(_) => todo!(),
NamingError::TooManyArguments(_) => todo!(),
NamingError::TooFewArguments(_) => todo!(),
NamingError::ExpectedCollection { .. } => todo!(),
NamingError::IllegalCLASS(_) => todo!(),
NamingError::IllegalTRAIT(_) => todo!(),
NamingError::IllegalFun(_) => todo!(),
NamingError::IllegalMemberVariableClass(_) => todo!(),
NamingError::IllegalMethFun(_) => todo!(),
NamingError::IllegalInstMeth(_) => todo!(),
NamingError::IllegalMethCaller(_) => todo!(),
NamingError::IllegalClassMeth(_) => todo!(),
NamingError::LvarInObjGet { .. } => todo!(),
NamingError::ClassMethNonFinalSelf { .. } => todo!(),
NamingError::ClassMethNonFinalCLASS { .. } => todo!(),
NamingError::ConstWithoutTypehint { .. } => todo!(),
NamingError::PropWithoutTypehint { .. } => todo!(),
NamingError::IllegalConstant(_) => todo!(),
NamingError::InvalidRequireImplements(_) => todo!(),
NamingError::InvalidRequireExtends(_) => todo!(),
NamingError::InvalidRequireClass(_) => todo!(),
NamingError::DidYouMean { .. } => todo!(),
NamingError::UsingInternalClass { .. } => todo!(),
NamingError::TooFewTypeArguments(_) => todo!(),
NamingError::DynamicClassNameInStrictMode(_) => todo!(),
NamingError::XhpOptionalRequiredAttr { .. } => todo!(),
NamingError::XhpRequiredWithDefault { .. } => todo!(),
NamingError::ArrayTypehintsDisallowed(_) => todo!(),
NamingError::WildcardHintDisallowed(_) => todo!(),
NamingError::WildcardTparamDisallowed(_) => todo!(),
NamingError::IllegalUseOfDynamicallyCallable { .. } => todo!(),
NamingError::ParentInFunctionPointer { .. } => todo!(),
NamingError::SelfInNonFinalFunctionPointer { .. } => todo!(),
NamingError::InvalidWildcardContext(_) => todo!(),
NamingError::ReturnOnlyTypehint { .. } => todo!(),
NamingError::UnexpectedTypeArguments(_) => todo!(),
NamingError::TooManyTypeArguments(_) => todo!(),
NamingError::ThisAsLexicalVariable(_) => todo!(),
NamingError::HKTUnsupportedFeature { .. } => todo!(),
NamingError::HKTPartialApplication { .. } => todo!(),
NamingError::HKTWildcard(_) => todo!(),
NamingError::HKTImplicitArgument { .. } => todo!(),
NamingError::HKTClassWithConstraintsUsed { .. } => todo!(),
NamingError::HKTAliasWithImplicitConstraints { .. } => todo!(),
NamingError::ExplicitConsistentConstructor { .. } => todo!(),
NamingError::ModuleDeclarationOutsideAllowedFiles(_) => todo!(),
NamingError::DynamicMethodAccess(_) => todo!(),
NamingError::DeprecatedUse { .. } => todo!(),
NamingError::UnnecessaryAttribute { .. } => todo!(),
NamingError::TparamNonShadowingReuse { .. } => todo!(),
NamingError::DynamicHintDisallowed(_) => todo!(),
NamingError::IllegalTypedLocal {
join,
id_pos,
id_name,
def_pos: _,
} => {
// For now, we can only generate this particular error. All of the
// infrastructure for displaying naming errors is in OCaml, and until
// the naming phase is completely ported, we can just special case the
// ones that might come up.
let msg = if *join {
"It is assigned in another branch. Consider moving the definition to an enclosing block."
} else {
"It is already defined. Typed locals must have their type declared before they can be assigned."
};
emit_unit::emit_fatal_unit(
alloc,
FatalOp::Parse,
id_pos.clone(),
format!("Illegal definition of typed local variable {id_name}. {msg}"),
)
}
}
}
fn emit_fatal_nast_check_error<'arena>(
_alloc: &'arena bumpalo::Bump,
err: &NastCheckError,
) -> Result<Unit<'arena>, Error> {
match err {
NastCheckError::RepeatedRecordFieldName { .. } => todo!(),
NastCheckError::DynamicallyCallableReified(_) => todo!(),
NastCheckError::NoConstructParent(_) => todo!(),
NastCheckError::NonstaticMethodInAbstractFinalClass(_) => todo!(),
NastCheckError::ConstructorRequired { .. } => todo!(),
NastCheckError::NotInitialized { .. } => todo!(),
NastCheckError::CallBeforeInit { .. } => todo!(),
NastCheckError::AbstractWithBody(_) => todo!(),
NastCheckError::NotAbstractWithoutTypeconst(_) => todo!(),
NastCheckError::TypeconstDependsOnExternalTparam { .. } => todo!(),
NastCheckError::InterfaceWithPartialTypeconst(_) => todo!(),
NastCheckError::PartiallyAbstractTypeconstDefinition(_) => todo!(),
NastCheckError::RefinementInTypestruct { .. } => todo!(),
NastCheckError::MultipleXhpCategory(_) => todo!(),
NastCheckError::ReturnInGen(_) => todo!(),
NastCheckError::ReturnInFinally(_) => todo!(),
NastCheckError::ToplevelBreak(_) => todo!(),
NastCheckError::ToplevelContinue(_) => todo!(),
NastCheckError::ContinueInSwitch(_) => todo!(),
NastCheckError::AwaitInSyncFunction { .. } => todo!(),
NastCheckError::InterfaceUsesTrait(_) => todo!(),
NastCheckError::StaticMemoizedFunction(_) => todo!(),
NastCheckError::Magic { .. } => todo!(),
NastCheckError::NonInterface { .. } => todo!(),
NastCheckError::ToStringReturnsString(_) => todo!(),
NastCheckError::ToStringVisibility(_) => todo!(),
NastCheckError::UsesNonTrait { .. } => todo!(),
NastCheckError::RequiresNonClass { .. } => todo!(),
NastCheckError::RequiresFinalClass { .. } => todo!(),
NastCheckError::AbstractBody(_) => todo!(),
NastCheckError::InterfaceWithMemberVariable(_) => todo!(),
NastCheckError::InterfaceWithStaticMemberVariable(_) => todo!(),
NastCheckError::IllegalFunctionName { .. } => todo!(),
NastCheckError::EntrypointArguments(_) => todo!(),
NastCheckError::EntrypointGenerics(_) => todo!(),
NastCheckError::VariadicMemoize(_) => todo!(),
NastCheckError::AbstractMethodMemoize(_) => todo!(),
NastCheckError::InstancePropertyInAbstractFinalClass(_) => todo!(),
NastCheckError::InoutParamsSpecial(_) => todo!(),
NastCheckError::InoutParamsMemoize { .. } => todo!(),
NastCheckError::InoutInTransformedPseudofunction { .. } => todo!(),
NastCheckError::ReadingFromAppend(_) => todo!(),
NastCheckError::ListRvalue(_) => todo!(),
NastCheckError::IllegalDestructor(_) => todo!(),
NastCheckError::IllegalContext { .. } => todo!(),
NastCheckError::CaseFallthrough { .. } => todo!(),
NastCheckError::DefaultFallthrough(_) => todo!(),
NastCheckError::PhpLambdaDisallowed(_) => todo!(),
NastCheckError::InternalMethodWithInvalidVisibility { .. } => todo!(),
NastCheckError::PrivateAndFinal(_) => todo!(),
NastCheckError::InternalMemberInsidePublicTrait { .. } => todo!(),
NastCheckError::AttributeConflictingMemoize { .. } => todo!(),
NastCheckError::SoftInternalWithoutInternal(_) => todo!(),
NastCheckError::WrongExpressionKindBuiltinAttribute { .. } => todo!(),
NastCheckError::AttributeTooManyArguments { .. } => todo!(),
NastCheckError::AttributeTooFewArguments { .. } => todo!(),
NastCheckError::AttributeNotExactNumberOfArgs { .. } => todo!(),
NastCheckError::AttributeParamType { .. } => todo!(),
NastCheckError::AttributeNoAutoDynamic(_) => todo!(),
NastCheckError::GenericAtRuntime { .. } => todo!(),
NastCheckError::GenericsNotAllowed(_) => todo!(),
NastCheckError::LocalVariableModifiedAndUsed { .. } => todo!(),
NastCheckError::LocalVariableModifiedTwice { .. } => todo!(),
NastCheckError::AssignDuringCase(_) => todo!(),
NastCheckError::ReadBeforeWrite { .. } => todo!(),
NastCheckError::LateinitWithDefault(_) => todo!(),
NastCheckError::MissingAssign(_) => todo!(),
}
}
fn emit_fatal_experimental_feature_error<'arena>(
_alloc: &'arena bumpalo::Bump,
err: &ExperimentalFeature,
) -> Result<Unit<'arena>, Error> {
match err {
ExperimentalFeature::LikeType(_) => todo!(),
ExperimentalFeature::Supportdyn(_) => todo!(),
ExperimentalFeature::ConstAttr(_) => todo!(),
ExperimentalFeature::ConstStaticProp(_) => todo!(),
ExperimentalFeature::IFCInferFlows(_) => todo!(),
}
}
fn emit_fatal_parsing_error<'arena>(
_alloc: &'arena bumpalo::Bump,
err: &ParsingError,
) -> Result<Unit<'arena>, Error> {
match err {
ParsingError::FixmeFormat(_) => todo!(),
ParsingError::HhIgnoreComment(_) => todo!(),
ParsingError::ParsingError { .. } => todo!(),
ParsingError::XhpParsingError { .. } => todo!(),
ParsingError::PackageConfigError { .. } => todo!(),
}
}
fn emit_fatal<'arena>(
alloc: &'arena bumpalo::Bump,
fatal_op: FatalOp,
pos: Pos,
msg: impl AsRef<str> + 'arena,
) -> Result<Unit<'arena>, Error> {
emit_unit::emit_fatal_unit(alloc, fatal_op, pos, msg)
}
fn create_emitter<'arena, 'decl>(
native_env: &NativeEnv,
decl_provider: Option<Arc<dyn DeclProvider<'decl> + 'decl>>,
alloc: &'arena bumpalo::Bump,
) -> Emitter<'arena, 'decl> {
Emitter::new(
NativeEnv::to_options(native_env),
native_env.flags.is_systemlib,
native_env.flags.for_debugger_eval,
alloc,
decl_provider,
native_env.filepath.clone(),
)
}
fn create_parser_options(opts: &Options, type_directed: bool) -> ParserOptions {
ParserOptions {
po_codegen: true,
po_disallow_silence: false,
tco_no_parser_readonly_check: type_directed,
..opts.hhvm.parser_options.clone()
}
}
#[derive(Error, Debug)]
#[error("{0}: {1}")]
pub(crate) struct ParseError(Pos, String, FatalOp);
fn parse_file(
opts: &Options,
source_text: SourceText<'_>,
elaborate_namespaces: bool,
namespace_env: Arc<NamespaceEnv>,
is_systemlib: bool,
for_debugger_eval: bool,
type_directed: bool,
profile: &mut Profile,
) -> Result<ast::Program, ParseError> {
let aast_env = AastEnv {
codegen: true,
php5_compat_mode: !opts.hhbc.uvs,
is_systemlib,
for_debugger_eval,
elaborate_namespaces,
parser_options: create_parser_options(opts, type_directed),
..AastEnv::default()
};
let indexed_source_text = IndexedSourceText::new(source_text);
let ast_result = AastParser::from_text_with_namespace_env(
&aast_env,
namespace_env,
&indexed_source_text,
HashSet::default(),
);
match ast_result {
Err(AastError::Other(msg)) => Err(ParseError(Pos::NONE, msg, FatalOp::Parse)),
Err(AastError::NotAHackFile()) => Err(ParseError(
Pos::NONE,
"Not a Hack file".to_string(),
FatalOp::Parse,
)),
Err(AastError::ParserFatal(syntax_error, pos)) => Err(ParseError(
pos,
syntax_error.message.to_string(),
FatalOp::Parse,
)),
Ok(ast) => match ast {
ParserResult { syntax_errors, .. } if !syntax_errors.is_empty() => {
let syntax_error = syntax_errors
.iter()
.find(|e| e.error_type == ErrorType::RuntimeError)
.unwrap_or(&syntax_errors[0]);
let pos = indexed_source_text
.relative_pos(syntax_error.start_offset, syntax_error.end_offset);
Err(ParseError(
pos.into(),
syntax_error.message.to_string(),
match syntax_error.error_type {
ErrorType::ParseError => FatalOp::Parse,
ErrorType::RuntimeError => FatalOp::Runtime,
},
))
}
ParserResult {
lowerer_parsing_errors,
..
} if !lowerer_parsing_errors.is_empty() => {
let (pos, msg) = lowerer_parsing_errors.into_iter().next().unwrap();
Err(ParseError(pos, msg, FatalOp::Parse))
}
ParserResult {
errors,
aast,
profile: parser_profile,
..
} => {
profile.parser_profile = parser_profile;
let mut errors = errors.iter().filter(|e| {
e.code() != 2086
/* Naming.MethodNeedsVisibility */
&& e.code() != 2102
/* Naming.UnsupportedTraitUseAs */
&& e.code() != 2103
});
match errors.next() {
Some(e) => Err(ParseError(
e.pos().clone(),
e.msg().to_str_lossy().into_owned(),
FatalOp::Parse,
)),
None => Ok(aast),
}
}
},
}
}
pub fn expr_to_string_lossy(flags: &EnvFlags, expr: &ast::Expr) -> String {
use print_expr::Context;
let opts = Options::default();
let alloc = bumpalo::Bump::new();
let emitter = Emitter::new(
opts,
flags.is_systemlib,
flags.for_debugger_eval,
&alloc,
None,
RelativePath::make(Prefix::Dummy, Default::default()),
);
let ctx = Context::new(&emitter);
print_expr::expr_to_string_lossy(ctx, expr)
} |
Rust | hhvm/hphp/hack/src/hackc/compile/dump_expr_tree.rs | //
// Copyright (c) Facebook, Inc. and its affiliates.
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::fs;
// use crate::compile_rust as compile;
use std::sync::Arc;
use options::Options;
use oxidized::aast;
use oxidized::aast_visitor::AstParams;
use oxidized::aast_visitor::Node;
use oxidized::aast_visitor::Visitor;
use oxidized::ast;
use oxidized::namespace_env::Env as NamespaceEnv;
use oxidized::pos::Pos;
use parser_core_types::source_text::SourceText;
use relative_path::RelativePath;
use crate::EnvFlags;
use crate::ParseError;
use crate::Profile;
struct ExprTreeLiteralExtractor {
literals: Vec<(Pos, ast::ExpressionTree)>,
}
impl<'ast> Visitor<'ast> for ExprTreeLiteralExtractor {
type Params = AstParams<(), ()>;
fn object(&mut self) -> &mut dyn Visitor<'ast, Params = Self::Params> {
self
}
fn visit_expr(&mut self, env: &mut (), e: &ast::Expr) -> Result<(), ()> {
use aast::Expr_;
match &e.2 {
Expr_::ExpressionTree(et) => {
self.literals.push((e.1.clone(), (**et).clone()));
}
_ => e.recurse(env, self)?,
}
Ok(())
}
}
/// Extract the expression tree literals in `program` along with their
/// positions.
///
/// Given the code:
///
/// ````
/// function foo(): void {
/// $c = Code`bar()`;
/// }
/// ```
///
/// We want the `` Code`bar()` `` part.
fn find_et_literals(program: ast::Program) -> Vec<(Pos, ast::ExpressionTree)> {
let mut visitor = ExprTreeLiteralExtractor { literals: vec![] };
for def in program {
visitor
.visit_def(&mut (), &def)
.expect("Failed to extract expression tree literals");
}
visitor.literals
}
fn sort_by_start_pos<T>(items: &mut [(Pos, T)]) {
items.sort_by(|(p1, _), (p2, _)| p1.start_offset().cmp(&p2.start_offset()));
}
/// The source code of `program` with expression tree literals
/// replaced with their desugared form.
fn desugar_and_replace_et_literals(flags: &EnvFlags, program: ast::Program, src: &str) -> String {
let mut literals = find_et_literals(program);
sort_by_start_pos(&mut literals);
// Start from the last literal in the source code, so earlier
// positions stay valid after string replacements.
literals.reverse();
let mut src = src.to_string();
for (pos, literal) in literals {
let desugared_literal_src = crate::expr_to_string_lossy(flags, &literal.runtime_expr);
let (pos_start, pos_end) = pos.info_raw();
src.replace_range(pos_start..pos_end, &desugared_literal_src);
}
src
}
/// Parse the file in `env`, desugar expression tree literals, and
/// print the source code as if the user manually wrote the desugared
/// syntax.
pub fn desugar_and_print(filepath: RelativePath, flags: &EnvFlags) {
let type_directed = false;
let opts = Options::default();
let content = fs::read(filepath.path()).unwrap(); // consider: also show prefix?
let source_text = SourceText::make(Arc::new(filepath), &content);
let ns = Arc::new(NamespaceEnv::empty(
opts.hhvm.aliased_namespaces_cloned().collect(),
true,
opts.hhvm.parser_options.po_disable_xhp_element_mangling,
));
match crate::parse_file(
&opts,
source_text,
false,
ns,
flags.is_systemlib,
false, // for_debugger_eval
type_directed,
&mut Profile::default(),
) {
Err(ParseError(_, msg, _)) => panic!("Parsing failed: {}", msg),
Ok(ast) => {
let old_src = String::from_utf8_lossy(&content);
let new_src = desugar_and_replace_et_literals(flags, ast, &old_src);
print!("{}", new_src);
}
}
} |
Rust | hhvm/hphp/hack/src/hackc/compile/options.rs | // Copyright (c) 2019; Facebook; Inc.
// All rights reserved.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use bstr::BStr;
use bstr::BString;
use hhbc_string_utils as string_utils;
pub use oxidized::parser_options::ParserOptions;
use serde::Deserialize;
use serde::Serialize;
#[derive(Debug, Clone, PartialEq)]
pub struct CompilerFlags {
pub constant_folding: bool,
pub optimize_null_checks: bool,
pub relabel: bool,
}
impl Default for CompilerFlags {
fn default() -> Self {
Self {
constant_folding: true,
optimize_null_checks: false,
relabel: true,
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Hhvm {
pub include_roots: BTreeMap<BString, BString>,
pub renamable_functions: BTreeSet<BString>,
pub non_interceptable_functions: BTreeSet<BString>,
pub parser_options: ParserOptions,
pub jit_enable_rename_function: JitEnableRenameFunction,
}
impl Hhvm {
pub fn aliased_namespaces_cloned(&self) -> impl Iterator<Item = (String, String)> + '_ {
self.parser_options.po_auto_namespace_map.iter().cloned()
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub enum JitEnableRenameFunction {
#[default]
Disable,
Enable,
RestrictedEnable,
}
#[derive(Clone, PartialEq, Debug)]
pub struct Options {
pub compiler_flags: CompilerFlags,
pub hhvm: Hhvm,
pub hhbc: HhbcFlags,
pub max_array_elem_size_on_the_stack: usize,
}
impl Options {
pub fn log_extern_compiler_perf(&self) -> bool {
self.hhbc.log_extern_compiler_perf
}
pub fn function_is_renamable(&self, func: &BStr) -> bool {
let stripped_func = string_utils::strip_ns_bstr(func);
match self.hhvm.jit_enable_rename_function {
JitEnableRenameFunction::Enable => true,
JitEnableRenameFunction::RestrictedEnable => {
self.hhvm.renamable_functions.contains(stripped_func)
}
JitEnableRenameFunction::Disable => false,
}
}
pub fn function_is_interceptable(&self, func: &BStr) -> bool {
let stripped_func = string_utils::strip_ns_bstr(func);
!self
.hhvm
.non_interceptable_functions
.contains(stripped_func)
}
}
impl Default for Options {
fn default() -> Options {
Options {
max_array_elem_size_on_the_stack: 64,
compiler_flags: CompilerFlags::default(),
hhvm: Hhvm::default(),
hhbc: HhbcFlags::default(),
}
}
}
impl Options {
pub fn array_provenance(&self) -> bool {
self.hhbc.array_provenance
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct HhbcFlags {
/// PHP7 left-to-right assignment semantics
pub ltr_assign: bool,
/// PHP7 Uniform Variable Syntax
pub uvs: bool,
pub log_extern_compiler_perf: bool,
pub enable_intrinsics_extension: bool,
pub emit_cls_meth_pointers: bool,
pub emit_meth_caller_func_pointers: bool,
pub array_provenance: bool,
pub fold_lazy_class_keys: bool,
pub readonly_nonlocal_infer: bool,
pub optimize_reified_param_checks: bool,
pub stress_shallow_decl_deps: bool,
pub stress_folded_decl_deps: bool,
}
impl Default for HhbcFlags {
fn default() -> Self {
Self {
ltr_assign: false,
uvs: false,
log_extern_compiler_perf: false,
enable_intrinsics_extension: false,
emit_cls_meth_pointers: true,
emit_meth_caller_func_pointers: true,
array_provenance: false,
fold_lazy_class_keys: true,
readonly_nonlocal_infer: false,
optimize_reified_param_checks: false,
stress_shallow_decl_deps: false,
stress_folded_decl_deps: false,
}
}
} |
Rust | hhvm/hphp/hack/src/hackc/compile/rewrite_program.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
#![feature(box_patterns)]
use std::path::PathBuf;
use std::sync::Arc;
use env::emitter::Emitter;
use error::Error;
use error::Result;
use hack_macros::hack_expr;
use hack_macros::hack_stmt;
use hhbc::decl_vars;
use oxidized::ast;
use oxidized::ast::Def;
use oxidized::ast::Expr;
use oxidized::ast::Expr_;
use oxidized::ast::FunDef;
use oxidized::ast::FunKind;
use oxidized::ast::Fun_;
use oxidized::ast::FuncBody;
use oxidized::ast::Id;
use oxidized::ast::Pos;
use oxidized::ast::Stmt;
use oxidized::ast::Stmt_;
use oxidized::ast::TypeHint;
use oxidized::ast::UserAttribute;
use oxidized::file_info::Mode;
use oxidized::local_id;
use oxidized::namespace_env;
use relative_path::Prefix;
use relative_path::RelativePath;
use rewrite_xml::rewrite_xml;
fn debugger_eval_should_modify(tast: &[ast::Def]) -> Result<bool> {
/*
The AST currently always starts with a Markup statement, so a
length of 2 means there was 1 user def (statement, function,
etc.); we assert that the first thing is a Markup statement, and
we only want to modify if there was exactly one user def (both 0
user defs and > 1 user def are valid situations where we pass the
program through unmodififed)
*/
if tast
.first()
.and_then(|x| x.as_stmt())
.map_or(true, |x| !x.1.is_markup())
{
return Err(Error::unrecoverable(
"Lowered AST did not start with a Markup statement",
));
}
if tast.len() != 2 {
Ok(false)
} else {
Ok(tast[1].as_stmt().map_or(false, |x| x.1.is_expr()))
}
}
pub fn rewrite_program<'p, 'arena, 'emitter, 'decl>(
emitter: &'emitter mut Emitter<'arena, 'decl>,
prog: &'p mut ast::Program,
namespace_env: Arc<namespace_env::Env>,
) -> Result<()> {
let for_debugger_eval =
emitter.for_debugger_eval && debugger_eval_should_modify(prog.as_slice())?;
if !emitter.for_debugger_eval {
let contains_toplevel_code = prog.iter().find_map(|d| {
if let Some(ast::Stmt(pos, s_)) = d.as_stmt() {
if s_.is_markup() { None } else { Some(pos) }
} else {
None
}
});
if let Some(pos) = contains_toplevel_code {
return Err(Error::fatal_parse(pos, "Found top-level code"));
}
}
if emitter.options().compiler_flags.constant_folding {
constant_folder::fold_program(prog, emitter)
.map_err(|e| Error::unrecoverable(format!("{}", e)))?;
}
if emitter.for_debugger_eval {
extract_debugger_main(&namespace_env, &mut prog.0).map_err(Error::unrecoverable)?;
}
// TODO: wind through flags.disable_toplevel_elaboration?
// This `flatten_ns` is not currently needed because unless
// `--disable-toplevel-elaboration` is set, we already do this while
// parsing. We may want to move that functionality into elab and remove
// this flattening (and remove it from the parser?)
if true {
prog.0 = flatten_ns(prog.0.drain(..));
}
closure_convert::convert_toplevel_prog(emitter, &mut prog.0, namespace_env)?;
emitter.for_debugger_eval = for_debugger_eval;
rewrite_xml(emitter, prog)?;
Ok(())
}
/// The function we emit for debugger takes all variables used in the block of
/// code as parameters to the function created and returns the updated version
/// of these variables as a vector, placing the result of executing this function
/// as the 0th index of this vector.
fn extract_debugger_main(
empty_namespace: &Arc<namespace_env::Env>,
all_defs: &mut Vec<Def>,
) -> std::result::Result<(), String> {
let (mut stmts, mut defs): (Vec<Def>, Vec<Def>) = all_defs.drain(..).partition(|x| x.is_stmt());
let mut vars = decl_vars::vars_from_ast(&[], &stmts, true)?
.into_iter()
.collect::<Vec<_>>();
// In order to find the return value of these sets of statements, we must
// search and obtain the "return statement".
// This basic pass looks at all the "return statements" and
// then replaces this stament with a variable set, so that we can later
// add this variable into our return result.
use oxidized::aast_visitor::NodeMut;
use oxidized::aast_visitor::VisitorMut;
struct Ctx {
return_val: local_id::LocalId,
}
struct Visitor {}
impl<'node> VisitorMut<'node> for Visitor {
type Params = oxidized::aast_visitor::AstParams<Ctx, Error>;
fn object(&mut self) -> &mut dyn VisitorMut<'node, Params = Self::Params> {
self
}
fn visit_stmt(&mut self, env: &mut Ctx, e: &'node mut ast::Stmt) -> Result<()> {
match e {
Stmt(p, Stmt_::Return(box value @ Some(_))) => {
let value = value.take();
let return_val = &env.return_val;
let expr: Expr = value.unwrap();
*e = hack_stmt!(pos = p.clone(), "#{lvar(clone(return_val))} = #expr;");
Ok(())
}
_ => e.recurse(env, self),
}
}
fn visit_expr(&mut self, env: &mut Ctx, e: &'node mut ast::Expr) -> Result<()> {
match &e.2 {
// Do not recurse into closures
Expr_::Lfun(_) | Expr_::Efun(_) => Ok(()),
_ => e.recurse(env, self),
}
}
}
let mut ctx = Ctx {
return_val: local_id::make_unscoped("$__debugger$return_val"),
};
for stmt in &mut stmts {
oxidized::aast_visitor::visit_mut(&mut Visitor {}, &mut ctx, stmt).unwrap();
}
let return_val = ctx.return_val;
let mut stmts = stmts
.into_iter()
.filter_map(|x| x.as_stmt_into())
.collect::<Vec<_>>();
if defs.is_empty() && stmts.len() == 2 && stmts[0].1.is_markup() && stmts[1].1.is_expr() {
let Stmt(p, s) = stmts.pop().unwrap();
let e = s.as_expr_into().unwrap();
stmts.push(hack_stmt!(pos = p, "#{lvar(clone(return_val))} = #e;"));
}
match stmts.last_mut() {
Some(Stmt(_, Stmt_::Awaitall(box (_, block)))) => match block.last_mut() {
Some(s) => match s {
Stmt(_, Stmt_::Expr(box Expr(_, p, e))) => {
let e_inner = Expr((), std::mem::take(p), std::mem::replace(e, Expr_::False));
*s = hack_stmt!("#{lvar(clone(return_val))} = #e_inner;");
}
_ => {}
},
_ => {}
},
_ => {}
}
let p = || Pos::NONE;
let mut unsets: ast::Block = vars
.iter()
.map(|name| {
let name = local_id::make_unscoped(name);
hack_stmt!("if (#{lvar(clone(name))} is __uninitSentinel) { unset(#{lvar(name)}); }")
})
.collect();
let sets: Vec<_> = vars
.iter()
.map(|name: &String| {
let name = local_id::make_unscoped(name);
hack_stmt!(
pos = p(),
r#"if (\__SystemLib\__debugger_is_uninit(#{lvar(clone(name))})) {
#{lvar(name)} = new __uninitSentinel();
}
"#
)
})
.collect();
vars.push("$__debugger$this".into());
vars.push("$__debugger_exn$output".into());
let (params, return_val_sets): (Vec<_>, Vec<_>) = vars
.iter()
.map(|var| {
let name = local_id::make_unscoped(var);
let param = closure_convert::make_fn_param(p(), &name, false, false);
let var = hack_expr!(pos = p(), r#"#{lvar(name)}"#);
(param, var)
})
.unzip();
let exnvar = local_id::make_unscoped("$__debugger_exn$output");
unsets.push(hack_stmt!("#{lvar(clone(return_val))} = null;"));
let catch = hack_stmt!(
pos = p(),
r#"
try {
#{stmts*};
} catch (Throwable #{lvar(exnvar)}) {
/* no-op */
} finally {
#{sets*};
return vec[#{lvar(return_val)}, #{return_val_sets*}];
}
"#
);
unsets.push(catch);
let body = unsets;
let pos = Pos::from_line_cols_offset(
Arc::new(RelativePath::make(Prefix::Dummy, PathBuf::from(""))),
1,
0..0,
0,
);
let f = Fun_ {
span: pos,
annotation: (),
readonly_this: None, // TODO(readonly): readonly_this in closure_convert
readonly_ret: None, // TODO(readonly): readonly_ret in closure_convert
ret: TypeHint((), None),
params,
ctxs: None, // TODO(T70095684)
unsafe_ctxs: None, // TODO(T70095684)
body: FuncBody { fb_ast: body },
fun_kind: FunKind::FAsync,
user_attributes: ast::UserAttributes(vec![UserAttribute {
name: Id(Pos::NONE, "__DebuggerMain".into()),
params: vec![],
}]),
external: false,
doc_comment: None,
};
let fd = FunDef {
namespace: Arc::clone(empty_namespace),
file_attributes: vec![],
mode: Mode::Mstrict,
name: Id(Pos::NONE, "include".into()),
fun: f,
// TODO(T116039119): Populate value with presence of internal attribute
internal: false,
module: None,
tparams: vec![],
where_constraints: vec![],
};
let mut new_defs = vec![Def::mk_fun(fd)];
new_defs.append(&mut defs);
*all_defs = new_defs;
Ok(())
}
fn flatten_ns(defs: impl Iterator<Item = Def> + ExactSizeIterator) -> Vec<Def> {
fn helper(out: &mut Vec<Def>, defs: impl Iterator<Item = Def> + ExactSizeIterator) {
out.reserve(defs.len());
for def in defs {
match def {
Def::Namespace(ns) => {
helper(out, ns.1.into_iter());
}
_ => out.push(def),
}
}
}
let mut out = Vec::with_capacity(defs.len());
helper(&mut out, defs);
out
} |
Rust | hhvm/hphp/hack/src/hackc/compile/rewrite_xml.rs | use env::emitter::Emitter;
use error::Error;
use error::Result;
use naming_special_names_rust::pseudo_consts;
use oxidized::aast_visitor::visit_mut;
use oxidized::aast_visitor::AstParams;
use oxidized::aast_visitor::NodeMut;
use oxidized::aast_visitor::VisitorMut;
use oxidized::ast;
use oxidized::ast_defs;
use oxidized::pos::Pos;
struct RewriteXmlVisitor<'emitter, 'arena, 'decl> {
phantom: std::marker::PhantomData<(&'emitter &'arena (), &'emitter &'decl ())>,
}
struct Ctx<'emitter, 'arena, 'decl> {
emitter: &'emitter mut Emitter<'arena, 'decl>,
}
impl<'ast, 'arena, 'emitter, 'decl> VisitorMut<'ast>
for RewriteXmlVisitor<'emitter, 'arena, 'decl>
{
type Params = AstParams<Ctx<'emitter, 'arena, 'decl>, Error>;
fn object(&mut self) -> &mut dyn VisitorMut<'ast, Params = Self::Params> {
self
}
fn visit_expr(
&mut self,
c: &mut Ctx<'emitter, 'arena, 'decl>,
e: &'ast mut ast::Expr,
) -> Result<()> {
let ast::Expr(_, pos, expr) = e;
let emitter = &mut c.emitter;
if let ast::Expr_::Xml(cs) = expr {
*e = rewrite_xml_(emitter, pos, cs.as_ref().clone())?;
}
e.recurse(c, self.object())?;
Ok(())
}
}
pub fn rewrite_xml<'p, 'arena, 'emitter, 'decl>(
emitter: &'emitter mut Emitter<'arena, 'decl>,
prog: &'p mut ast::Program,
) -> Result<()> {
let mut xml_visitor = RewriteXmlVisitor {
phantom: std::marker::PhantomData,
};
let mut c: Ctx<'emitter, 'arena, 'decl> = Ctx { emitter };
visit_mut(&mut xml_visitor, &mut c, prog)
}
fn rewrite_xml_<'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
pos: &Pos,
(id, attributes, children): (ast::Sid, Vec<ast::XhpAttribute>, Vec<ast::Expr>),
) -> Result<ast::Expr> {
use ast::ClassId;
use ast::ClassId_;
use ast::Expr;
use ast::Expr_;
use ast::XhpAttribute;
use ast_defs::Id;
use ast_defs::ShapeFieldName;
let (_, attributes) =
attributes
.into_iter()
.fold((0, vec![]), |(mut spread_id, mut attrs), attr| {
match attr {
XhpAttribute::XhpSimple(xhp_simple) => {
let (pos, name) = xhp_simple.name;
attrs.push((
ShapeFieldName::SFlitStr((pos, name.into())),
xhp_simple.expr,
));
}
XhpAttribute::XhpSpread(expr) => {
attrs.push((
ShapeFieldName::SFlitStr((
expr.1.clone(),
format!("...${}", spread_id).into(),
)),
expr,
));
spread_id += 1;
}
}
(spread_id, attrs)
});
let attribute_map = Expr((), pos.clone(), Expr_::mk_shape(attributes));
let children_vec = Expr((), pos.clone(), Expr_::mk_varray(None, children));
let filename = Expr(
(),
pos.clone(),
Expr_::mk_id(Id(pos.clone(), pseudo_consts::G__FILE__.into())),
);
let line = Expr(
(),
pos.clone(),
Expr_::mk_id(Id(pos.clone(), pseudo_consts::G__LINE__.into())),
);
let renamed_id = hhbc::ClassName::from_ast_name_and_mangle(e.alloc, &id.1);
let cid = ClassId(
(),
pos.clone(),
ClassId_::CI(Id(id.0.clone(), renamed_id.unsafe_as_str().into())),
);
e.add_class_ref(renamed_id);
Ok(Expr(
(),
pos.clone(),
Expr_::New(Box::new((
cid,
vec![],
vec![attribute_map, children_vec, filename, line],
None,
(),
))),
))
} |
TOML | hhvm/hphp/hack/src/hackc/compile/cargo/closure_convert/Cargo.toml | # @generated by autocargo
[package]
name = "closure_convert"
version = "0.0.0"
edition = "2021"
[lib]
path = "../../closure_convert.rs"
[dependencies]
bumpalo = { version = "3.11.1", features = ["collections"] }
env = { version = "0.0.0", path = "../../../emitter/cargo/env" }
error = { version = "0.0.0", path = "../../../error/cargo/error" }
global_state = { version = "0.0.0", path = "../../../emitter/cargo/global_state" }
hack_macros = { version = "0.0.0", path = "../../../../utils/hack_macros/cargo/hack_macros" }
hash = { version = "0.0.0", path = "../../../../utils/hash" }
hhbc = { version = "0.0.0", path = "../../../hhbc/cargo/hhbc" }
hhbc_string_utils = { version = "0.0.0", path = "../../../utils/cargo/hhbc_string_utils" }
itertools = "0.10.3"
naming_special_names_rust = { version = "0.0.0", path = "../../../../naming" }
options = { version = "0.0.0", path = "../options" }
oxidized = { version = "0.0.0", path = "../../../../oxidized" }
stack_limit = { version = "0.0.0", path = "../../../../utils/stack_limit" }
unique_id_builder = { version = "0.0.0", path = "../../../utils/cargo/unique_id_builder" } |
TOML | hhvm/hphp/hack/src/hackc/compile/cargo/compile/Cargo.toml | # @generated by autocargo
[package]
name = "compile"
version = "0.0.0"
edition = "2021"
[lib]
path = "../../compile.rs"
[dependencies]
aast_parser = { version = "0.0.0", path = "../../../../parser/cargo/aast_parser" }
anyhow = "1.0.71"
bc_to_ir = { version = "0.0.0", path = "../../../ir/conversions/bc_to_ir" }
bstr = { version = "1.4.0", features = ["serde", "std", "unicode"] }
bumpalo = { version = "3.11.1", features = ["collections"] }
bytecode_printer = { version = "0.0.0", path = "../../../bytecode_printer" }
clap = { version = "4.3.5", features = ["derive", "env", "string", "unicode", "wrap_help"] }
decl_provider = { version = "0.0.0", path = "../../../decl_provider" }
elab = { version = "0.0.0", path = "../../../../elab" }
emit_unit = { version = "0.0.0", path = "../../../emitter/cargo/emit_unit" }
env = { version = "0.0.0", path = "../../../emitter/cargo/env" }
error = { version = "0.0.0", path = "../../../error/cargo/error" }
hhbc = { version = "0.0.0", path = "../../../hhbc/cargo/hhbc" }
ir = { version = "0.0.0", path = "../../../ir" }
ir_to_bc = { version = "0.0.0", path = "../../../ir/conversions/ir_to_bc" }
options = { version = "0.0.0", path = "../options" }
oxidized = { version = "0.0.0", path = "../../../../oxidized" }
parser_core_types = { version = "0.0.0", path = "../../../../parser/cargo/core_types" }
print_expr = { version = "0.0.0", path = "../../../print_expr" }
profile_rust = { version = "0.0.0", path = "../../../../utils/perf/cargo/profile" }
relative_path = { version = "0.0.0", path = "../../../../utils/rust/relative_path" }
rewrite_program = { version = "0.0.0", path = "../rewrite_program" }
serde = { version = "1.0.176", features = ["derive", "rc"] }
stack_limit = { version = "0.0.0", path = "../../../../utils/stack_limit" }
thiserror = "1.0.43"
types = { version = "0.0.0", path = "../../../types/cargo/types" } |
TOML | hhvm/hphp/hack/src/hackc/compile/cargo/options/Cargo.toml | # @generated by autocargo
[package]
name = "options"
version = "0.0.0"
edition = "2021"
[lib]
path = "../../options.rs"
[dependencies]
bstr = { version = "1.4.0", features = ["serde", "std", "unicode"] }
hhbc_string_utils = { version = "0.0.0", path = "../../../utils/cargo/hhbc_string_utils" }
oxidized = { version = "0.0.0", path = "../../../../oxidized" }
serde = { version = "1.0.176", features = ["derive", "rc"] } |
TOML | hhvm/hphp/hack/src/hackc/compile/cargo/rewrite_program/Cargo.toml | # @generated by autocargo
[package]
name = "rewrite_program"
version = "0.0.0"
edition = "2021"
[lib]
path = "../../rewrite_program.rs"
[dependencies]
closure_convert = { version = "0.0.0", path = "../closure_convert" }
constant_folder = { version = "0.0.0", path = "../../../emitter/cargo/constant_folder" }
env = { version = "0.0.0", path = "../../../emitter/cargo/env" }
error = { version = "0.0.0", path = "../../../error/cargo/error" }
hack_macros = { version = "0.0.0", path = "../../../../utils/hack_macros/cargo/hack_macros" }
hhbc = { version = "0.0.0", path = "../../../hhbc/cargo/hhbc" }
oxidized = { version = "0.0.0", path = "../../../../oxidized" }
relative_path = { version = "0.0.0", path = "../../../../utils/rust/relative_path" }
rewrite_xml = { version = "0.0.0", path = "../rewrite_xml" } |
TOML | hhvm/hphp/hack/src/hackc/compile/cargo/rewrite_xml/Cargo.toml | # @generated by autocargo
[package]
name = "rewrite_xml"
version = "0.0.0"
edition = "2021"
[lib]
path = "../../rewrite_xml.rs"
[dependencies]
env = { version = "0.0.0", path = "../../../emitter/cargo/env" }
error = { version = "0.0.0", path = "../../../error/cargo/error" }
hhbc = { version = "0.0.0", path = "../../../hhbc/cargo/hhbc" }
naming_special_names_rust = { version = "0.0.0", path = "../../../../naming" }
oxidized = { version = "0.0.0", path = "../../../../oxidized" } |
TOML | hhvm/hphp/hack/src/hackc/decl_provider/Cargo.toml | # @generated by autocargo
[package]
name = "decl_provider"
version = "0.0.0"
edition = "2021"
[lib]
path = "decl_provider.rs"
[dependencies]
arena_deserializer = { version = "0.0.0", path = "../../utils/arena_deserializer" }
bincode = "1.3.3"
bumpalo = { version = "3.11.1", features = ["collections"] }
direct_decl_parser = { version = "0.0.0", path = "../../parser/api/cargo/direct_decl_parser" }
hash = { version = "0.0.0", path = "../../utils/hash" }
oxidized = { version = "0.0.0", path = "../../oxidized" }
oxidized_by_ref = { version = "0.0.0", path = "../../oxidized_by_ref" }
parser_core_types = { version = "0.0.0", path = "../../parser/cargo/core_types" }
sha1 = "0.10.5"
thiserror = "1.0.43" |
Rust | hhvm/hphp/hack/src/hackc/decl_provider/decl_provider.rs | // Copyright (c) 2019, Facebook, Inc.
// All rights reserved.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
mod memo_provider;
mod self_provider;
use std::io::BufReader;
use std::io::BufWriter;
use std::io::Read;
use std::io::Write;
use std::path::PathBuf;
use arena_deserializer::serde::Deserialize;
use arena_deserializer::ArenaDeserializer;
use bincode::Options;
use direct_decl_parser::Decls;
use direct_decl_parser::ParsedFile;
use hash::IndexMap;
pub use memo_provider::MemoProvider;
use oxidized_by_ref::shallow_decl_defs::ClassDecl;
pub use oxidized_by_ref::shallow_decl_defs::ConstDecl;
use oxidized_by_ref::shallow_decl_defs::Decl;
pub use oxidized_by_ref::shallow_decl_defs::FunDecl;
pub use oxidized_by_ref::shallow_decl_defs::ModuleDecl;
pub use oxidized_by_ref::shallow_decl_defs::TypedefDecl;
pub use self_provider::SelfProvider;
use sha1::Digest;
use sha1::Sha1;
use thiserror::Error;
pub type Result<T, E = Error> = std::result::Result<T, E>;
#[derive(Debug, Error)]
pub enum Error {
#[error("Decl not found")]
NotFound,
#[error(transparent)]
Bincode(#[from] bincode::Error),
}
#[derive(Debug, Clone, Copy)]
pub enum TypeDecl<'a> {
Class(&'a ClassDecl<'a>),
Typedef(&'a TypedefDecl<'a>),
}
/// DeclProvider is an interface for requesting named decl data required
/// for bytecode compilation.
///
/// The provider is supplied by the client requesting a bytecode
/// compilation. This client may wish to cache the compiled bytecode and
/// will record the various symbols observed during compilation for the
/// purpose of generating a cache key.
///
/// Methods are provided for each distinct kind of name (starting with
/// types, for now).
///
/// A special depth parameter is supplied to the client indicating how many
/// levels of get requests were traversed to arrive at the current
/// request. It may be used in an implementation specified manner to improve
/// caching.
///
/// As an example consider these source files:
///
/// a.php:
///
/// <?hh
///
/// function foo(MyType $bar): void { ... }
///
/// b.php:
///
/// <?hh
///
/// type MyType = Bar<Biz, Buz>;
///
/// If while compiling `a.php` a request is made for `MyType` the depth
/// will be zero as the symbol is referenced directly from `a.php`. The
/// shallow decl returned will be for a type alias to a `Bar`.
///
/// Should the compiler now request `Bar` the depth should be one, as the
/// lookup was an indirect reference. Likewise `Biz` and `Buz` would be
/// requested with a depth of one.
///
/// Further traversal into the type of Bar should it too be a type alias
/// would be at a depth of two.
///
pub trait DeclProvider<'d>: std::fmt::Debug {
/// Get a decl for the given type name and depth.
/// * `symbol` - the name of the symbol being requested
/// * `depth` - a hint to the provider about the number of layers of decl
/// request traversed to arrive at this request
fn type_decl<'s>(&'s self, symbol: &str, depth: u64) -> Result<TypeDecl<'d>>;
fn func_decl<'s>(&'s self, symbol: &str) -> Result<&'d FunDecl<'d>>;
fn const_decl<'s>(&'s self, symbol: &str) -> Result<&'d ConstDecl<'d>>;
fn module_decl<'s>(&'s self, symbol: &str) -> Result<&'d ModuleDecl<'d>>;
}
/// Serialize decls into an opaque blob suffixed with a Sha1 content hash.
pub fn serialize_decls(decls: &Decls<'_>) -> Result<Vec<u8>, bincode::Error> {
let mut blob = Vec::new();
bincode::options()
.with_native_endian()
.serialize_into(&mut blob, decls)?;
let mut digest = Sha1::new();
digest.update(&blob);
blob.write_all(&digest.finalize())?;
Ok(blob)
}
/// Deserialize decls. Panic in cfg(debug) if the content hash is wrong.
pub fn deserialize_decls<'a>(
arena: &'a bumpalo::Bump,
data: &[u8],
) -> Result<Decls<'a>, bincode::Error> {
let (data, hash) = split_serialized_decls(data);
debug_assert!({
let mut digest = Sha1::new();
digest.update(data);
digest.finalize().to_vec() == hash
});
let op = bincode::options().with_native_endian();
let mut de = bincode::de::Deserializer::from_slice(data, op);
let de = arena_deserializer::ArenaDeserializer::new(arena, &mut de);
Decls::deserialize(de)
}
/// Separate the raw serialized decls from the content hash suffixed by serialize_decls().
/// Returns (data, content_hash).
fn split_serialized_decls(data: &[u8]) -> (&[u8], &[u8]) {
assert!(data.len() >= Sha1::output_size());
let split = data.len() - Sha1::output_size();
(&data[0..split], &data[split..])
}
/// Recover the content hash that was appended to serialized decls.
pub fn decls_content_hash(data: &[u8]) -> &[u8] {
split_serialized_decls(data).1
}
pub fn find_type_decl<'a>(decls: &Decls<'a>, needle: &str) -> Result<TypeDecl<'a>> {
decls
.types()
.find_map(|(name, decl)| match decl {
Decl::Class(c) if needle.eq_ignore_ascii_case(name) => Some(TypeDecl::Class(c)),
Decl::Typedef(c) if needle.eq_ignore_ascii_case(name) => Some(TypeDecl::Typedef(c)),
Decl::Class(_) | Decl::Typedef(_) => None,
Decl::Fun(_) | Decl::Const(_) | Decl::Module(_) => unreachable!(),
})
.ok_or(Error::NotFound)
}
pub fn find_func_decl<'a>(decls: &Decls<'a>, needle: &str) -> Result<&'a FunDecl<'a>> {
decls
.funs()
.find_map(|(name, decl)| {
if needle.eq_ignore_ascii_case(name) {
Some(decl)
} else {
None
}
})
.ok_or(Error::NotFound)
}
pub fn find_const_decl<'a>(decls: &Decls<'a>, needle: &str) -> Result<&'a ConstDecl<'a>> {
decls
.consts()
.find_map(|(name, decl)| if needle == name { Some(decl) } else { None })
.ok_or(Error::NotFound)
}
pub fn find_module_decl<'a>(decls: &Decls<'a>, needle: &str) -> Result<&'a ModuleDecl<'a>> {
decls
.modules()
.find_map(|(name, decl)| if needle == name { Some(decl) } else { None })
.ok_or(Error::NotFound)
}
pub fn serialize_batch_decls(
w: impl Write,
parsed_files: &IndexMap<PathBuf, ParsedFile<'_>>,
) -> Result<(), bincode::Error> {
let mut w = BufWriter::new(w);
bincode::options()
.with_native_endian()
.serialize_into(&mut w, &parsed_files)
}
pub fn deserialize_batch_decls<'a>(
r: impl Read,
arena: &'a bumpalo::Bump,
) -> Result<IndexMap<PathBuf, ParsedFile<'a>>, bincode::Error> {
let r = BufReader::new(r);
let mut de = bincode::de::Deserializer::with_reader(r, bincode::options().with_native_endian());
let de = ArenaDeserializer::new(arena, &mut de);
IndexMap::deserialize(de)
} |
Rust | hhvm/hphp/hack/src/hackc/decl_provider/memo_provider.rs | // Copyright (c) 2019, Facebook, Inc.
// All rights reserved.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::cell::RefCell;
use std::sync::Arc;
use hash::HashMap;
use crate::ConstDecl;
use crate::DeclProvider;
use crate::FunDecl;
use crate::ModuleDecl;
use crate::Result;
use crate::TypeDecl;
/// A DeclProvider that memoizes results of previous queries.
pub struct MemoProvider<'d> {
next: Arc<dyn DeclProvider<'d> + 'd>,
types: RefCell<HashMap<String, TypeDecl<'d>>>,
funcs: RefCell<HashMap<String, &'d FunDecl<'d>>>,
consts: RefCell<HashMap<String, &'d ConstDecl<'d>>>,
modules: RefCell<HashMap<String, &'d ModuleDecl<'d>>>,
}
impl<'d> MemoProvider<'d> {
pub fn new(next: Arc<dyn DeclProvider<'d> + 'd>) -> Self {
Self {
next,
types: Default::default(),
funcs: Default::default(),
consts: Default::default(),
modules: Default::default(),
}
}
fn fetch_or_insert<T: Copy>(
table: &RefCell<HashMap<String, T>>,
symbol: &str,
mut on_miss: impl FnMut() -> Result<T>,
) -> Result<T> {
use std::collections::hash_map::Entry::*;
match table.borrow_mut().entry(symbol.into()) {
Occupied(e) => Ok(*e.get()),
Vacant(e) => Ok(*e.insert(on_miss()?)),
}
}
}
impl<'d> DeclProvider<'d> for MemoProvider<'d> {
fn type_decl(&self, symbol: &str, depth: u64) -> Result<TypeDecl<'d>> {
Self::fetch_or_insert(&self.types, symbol, || self.next.type_decl(symbol, depth))
}
fn func_decl(&self, symbol: &str) -> Result<&'d FunDecl<'d>> {
Self::fetch_or_insert(&self.funcs, symbol, || self.next.func_decl(symbol))
}
fn const_decl(&self, symbol: &str) -> Result<&'d ConstDecl<'d>> {
Self::fetch_or_insert(&self.consts, symbol, || self.next.const_decl(symbol))
}
fn module_decl(&self, symbol: &str) -> Result<&'d ModuleDecl<'d>> {
Self::fetch_or_insert(&self.modules, symbol, || self.next.module_decl(symbol))
}
}
impl<'d> std::fmt::Debug for MemoProvider<'d> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.next.fmt(f)
}
} |
Rust | hhvm/hphp/hack/src/hackc/decl_provider/self_provider.rs | // Copyright (c) Meta Platforms, Inc. and affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::sync::Arc;
use direct_decl_parser::parse_decls_for_bytecode;
use direct_decl_parser::Decls;
use oxidized::decl_parser_options::DeclParserOptions;
use oxidized_by_ref::shallow_decl_defs::ConstDecl;
use oxidized_by_ref::shallow_decl_defs::FunDecl;
use oxidized_by_ref::shallow_decl_defs::ModuleDecl;
use parser_core_types::source_text::SourceText;
use crate::DeclProvider;
use crate::Result;
use crate::TypeDecl;
/// A decl provider that also provides decls found in the given file.
///
/// Checks the current file first for decls. If not found,
/// checks the provided decl provider for the decls next.
///
/// Useful when the file under compilation is not indexed by the HHVM autoloader
/// or similar circumstances.
pub struct SelfProvider<'d> {
fallback_decl_provider: Option<Arc<dyn DeclProvider<'d> + 'd>>,
decls: Decls<'d>,
}
impl<'d> SelfProvider<'d> {
pub fn new(
fallback_decl_provider: Option<Arc<dyn DeclProvider<'d> + 'd>>,
decl_opts: DeclParserOptions,
source_text: SourceText<'_>,
arena: &'d bumpalo::Bump,
) -> Self {
let parsed_file = parse_decls_for_bytecode(
&decl_opts,
source_text.file_path().clone(),
source_text.text(),
arena,
);
SelfProvider {
fallback_decl_provider,
decls: parsed_file.decls,
}
}
/// Currently, because decls are not on by default everywhere
/// only create a new SelfProvider when given a fallback provider,
/// which indicates that we want to compile with decls.
/// When decls are turned on everywhere by default and it is no longer optional
/// this can simply return a nonoption decl provider
pub fn wrap_existing_provider(
fallback_decl_provider: Option<Arc<dyn DeclProvider<'d> + 'd>>,
decl_opts: DeclParserOptions,
source_text: SourceText<'_>,
arena: &'d bumpalo::Bump,
) -> Option<Arc<dyn DeclProvider<'d> + 'd>> {
if fallback_decl_provider.is_none() {
None
} else {
Some(Arc::new(SelfProvider::new(
fallback_decl_provider,
decl_opts,
source_text,
arena,
)) as Arc<dyn DeclProvider<'d> + 'd>)
}
}
fn result_or_else<T>(
&self,
decl: Result<T>,
get_fallback_decl: impl Fn(&Arc<dyn DeclProvider<'d> + 'd>) -> Result<T>,
) -> Result<T> {
decl.or_else(|_| {
self.fallback_decl_provider
.as_ref()
.map_or(Err(crate::Error::NotFound), get_fallback_decl)
})
}
}
impl<'d> DeclProvider<'d> for SelfProvider<'d> {
fn type_decl(&self, symbol: &str, depth: u64) -> Result<TypeDecl<'d>> {
self.result_or_else(crate::find_type_decl(&self.decls, symbol), |provider| {
provider.type_decl(symbol, depth)
})
}
fn func_decl(&self, symbol: &str) -> Result<&'d FunDecl<'d>> {
self.result_or_else(crate::find_func_decl(&self.decls, symbol), |provider| {
provider.func_decl(symbol)
})
}
fn const_decl(&self, symbol: &str) -> Result<&'d ConstDecl<'d>> {
self.result_or_else(crate::find_const_decl(&self.decls, symbol), |provider| {
provider.const_decl(symbol)
})
}
fn module_decl(&self, symbol: &str) -> Result<&'d ModuleDecl<'d>> {
self.result_or_else(crate::find_module_decl(&self.decls, symbol), |provider| {
provider.module_decl(symbol)
})
}
}
impl<'d> std::fmt::Debug for SelfProvider<'d> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Some(p) = &self.fallback_decl_provider {
write!(f, "SelfProvider({:?})", p)
} else {
write!(f, "SelfProvider")
}
}
} |
Rust | hhvm/hphp/hack/src/hackc/emitter/adata_state.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use hash::HashMap;
use hhbc::Adata;
use hhbc::AdataId;
use hhbc::TypedValue;
#[derive(Debug, Default)]
pub struct AdataState<'a> {
shared: HashMap<TypedValue<'a>, AdataId<'a>>,
adata: Vec<Adata<'a>>,
}
impl<'a> AdataState<'a> {
pub fn push(&mut self, alloc: &'a bumpalo::Bump, value: TypedValue<'a>) -> AdataId<'a> {
push(alloc, &mut self.adata, value)
}
pub fn intern(&mut self, alloc: &'a bumpalo::Bump, tv: TypedValue<'a>) -> AdataId<'a> {
*self
.shared
.entry(tv)
.or_insert_with_key(|tv| push(alloc, &mut self.adata, tv.clone()))
}
pub fn take_adata(&mut self) -> Vec<Adata<'a>> {
self.shared = Default::default();
std::mem::take(&mut self.adata)
}
}
fn push<'a>(
alloc: &'a bumpalo::Bump,
adata: &mut Vec<Adata<'a>>,
value: TypedValue<'a>,
) -> AdataId<'a> {
let id = AdataId::from_raw_string(alloc, &format!("A_{}", adata.len()));
adata.push(Adata { id, value });
id
} |
Rust | hhvm/hphp/hack/src/hackc/emitter/ast_scope.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
pub mod ast_scope_item;
use std::borrow::Cow;
use hhbc::Coeffects;
use oxidized::ast;
use oxidized::ast_defs::FunKind;
use oxidized::ast_defs::Id;
use oxidized::pos::Pos;
pub use crate::ast_scope_item::Class;
pub use crate::ast_scope_item::Fun;
pub use crate::ast_scope_item::Lambda;
pub use crate::ast_scope_item::Method;
pub use crate::ast_scope_item::ScopeItem;
#[derive(Clone, Default, Debug, Eq, PartialEq)]
pub struct Scope<'a, 'arena> {
items: Vec<ScopeItem<'a, 'arena>>,
class_cache: Option<Class<'a>>,
}
impl<'a, 'arena> Scope<'a, 'arena> {
pub fn with_item(item: ScopeItem<'a, 'arena>) -> Self {
let mut scope = Self::default();
scope.push_item(item);
scope
}
pub fn push_item(&mut self, s: ScopeItem<'a, 'arena>) {
if let ScopeItem::Class(cd) = &s {
self.class_cache = Some(cd.clone());
}
self.items.push(s)
}
pub fn items(&self) -> &[ScopeItem<'a, 'arena>] {
&self.items
}
pub fn iter(&self) -> impl ExactSizeIterator<Item = &ScopeItem<'a, 'arena>> {
self.items.iter().rev()
}
pub fn iter_subscopes(&self) -> impl Iterator<Item = &[ScopeItem<'a, 'arena>]> {
(0..self.items.len()).rev().map(move |i| &self.items[..i])
}
pub fn top(&self) -> Option<&ScopeItem<'a, 'arena>> {
self.items.last()
}
pub fn get_class(&self) -> Option<&Class<'_>> {
self.class_cache.as_ref()
}
pub fn get_span(&self) -> Option<&Pos> {
self.top().map(ScopeItem::get_span)
}
pub fn get_span_or_none<'b>(&'b self) -> Cow<'b, Pos> {
if let Some(pos) = self.get_span() {
Cow::Borrowed(pos)
} else {
Cow::Owned(Pos::NONE)
}
}
pub fn get_tparams(&self) -> Vec<&ast::Tparam> {
let mut tparams = vec![];
let extend_shallowly = &mut |tps| {
for tparam in tps {
tparams.push(tparam);
}
};
for scope_item in self.iter() {
match scope_item {
ScopeItem::Class(cd) => {
extend_shallowly(cd.get_tparams());
}
ScopeItem::Function(fd) => {
extend_shallowly(fd.get_tparams());
}
ScopeItem::Method(md) => {
extend_shallowly(md.get_tparams());
}
_ => {}
}
}
tparams
}
pub fn get_fun_tparams(&self) -> &[ast::Tparam] {
for scope_item in self.iter() {
match scope_item {
ScopeItem::Class(_) => {
return &[];
}
ScopeItem::Function(fd) => {
return fd.get_tparams();
}
ScopeItem::Method(md) => {
return md.get_tparams();
}
_ => {}
}
}
&[]
}
pub fn get_class_tparams(&self) -> &[ast::Tparam] {
for scope_item in self.iter() {
if let ScopeItem::Class(cd) = scope_item {
return cd.get_tparams();
}
}
&[]
}
pub fn has_this(&self) -> bool {
if self.items.is_empty() {
/* Assume top level has this */
return true;
}
for scope_item in self.iter() {
match scope_item {
ScopeItem::Class(_) | ScopeItem::Function(_) => {
return false;
}
ScopeItem::Method(_) => {
return true;
}
_ => {}
}
}
false
}
pub fn is_in_async(&self) -> bool {
for scope_item in self.iter() {
match scope_item {
ScopeItem::Class(_) => {
return false;
}
ScopeItem::Method(m) => {
let fun_kind = m.get_fun_kind();
return fun_kind == FunKind::FAsync || fun_kind == FunKind::FAsyncGenerator;
}
ScopeItem::Function(f) => {
let fun_kind = f.get_fun_kind();
return fun_kind == FunKind::FAsync || fun_kind == FunKind::FAsyncGenerator;
}
_ => {}
}
}
false
}
pub fn is_toplevel(&self) -> bool {
self.items.is_empty()
}
pub fn is_in_static_method(&self) -> bool {
for scope_item in self.iter() {
match scope_item {
ScopeItem::Method(md) => {
return md.is_static();
}
ScopeItem::Lambda(_) => {}
_ => return false,
}
}
false
}
pub fn is_in_lambda(&self) -> bool {
self.items.last().map_or(false, ScopeItem::is_in_lambda)
}
pub fn coeffects_of_scope(&self, alloc: &'arena bumpalo::Bump) -> Coeffects<'arena> {
for scope_item in self.iter() {
match scope_item {
ScopeItem::Class(_) => {
return Coeffects::default();
}
ScopeItem::Method(m) => {
return Coeffects::from_ast(
alloc,
m.get_ctxs(),
m.get_params(),
m.get_tparams(),
self.get_class_tparams(),
);
}
ScopeItem::Function(f) => {
return Coeffects::from_ast(
alloc,
f.get_ctxs(),
f.get_params(),
f.get_tparams(),
vec![],
);
}
ScopeItem::Lambda(Lambda { coeffects, .. })
if !coeffects.get_static_coeffects().is_empty() =>
{
return coeffects.clone();
}
ScopeItem::Lambda(_) => {}
}
}
Coeffects::default()
}
pub fn has_function_attribute(&self, attr_name: impl AsRef<str>) -> bool {
let has = |ua: &[ast::UserAttribute]| ua.iter().any(|a| a.name.1 == attr_name.as_ref());
for scope_item in self.iter() {
match scope_item {
ScopeItem::Method(m) => {
return has(m.get_user_attributes());
}
ScopeItem::Function(f) => {
return has(f.get_user_attributes());
}
_ => {}
}
}
false
}
pub fn is_static(&self) -> bool {
for x in self.iter() {
match x {
ScopeItem::Function(_) => return true,
ScopeItem::Method(md) => return md.is_static(),
ScopeItem::Lambda(_) => {}
_ => return true,
}
}
true
}
// get captured variables when in closure scope
pub fn get_captured_vars(&self) -> Vec<String> {
// closure scope: lambda -> method -> class
match &self.items[..] {
[.., ScopeItem::Class(ast_cls), _, _] => ast_cls
.get_vars()
.iter()
.map(|var| {
let Id(_, id) = &var.id;
format!("${}", id)
})
.collect::<Vec<_>>(),
_ => panic!("closure scope should be lambda -> method -> class"),
}
}
pub fn is_in_debugger_eval_fun(&self) -> bool {
for x in self.iter() {
match x {
ScopeItem::Lambda(_) => {}
ScopeItem::Function(f) => return f.get_name().1 == "include",
_ => return false,
}
}
true
}
} |
Rust | hhvm/hphp/hack/src/hackc/emitter/ast_scope_item.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::rc::Rc;
use hhbc::Coeffects;
use oxidized::ast;
use oxidized::file_info;
use oxidized::pos::Pos;
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Lambda<'arena> {
pub is_long: bool,
pub is_async: bool,
pub coeffects: Coeffects<'arena>,
pub pos: Pos,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ScopeItem<'a, 'arena> {
Class(Class<'a>),
Function(Fun<'a>),
Method(Method<'a>),
Lambda(Lambda<'arena>),
}
impl<'a, 'arena> ScopeItem<'a, 'arena> {
pub fn get_span(&self) -> &Pos {
match self {
ScopeItem::Class(cd) => cd.get_span(),
ScopeItem::Function(fd) => fd.get_span(),
ScopeItem::Method(md) => md.get_span(),
ScopeItem::Lambda(lambda) => &lambda.pos,
}
}
pub fn is_in_lambda(&self) -> bool {
matches!(self, ScopeItem::Lambda(_))
}
pub fn is_in_long_lambda(&self) -> bool {
match self {
ScopeItem::Lambda(inner) => inner.is_long,
_ => false,
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Class<'a> {
Borrowed(&'a ast::Class_),
Counted(Rc<Class_>),
}
impl<'a> Class<'a> {
pub fn new_ref(ast: &'a ast::Class_) -> Self {
Self::Borrowed(ast)
}
pub fn new_rc(x: &ast::Class_) -> Self {
Self::Counted(Rc::new(Class_::new(x)))
}
pub fn get_tparams(&self) -> &[ast::Tparam] {
match self {
Self::Borrowed(x) => &x.tparams,
Self::Counted(x) => &x.tparams,
}
}
pub fn get_span(&self) -> &Pos {
match self {
Self::Borrowed(x) => &x.span,
Self::Counted(x) => &x.span,
}
}
pub fn get_name(&self) -> &ast::Id {
match self {
Self::Borrowed(x) => &x.name,
Self::Counted(x) => &x.name,
}
}
pub fn get_name_str(&self) -> &str {
&self.get_name().1
}
pub fn get_mode(&self) -> file_info::Mode {
match self {
Self::Borrowed(x) => x.mode,
Self::Counted(x) => x.mode,
}
}
pub fn get_kind(&self) -> ast::ClassishKind {
match self {
Self::Borrowed(x) => x.kind,
Self::Counted(x) => x.kind,
}
}
pub fn get_extends(&self) -> &[ast::Hint] {
match self {
Self::Borrowed(x) => &x.extends,
Self::Counted(x) => &x.extends,
}
}
pub fn get_vars(&self) -> &[ast::ClassVar] {
match self {
Self::Borrowed(x) => &x.vars,
Self::Counted(x) => &x.vars,
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Fun<'a> {
Borrowed(&'a ast::FunDef),
Counted(Rc<Fun_>),
}
impl<'a> Fun<'a> {
pub fn new_ref(ast: &'a ast::FunDef) -> Self {
Self::Borrowed(ast)
}
pub fn new_rc(x: &ast::FunDef) -> Self {
Self::Counted(Rc::new(Fun_::new(x)))
}
pub fn get_tparams(&self) -> &[ast::Tparam] {
match self {
Self::Borrowed(x) => &x.tparams,
Self::Counted(x) => &x.tparams,
}
}
pub(crate) fn get_user_attributes(&self) -> &[ast::UserAttribute] {
match self {
Self::Borrowed(x) => &x.fun.user_attributes,
Self::Counted(x) => &x.user_attributes,
}
}
pub fn get_ctxs(&self) -> Option<&ast::Contexts> {
match self {
Self::Borrowed(x) => x.fun.ctxs.as_ref(),
Self::Counted(x) => x.ctxs.as_ref(),
}
}
pub fn get_params(&self) -> &[ast::FunParam] {
match self {
Self::Borrowed(x) => &x.fun.params,
Self::Counted(x) => &x.params,
}
}
pub fn get_span(&self) -> &Pos {
match self {
Self::Borrowed(x) => &x.fun.span,
Self::Counted(x) => &x.span,
}
}
pub fn get_name(&self) -> &ast::Id {
match self {
Self::Borrowed(x) => &x.name,
Self::Counted(x) => &x.name,
}
}
pub fn get_name_str(&self) -> &str {
&self.get_name().1
}
pub fn get_mode(&self) -> file_info::Mode {
match self {
Self::Borrowed(x) => x.mode,
Self::Counted(x) => x.mode,
}
}
pub fn get_fun_kind(&self) -> ast::FunKind {
match self {
Self::Borrowed(x) => x.fun.fun_kind,
Self::Counted(x) => x.fun_kind,
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Method<'a> {
Borrowed(&'a ast::Method_),
Counted(Rc<Method_>),
}
impl<'a> Method<'a> {
pub fn new_ref(ast: &'a ast::Method_) -> Self {
Self::Borrowed(ast)
}
pub fn new_rc(x: &ast::Method_) -> Self {
Self::Counted(Rc::new(Method_::new(x)))
}
pub fn get_tparams(&self) -> &[ast::Tparam] {
match self {
Self::Borrowed(m) => &m.tparams,
Self::Counted(m) => &m.tparams,
}
}
pub fn is_static(&self) -> bool {
match self {
Self::Borrowed(m) => m.static_,
Self::Counted(m) => m.static_,
}
}
pub(crate) fn get_user_attributes(&self) -> &[ast::UserAttribute] {
match self {
Self::Borrowed(x) => &x.user_attributes,
Self::Counted(x) => &x.user_attributes,
}
}
pub fn get_ctxs(&self) -> Option<&ast::Contexts> {
match self {
Self::Borrowed(x) => x.ctxs.as_ref(),
Self::Counted(x) => x.ctxs.as_ref(),
}
}
pub fn get_params(&self) -> &[ast::FunParam] {
match self {
Self::Borrowed(x) => &x.params,
Self::Counted(x) => &x.params,
}
}
pub fn get_span(&self) -> &Pos {
match self {
Self::Borrowed(x) => &x.span,
Self::Counted(x) => &x.span,
}
}
pub fn get_name(&self) -> &ast::Id {
match self {
Self::Borrowed(x) => &x.name,
Self::Counted(x) => &x.name,
}
}
pub fn get_name_str(&self) -> &str {
&self.get_name().1
}
pub fn get_fun_kind(&self) -> ast::FunKind {
match self {
Self::Borrowed(x) => x.fun_kind,
Self::Counted(x) => x.fun_kind,
}
}
}
#[derive(Debug, Eq, PartialEq)]
pub struct Class_ {
name: ast::Id,
span: Pos,
tparams: Vec<ast::Tparam>,
vars: Vec<ast::ClassVar>,
mode: file_info::Mode,
kind: ast::ClassishKind,
extends: Vec<ast::Hint>,
}
impl Class_ {
fn new(c: &ast::Class_) -> Self {
Self {
name: c.name.clone(),
span: c.span.clone(),
tparams: c.tparams.clone(),
vars: c.vars.clone(),
mode: c.mode,
kind: c.kind.clone(),
extends: c.extends.clone(),
}
}
}
#[derive(Debug, Eq, PartialEq)]
pub struct Fun_ {
name: ast::Id,
span: Pos,
tparams: Vec<ast::Tparam>,
user_attributes: Vec<ast::UserAttribute>,
mode: file_info::Mode,
fun_kind: ast::FunKind,
ctxs: Option<ast::Contexts>,
params: Vec<ast::FunParam>,
}
impl Fun_ {
fn new(fd: &ast::FunDef) -> Self {
let f = &fd.fun;
Self {
name: fd.name.clone(),
span: f.span.clone(),
tparams: fd.tparams.clone(),
user_attributes: f.user_attributes.clone().into(),
mode: fd.mode,
fun_kind: f.fun_kind,
ctxs: f.ctxs.clone(),
params: f.params.clone(),
}
}
}
#[derive(Debug, Eq, PartialEq)]
pub struct Method_ {
name: ast::Id,
span: Pos,
tparams: Vec<ast::Tparam>,
user_attributes: Vec<ast::UserAttribute>,
static_: bool,
fun_kind: ast::FunKind,
ctxs: Option<ast::Contexts>,
params: Vec<ast::FunParam>,
}
impl Method_ {
fn new(m: &ast::Method_) -> Self {
Self {
name: m.name.clone(),
span: m.span.clone(),
tparams: m.tparams.clone(),
static_: m.static_,
user_attributes: m.user_attributes.clone().into(),
fun_kind: m.fun_kind,
ctxs: m.ctxs.clone(),
params: m.params.clone(),
}
}
} |
Rust | hhvm/hphp/hack/src/hackc/emitter/class_expr.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use ast_scope::Scope;
use hhbc::ClassishKind;
use hhbc::SpecialClsRef;
use hhbc_string_utils as string_utils;
use instruction_sequence::InstrSeq;
use naming_special_names_rust::classes;
use oxidized::aast::*;
use oxidized::ast;
use oxidized::ast_defs;
use crate::emitter::Emitter;
#[derive(Debug)]
pub enum ClassExpr<'arena> {
Special(SpecialClsRef),
Id(ast_defs::Id),
Expr(ast::Expr),
Reified(InstrSeq<'arena>),
}
impl<'arena> ClassExpr<'arena> {
fn get_original_class_name<'decl>(
emitter: &Emitter<'arena, 'decl>,
check_traits: bool,
resolve_self: bool,
opt_class_info: Option<(ClassishKind, &str)>,
) -> Option<String> {
if let Some((kind, class_name)) = opt_class_info {
if (kind != ClassishKind::Trait || check_traits) && resolve_self {
if string_utils::closures::unmangle_closure(class_name).is_none() {
return Some(class_name.to_string());
} else if let Some(c) = emitter
.global_state()
.get_closure_enclosing_class(class_name)
{
if ClassishKind::from(c.kind.clone()) != ClassishKind::Trait {
return Some(c.name.clone());
}
}
}
}
None
}
pub fn get_parent_class_name<'a>(class: &'a ast_scope::Class<'a>) -> Option<&'a str> {
if let [Hint(_, hint)] = class.get_extends() {
if let Hint_::Happly(ast_defs::Id(_, parent_cid), _) = &**hint {
return Some(parent_cid);
}
}
None
}
fn get_original_parent_class_name<'decl>(
emitter: &Emitter<'arena, 'decl>,
check_traits: bool,
resolve_self: bool,
opt_class_info: Option<(ClassishKind, &str)>,
opt_parent_name: Option<String>,
) -> Option<String> {
if let Some((kind, class_name)) = opt_class_info {
if kind == ClassishKind::Interface {
return Some(classes::PARENT.to_string());
};
if (kind != ClassishKind::Trait || check_traits) && resolve_self {
if string_utils::closures::unmangle_closure(class_name).is_none() {
return opt_parent_name;
} else if let Some(c) = emitter
.global_state()
.get_closure_enclosing_class(class_name)
{
return c.parent_class_name.clone();
}
}
}
None
}
fn expr_to_class_expr<'a, 'decl>(
emitter: &Emitter<'arena, 'decl>,
check_traits: bool,
resolve_self: bool,
scope: &Scope<'a, 'arena>,
expr: ast::Expr,
) -> Self {
if let Some(cd) = scope.get_class() {
Self::expr_to_class_expr_(
emitter,
check_traits,
resolve_self,
Some((ClassishKind::from(cd.get_kind()), cd.get_name_str())),
Self::get_parent_class_name(cd).map(String::from),
expr,
)
} else {
Self::expr_to_class_expr_(emitter, check_traits, resolve_self, None, None, expr)
}
}
pub fn expr_to_class_expr_<'decl>(
emitter: &Emitter<'arena, 'decl>,
check_traits: bool,
resolve_self: bool,
opt_class_info: Option<(ClassishKind, &str)>,
opt_parent_name: Option<String>,
expr: ast::Expr,
) -> Self {
match expr.2 {
Expr_::Id(x) => {
let ast_defs::Id(pos, id) = *x;
if string_utils::is_static(&id) {
Self::Special(SpecialClsRef::LateBoundCls)
} else if string_utils::is_parent(&id) {
match Self::get_original_parent_class_name(
emitter,
check_traits,
resolve_self,
opt_class_info,
opt_parent_name,
) {
Some(name) => Self::Id(ast_defs::Id(pos, name)),
None => Self::Special(SpecialClsRef::ParentCls),
}
} else if string_utils::is_self(&id) {
match Self::get_original_class_name(
emitter,
check_traits,
resolve_self,
opt_class_info,
) {
Some(name) => Self::Id(ast_defs::Id(pos, name)),
None => Self::Special(SpecialClsRef::SelfCls),
}
} else {
Self::Id(ast_defs::Id(pos, id))
}
}
_ => Self::Expr(expr),
}
}
pub fn class_id_to_class_expr<'a, 'decl>(
emitter: &Emitter<'arena, 'decl>,
check_traits: bool,
resolve_self: bool,
scope: &Scope<'a, 'arena>,
cid: &ast::ClassId,
) -> Self {
let ClassId(_, annot, cid_) = cid;
let expr = match cid_ {
ClassId_::CIexpr(e) => e.clone(),
ClassId_::CI(sid) => Expr((), annot.clone(), Expr_::mk_id(sid.clone())),
ClassId_::CIparent => return Self::Special(SpecialClsRef::ParentCls),
ClassId_::CIstatic => return Self::Special(SpecialClsRef::LateBoundCls),
ClassId_::CIself => return Self::Special(SpecialClsRef::SelfCls),
};
Self::expr_to_class_expr(emitter, check_traits, resolve_self, scope, expr)
}
} |
Rust | hhvm/hphp/hack/src/hackc/emitter/constant_folder.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::collections::hash_map::RandomState;
use std::fmt;
use env::emitter::Emitter;
use env::ClassExpr;
use ffi::Str;
use hhbc::DictEntry;
use hhbc::TypedValue;
use hhbc_string_utils as string_utils;
use indexmap::IndexMap;
use itertools::Itertools;
use naming_special_names_rust::math;
use naming_special_names_rust::members;
use naming_special_names_rust::typehints;
use oxidized::aast_visitor::visit_mut;
use oxidized::aast_visitor::AstParams;
use oxidized::aast_visitor::NodeMut;
use oxidized::aast_visitor::VisitorMut;
use oxidized::ast;
use oxidized::ast_defs;
use oxidized::pos::Pos;
#[derive(Debug, PartialEq, Eq)]
pub enum Error {
NotLiteral,
UserDefinedConstant,
Unrecoverable(String),
}
impl Error {
fn unrecoverable(s: impl Into<String>) -> Self {
Self::Unrecoverable(s.into())
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NotLiteral => write!(f, "NotLiteral"),
Self::UserDefinedConstant => write!(f, "UserDefinedConstant"),
Self::Unrecoverable(msg) => write!(f, "{}", msg),
}
}
}
enum Radix {
Oct,
Hex,
Dec,
Bin,
}
fn radix(s: &str) -> Radix {
let s = s.as_bytes();
if s.len() > 1 && (s[0] as char) == '0' {
match s[1] as char {
'b' | 'B' => Radix::Bin,
'x' | 'X' => Radix::Hex,
_ => Radix::Oct,
}
} else {
Radix::Dec
}
}
fn try_type_intlike(s: &str) -> Option<i64> {
match radix(s) {
Radix::Dec => s.parse().ok(),
Radix::Bin => i64::from_str_radix(&s[2..], 2).ok(),
Radix::Oct => {
let mut i = 1;
let sb = s.as_bytes();
// Ocaml's version truncate if any digit is greater then 7.
while i < sb.len() {
if sb[i] >= b'0' && sb[i] <= b'7' {
i += 1;
} else {
break;
}
}
if i > 1 {
let sb = &sb[1..i];
i64::from_str_radix(std::str::from_utf8(sb).unwrap(), 8).ok()
} else {
Some(0)
}
}
Radix::Hex => i64::from_str_radix(&s[2..], 16).ok(),
}
}
fn class_const_to_typed_value<'arena, 'decl>(
emitter: &Emitter<'arena, 'decl>,
cid: &ast::ClassId,
id: &ast::Pstring,
) -> Result<TypedValue<'arena>, Error> {
if id.1 == members::M_CLASS {
let cexpr = ClassExpr::class_id_to_class_expr(
emitter,
false,
true,
&ast_scope::Scope::default(),
cid,
);
if let ClassExpr::Id(ast_defs::Id(_, cname)) = cexpr {
let classid =
hhbc::ClassName::from_ast_name_and_mangle(emitter.alloc, cname).as_ffi_str();
return Ok(TypedValue::LazyClass(classid));
}
}
Err(Error::UserDefinedConstant)
}
fn varray_to_typed_value<'arena, 'decl>(
emitter: &Emitter<'arena, 'decl>,
fields: &[ast::Expr],
) -> Result<TypedValue<'arena>, Error> {
let tv_fields = emitter.alloc.alloc_slice_fill_iter(
fields
.iter()
.map(|x| expr_to_typed_value(emitter, x))
.collect::<Result<Vec<_>, _>>()?
.into_iter(),
);
Ok(TypedValue::vec(tv_fields))
}
fn darray_to_typed_value<'arena, 'decl>(
emitter: &Emitter<'arena, 'decl>,
fields: &[(ast::Expr, ast::Expr)],
) -> Result<TypedValue<'arena>, Error> {
//TODO: Improve. It's a bit silly having to use a std::vector::Vec
// here.
let tv_fields: Vec<(TypedValue<'arena>, TypedValue<'arena>)> = fields
.iter()
.map(|(k, v)| {
Ok((
key_expr_to_typed_value(emitter, k)?,
expr_to_typed_value(emitter, v)?,
))
})
.collect::<Result<_, Error>>()?;
Ok(TypedValue::dict(emitter.alloc.alloc_slice_fill_iter(
update_duplicates_in_map(tv_fields),
)))
}
fn set_afield_to_typed_value_pair<'arena, 'decl>(
e: &Emitter<'arena, 'decl>,
afield: &ast::Afield,
) -> Result<(TypedValue<'arena>, TypedValue<'arena>), Error> {
match afield {
ast::Afield::AFvalue(v) => set_afield_value_to_typed_value_pair(e, v),
_ => Err(Error::unrecoverable(
"set_afield_to_typed_value_pair: unexpected key=>value",
)),
}
}
fn set_afield_value_to_typed_value_pair<'arena, 'decl>(
e: &Emitter<'arena, 'decl>,
v: &ast::Expr,
) -> Result<(TypedValue<'arena>, TypedValue<'arena>), Error> {
let tv = key_expr_to_typed_value(e, v)?;
Ok((tv.clone(), tv))
}
fn afield_to_typed_value_pair<'arena, 'decl>(
emitter: &Emitter<'arena, 'decl>,
afield: &ast::Afield,
) -> Result<(TypedValue<'arena>, TypedValue<'arena>), Error> {
match afield {
ast::Afield::AFvalue(_) => Err(Error::unrecoverable(
"afield_to_typed_value_pair: unexpected value",
)),
ast::Afield::AFkvalue(key, value) => kv_to_typed_value_pair(emitter, key, value),
}
}
fn kv_to_typed_value_pair<'arena, 'decl>(
emitter: &Emitter<'arena, 'decl>,
key: &ast::Expr,
value: &ast::Expr,
) -> Result<(TypedValue<'arena>, TypedValue<'arena>), Error> {
Ok((
key_expr_to_typed_value(emitter, key)?,
expr_to_typed_value(emitter, value)?,
))
}
fn value_afield_to_typed_value<'arena, 'decl>(
emitter: &Emitter<'arena, 'decl>,
afield: &ast::Afield,
) -> Result<TypedValue<'arena>, Error> {
match afield {
ast::Afield::AFvalue(e) => expr_to_typed_value(emitter, e),
ast::Afield::AFkvalue(_, _) => Err(Error::unrecoverable(
"value_afield_to_typed_value: unexpected key=>value",
)),
}
}
fn key_expr_to_typed_value<'arena, 'decl>(
emitter: &Emitter<'arena, 'decl>,
expr: &ast::Expr,
) -> Result<TypedValue<'arena>, Error> {
let tv = expr_to_typed_value(emitter, expr)?;
let fold_lc = emitter.options().hhbc.fold_lazy_class_keys;
match tv {
TypedValue::Int(_) | TypedValue::String(_) => Ok(tv),
TypedValue::LazyClass(_) if fold_lc => Ok(tv),
_ => Err(Error::NotLiteral),
}
}
fn keyset_value_afield_to_typed_value<'arena, 'decl>(
emitter: &Emitter<'arena, 'decl>,
afield: &ast::Afield,
) -> Result<TypedValue<'arena>, Error> {
let tv = value_afield_to_typed_value(emitter, afield)?;
let fold_lc = emitter.options().hhbc.fold_lazy_class_keys;
match tv {
TypedValue::Int(_) | TypedValue::String(_) => Ok(tv),
TypedValue::LazyClass(_) if fold_lc => Ok(tv),
_ => Err(Error::NotLiteral),
}
}
fn shape_to_typed_value<'arena, 'decl>(
emitter: &Emitter<'arena, 'decl>,
fields: &[(ast::ShapeFieldName, ast::Expr)],
) -> Result<TypedValue<'arena>, Error> {
let a = emitter.alloc.alloc_slice_fill_iter(
fields
.iter()
.map(|(sf, expr)| {
let key = match sf {
ast_defs::ShapeFieldName::SFlitInt((_, s)) => {
let tv = int_expr_to_typed_value(s)?;
match tv {
TypedValue::Int(_) => tv,
_ => {
return Err(Error::unrecoverable(format!(
"{} is not a valid integer index",
s
)));
}
}
}
ast_defs::ShapeFieldName::SFlitStr(id) => {
// FIXME: This is not safe--string literals are binary
// strings. There's no guarantee that they're valid UTF-8.
TypedValue::string(
emitter
.alloc
.alloc_str(unsafe { std::str::from_utf8_unchecked(&id.1) }),
)
}
ast_defs::ShapeFieldName::SFclassConst(class_id, id) => {
class_const_to_typed_value(
emitter,
&ast::ClassId((), Pos::NONE, ast::ClassId_::CI(class_id.clone())),
id,
)?
}
};
let value = expr_to_typed_value(emitter, expr)?;
Ok(DictEntry { key, value })
})
.collect::<Result<Vec<_>, _>>()?
.into_iter(),
);
Ok(TypedValue::dict(a))
}
pub fn vec_to_typed_value<'arena, 'decl>(
e: &Emitter<'arena, 'decl>,
fields: &[ast::Afield],
) -> Result<TypedValue<'arena>, Error> {
//TODO: Improve. It's a bit silly having to use a std::vector::Vec
// here.
let tv_fields: Result<Vec<TypedValue<'arena>>, Error> = fields
.iter()
.map(|f| value_afield_to_typed_value(e, f))
.collect();
let fields = e.alloc.alloc_slice_fill_iter(tv_fields?.into_iter());
Ok(TypedValue::vec(fields))
}
pub fn expr_to_typed_value<'arena, 'decl>(
e: &Emitter<'arena, 'decl>,
expr: &ast::Expr,
) -> Result<TypedValue<'arena>, Error> {
expr_to_typed_value_(e, expr, false /*allow_maps*/)
}
pub fn expr_to_typed_value_<'arena, 'decl>(
emitter: &Emitter<'arena, 'decl>,
expr: &ast::Expr,
allow_maps: bool,
) -> Result<TypedValue<'arena>, Error> {
stack_limit::maybe_grow(|| {
// TODO: ML equivalent has this as an implicit parameter that defaults to false.
use ast::Expr_;
match &expr.2 {
Expr_::Int(s) => int_expr_to_typed_value(s),
Expr_::True => Ok(TypedValue::Bool(true)),
Expr_::False => Ok(TypedValue::Bool(false)),
Expr_::Null => Ok(TypedValue::Null),
Expr_::String(s) => string_expr_to_typed_value(emitter, s),
Expr_::Float(s) => float_expr_to_typed_value(emitter, s),
Expr_::Varray(fields) => varray_to_typed_value(emitter, &fields.1),
Expr_::Darray(fields) => darray_to_typed_value(emitter, &fields.1),
Expr_::Id(id) if id.1 == math::NAN => Ok(TypedValue::float(std::f64::NAN)),
Expr_::Id(id) if id.1 == math::INF => Ok(TypedValue::float(std::f64::INFINITY)),
Expr_::Id(_) => Err(Error::UserDefinedConstant),
Expr_::Collection(x) if x.0.name().eq("keyset") => {
keyset_expr_to_typed_value(emitter, x)
}
Expr_::Collection(x)
if x.0.name().eq("dict")
|| allow_maps
&& (string_utils::cmp(&(x.0).1, "Map", false, true)
|| string_utils::cmp(&(x.0).1, "ImmMap", false, true)) =>
{
dict_expr_to_typed_value(emitter, x)
}
Expr_::Collection(x)
if allow_maps
&& (string_utils::cmp(&(x.0).1, "Set", false, true)
|| string_utils::cmp(&(x.0).1, "ImmSet", false, true)) =>
{
set_expr_to_typed_value(emitter, x)
}
Expr_::Tuple(x) => tuple_expr_to_typed_value(emitter, x),
Expr_::ValCollection(x)
if x.0.1 == ast::VcKind::Vec || x.0.1 == ast::VcKind::Vector =>
{
valcollection_vec_expr_to_typed_value(emitter, x)
}
Expr_::ValCollection(x) if x.0.1 == ast::VcKind::Keyset => {
valcollection_keyset_expr_to_typed_value(emitter, x)
}
Expr_::ValCollection(x)
if x.0.1 == ast::VcKind::Set || x.0.1 == ast::VcKind::ImmSet =>
{
valcollection_set_expr_to_typed_value(emitter, x)
}
Expr_::KeyValCollection(x) => keyvalcollection_expr_to_typed_value(emitter, x),
Expr_::Shape(fields) => shape_to_typed_value(emitter, fields),
Expr_::ClassConst(x) => class_const_to_typed_value(emitter, &x.0, &x.1),
Expr_::ClassGet(_) => Err(Error::UserDefinedConstant),
ast::Expr_::As(x) if (x.1).1.is_hlike() => {
expr_to_typed_value_(emitter, &x.0, allow_maps)
}
Expr_::Upcast(e) => expr_to_typed_value(emitter, &e.0),
_ => Err(Error::NotLiteral),
}
})
}
fn valcollection_keyset_expr_to_typed_value<'arena, 'decl>(
emitter: &Emitter<'arena, 'decl>,
x: &((Pos, ast::VcKind), Option<ast::Targ>, Vec<ast::Expr>),
) -> Result<TypedValue<'arena>, Error> {
let keys = emitter.alloc.alloc_slice_fill_iter(
x.2.iter()
.map(|e| {
expr_to_typed_value(emitter, e).and_then(|tv| match tv {
TypedValue::Int(_) | TypedValue::String(_) => Ok(tv),
TypedValue::LazyClass(_) if emitter.options().hhbc.fold_lazy_class_keys => {
Ok(tv)
}
_ => Err(Error::NotLiteral),
})
})
.collect::<Result<Vec<_>, _>>()?
.into_iter()
.unique()
.collect::<Vec<_>>()
.into_iter(),
);
Ok(TypedValue::keyset(keys))
}
fn keyvalcollection_expr_to_typed_value<'arena, 'decl>(
emitter: &Emitter<'arena, 'decl>,
x: &(
(Pos, ast::KvcKind),
Option<(ast::Targ, ast::Targ)>,
Vec<ast::Field>,
),
) -> Result<TypedValue<'arena>, Error> {
let values = emitter
.alloc
.alloc_slice_fill_iter(update_duplicates_in_map(
x.2.iter()
.map(|e| kv_to_typed_value_pair(emitter, &e.0, &e.1))
.collect::<Result<Vec<_>, _>>()?,
));
Ok(TypedValue::dict(values))
}
fn valcollection_set_expr_to_typed_value<'arena, 'decl>(
emitter: &Emitter<'arena, 'decl>,
x: &((Pos, ast::VcKind), Option<ast::Targ>, Vec<ast::Expr>),
) -> Result<TypedValue<'arena>, Error> {
let values = emitter
.alloc
.alloc_slice_fill_iter(update_duplicates_in_map(
x.2.iter()
.map(|e| set_afield_value_to_typed_value_pair(emitter, e))
.collect::<Result<Vec<_>, _>>()?,
));
Ok(TypedValue::dict(values))
}
fn valcollection_vec_expr_to_typed_value<'arena, 'decl>(
emitter: &Emitter<'arena, 'decl>,
x: &((Pos, ast::VcKind), Option<ast::Targ>, Vec<ast::Expr>),
) -> Result<TypedValue<'arena>, Error> {
let v: Vec<_> =
x.2.iter()
.map(|e| expr_to_typed_value(emitter, e))
.collect::<Result<_, _>>()?;
Ok(TypedValue::vec(
emitter.alloc.alloc_slice_fill_iter(v.into_iter()),
))
}
fn tuple_expr_to_typed_value<'arena, 'decl>(
emitter: &Emitter<'arena, 'decl>,
x: &[ast::Expr],
) -> Result<TypedValue<'arena>, Error> {
let v: Vec<_> = x
.iter()
.map(|e| expr_to_typed_value(emitter, e))
.collect::<Result<_, _>>()?;
Ok(TypedValue::vec(
emitter.alloc.alloc_slice_fill_iter(v.into_iter()),
))
}
fn set_expr_to_typed_value<'arena, 'decl>(
emitter: &Emitter<'arena, 'decl>,
x: &(
ast::ClassName,
Option<ast::CollectionTarg>,
Vec<ast::Afield>,
),
) -> Result<TypedValue<'arena>, Error> {
let values = emitter
.alloc
.alloc_slice_fill_iter(update_duplicates_in_map(
x.2.iter()
.map(|x| set_afield_to_typed_value_pair(emitter, x))
.collect::<Result<_, _>>()?,
));
Ok(TypedValue::dict(values))
}
fn dict_expr_to_typed_value<'arena, 'decl>(
emitter: &Emitter<'arena, 'decl>,
x: &(
ast::ClassName,
Option<ast::CollectionTarg>,
Vec<ast::Afield>,
),
) -> Result<TypedValue<'arena>, Error> {
let values = emitter
.alloc
.alloc_slice_fill_iter(update_duplicates_in_map(
x.2.iter()
.map(|x| afield_to_typed_value_pair(emitter, x))
.collect::<Result<_, _>>()?,
));
Ok(TypedValue::dict(values))
}
fn keyset_expr_to_typed_value<'arena, 'decl>(
emitter: &Emitter<'arena, 'decl>,
x: &(
ast::ClassName,
Option<ast::CollectionTarg>,
Vec<ast::Afield>,
),
) -> Result<TypedValue<'arena>, Error> {
let keys = emitter.alloc.alloc_slice_fill_iter(
x.2.iter()
.map(|x| keyset_value_afield_to_typed_value(emitter, x))
.collect::<Result<Vec<_>, _>>()?
.into_iter()
.unique()
.collect::<Vec<_>>()
.into_iter(),
);
Ok(TypedValue::keyset(keys))
}
fn float_expr_to_typed_value<'arena, 'decl>(
_emitter: &Emitter<'arena, 'decl>,
s: &str,
) -> Result<TypedValue<'arena>, Error> {
if s == math::INF {
Ok(TypedValue::float(std::f64::INFINITY))
} else if s == math::NEG_INF {
Ok(TypedValue::float(std::f64::NEG_INFINITY))
} else if s == math::NAN {
Ok(TypedValue::float(std::f64::NAN))
} else {
s.parse()
.map(TypedValue::float)
.map_err(|_| Error::NotLiteral)
}
}
fn string_expr_to_typed_value<'arena, 'decl>(
emitter: &Emitter<'arena, 'decl>,
s: &[u8],
) -> Result<TypedValue<'arena>, Error> {
// FIXME: This is not safe--string literals are binary strings.
// There's no guarantee that they're valid UTF-8.
Ok(TypedValue::string(
emitter
.alloc
.alloc_str(unsafe { std::str::from_utf8_unchecked(s) }),
))
}
fn int_expr_to_typed_value<'arena>(s: &str) -> Result<TypedValue<'arena>, Error> {
Ok(TypedValue::Int(
try_type_intlike(s).unwrap_or(std::i64::MAX),
))
}
fn update_duplicates_in_map<'arena>(
kvs: Vec<(TypedValue<'arena>, TypedValue<'arena>)>,
) -> impl IntoIterator<
Item = DictEntry<'arena>,
IntoIter = impl Iterator<Item = DictEntry<'arena>> + ExactSizeIterator + 'arena,
> + 'arena {
kvs.into_iter()
.collect::<IndexMap<_, _, RandomState>>()
.into_iter()
.map(|(key, value)| DictEntry { key, value })
}
fn cast_value<'arena>(
alloc: &'arena bumpalo::Bump,
hint: &ast::Hint_,
v: TypedValue<'arena>,
) -> Result<TypedValue<'arena>, Error> {
match hint {
ast::Hint_::Happly(ast_defs::Id(_, id), args) if args.is_empty() => {
let id = string_utils::strip_hh_ns(id);
if id == typehints::BOOL {
Some(TypedValue::Bool(cast_to_bool(v)))
} else if id == typehints::STRING {
cast_to_arena_str(v, alloc).map(TypedValue::string)
} else if id == typehints::FLOAT {
cast_to_float(v).map(TypedValue::float)
} else {
None
}
}
_ => None,
}
.ok_or(Error::NotLiteral)
}
fn unop_on_value<'arena>(
unop: &ast_defs::Uop,
v: TypedValue<'arena>,
) -> Result<TypedValue<'arena>, Error> {
match unop {
ast_defs::Uop::Unot => fold_logical_not(v),
ast_defs::Uop::Uplus => fold_add(v, TypedValue::Int(0)),
ast_defs::Uop::Uminus => match v {
TypedValue::Int(i) => Some(TypedValue::Int((-std::num::Wrapping(i)).0)),
TypedValue::Float(i) => Some(TypedValue::float(0.0 - i.to_f64())),
_ => None,
},
ast_defs::Uop::Utild => fold_bitwise_not(v),
ast_defs::Uop::Usilence => Some(v.clone()),
_ => None,
}
.ok_or(Error::NotLiteral)
}
fn binop_on_values<'arena>(
alloc: &'arena bumpalo::Bump,
binop: &ast_defs::Bop,
v1: TypedValue<'arena>,
v2: TypedValue<'arena>,
) -> Result<TypedValue<'arena>, Error> {
use ast_defs::Bop;
match binop {
Bop::Dot => fold_concat(v1, v2, alloc),
Bop::Plus => fold_add(v1, v2),
Bop::Minus => fold_sub(v1, v2),
Bop::Star => fold_mul(v1, v2),
Bop::Ltlt => fold_shift_left(v1, v2),
Bop::Slash => fold_div(v1, v2),
Bop::Bar => fold_bitwise_or(v1, v2),
_ => None,
}
.ok_or(Error::NotLiteral)
}
fn value_to_expr_<'arena>(v: TypedValue<'arena>) -> Result<ast::Expr_, Error> {
use ast::Expr_;
match v {
TypedValue::Int(i) => Ok(Expr_::Int(i.to_string())),
TypedValue::Float(f) => Ok(Expr_::Float(hhbc_string_utils::float::to_string(
f.to_f64(),
))),
TypedValue::Bool(false) => Ok(Expr_::False),
TypedValue::Bool(true) => Ok(Expr_::True),
TypedValue::String(s) => Ok(Expr_::String(s.unsafe_as_str().into())),
TypedValue::LazyClass(_) => Err(Error::unrecoverable("value_to_expr: lazyclass NYI")),
TypedValue::Null => Ok(Expr_::Null),
TypedValue::Uninit => Err(Error::unrecoverable("value_to_expr: uninit value")),
TypedValue::Vec(_) => Err(Error::unrecoverable("value_to_expr: vec NYI")),
TypedValue::Keyset(_) => Err(Error::unrecoverable("value_to_expr: keyset NYI")),
TypedValue::Dict(_) => Err(Error::unrecoverable("value_to_expr: dict NYI")),
}
}
struct FolderVisitor<'a, 'arena, 'decl> {
emitter: &'a Emitter<'arena, 'decl>,
}
impl<'a, 'arena, 'decl> FolderVisitor<'a, 'arena, 'decl> {
fn new(emitter: &'a Emitter<'arena, 'decl>) -> Self {
Self { emitter }
}
}
impl<'ast, 'decl> VisitorMut<'ast> for FolderVisitor<'_, '_, 'decl> {
type Params = AstParams<(), Error>;
fn object(&mut self) -> &mut dyn VisitorMut<'ast, Params = Self::Params> {
self
}
fn visit_expr_(&mut self, c: &mut (), p: &mut ast::Expr_) -> Result<(), Error> {
p.recurse(c, self.object())?;
let new_p = match p {
ast::Expr_::Cast(e) => expr_to_typed_value(self.emitter, &e.1)
.and_then(|v| cast_value(self.emitter.alloc, &(e.0).1, v))
.map(value_to_expr_)
.ok(),
ast::Expr_::Unop(e) => expr_to_typed_value(self.emitter, &e.1)
.and_then(|v| unop_on_value(&e.0, v))
.map(value_to_expr_)
.ok(),
ast::Expr_::Binop(binop) => expr_to_typed_value(self.emitter, &binop.lhs)
.and_then(|v1| {
expr_to_typed_value(self.emitter, &binop.rhs).and_then(|v2| {
binop_on_values(self.emitter.alloc, &binop.bop, v1, v2).map(value_to_expr_)
})
})
.ok(),
_ => None,
};
if let Some(new_p) = new_p {
*p = new_p?
}
Ok(())
}
}
pub fn fold_expr<'arena, 'decl>(
expr: &mut ast::Expr,
e: &mut Emitter<'arena, 'decl>,
) -> Result<(), Error> {
visit_mut(&mut FolderVisitor::new(e), &mut (), expr)
}
pub fn fold_program<'arena, 'decl>(
p: &mut ast::Program,
e: &mut Emitter<'arena, 'decl>,
) -> Result<(), Error> {
visit_mut(&mut FolderVisitor::new(e), &mut (), p)
}
pub fn literals_from_exprs<'arena, 'decl>(
exprs: &mut [ast::Expr],
e: &mut Emitter<'arena, 'decl>,
) -> Result<Vec<TypedValue<'arena>>, Error> {
for expr in exprs.iter_mut() {
fold_expr(expr, e)?;
}
let ret = exprs
.iter()
.map(|expr| expr_to_typed_value_(e, expr, false))
.collect();
if let Err(Error::NotLiteral) = ret {
Err(Error::unrecoverable("literals_from_exprs: not literal"))
} else {
ret
}
}
fn cast_to_arena_str<'a>(x: TypedValue<'a>, alloc: &'a bumpalo::Bump) -> Option<Str<'a>> {
match x {
TypedValue::Uninit => None, // Should not happen
TypedValue::Bool(false) => Some("".into()),
TypedValue::Bool(true) => Some("1".into()),
TypedValue::Null => Some("".into()),
TypedValue::Int(i) => Some(alloc.alloc_str(i.to_string().as_str()).into()),
TypedValue::String(s) => Some(s),
TypedValue::LazyClass(s) => Some(s),
_ => None,
}
}
// Arithmetic. Only on pure integer or float operands
// and don't attempt to implement overflow-to-float semantics.
fn fold_add<'a>(x: TypedValue<'a>, y: TypedValue<'a>) -> Option<TypedValue<'a>> {
match (x, y) {
(TypedValue::Float(i1), TypedValue::Float(i2)) => {
Some(TypedValue::float(i1.to_f64() + i2.to_f64()))
}
(TypedValue::Int(i1), TypedValue::Int(i2)) => Some(TypedValue::Int(
(std::num::Wrapping(i1) + std::num::Wrapping(i2)).0,
)),
(TypedValue::Int(i1), TypedValue::Float(i2)) => {
Some(TypedValue::float(i1 as f64 + i2.to_f64()))
}
(TypedValue::Float(i1), TypedValue::Int(i2)) => {
Some(TypedValue::float(i1.to_f64() + i2 as f64))
}
_ => None,
}
}
// Arithmetic. Only on pure integer or float operands,
// and don't attempt to implement overflow-to-float semantics.
fn fold_sub<'a>(x: TypedValue<'a>, y: TypedValue<'a>) -> Option<TypedValue<'a>> {
match (x, y) {
(TypedValue::Int(i1), TypedValue::Int(i2)) => Some(TypedValue::Int(
(std::num::Wrapping(i1) - std::num::Wrapping(i2)).0,
)),
(TypedValue::Float(f1), TypedValue::Float(f2)) => {
Some(TypedValue::float(f1.to_f64() - f2.to_f64()))
}
_ => None,
}
}
// Arithmetic. Only on pure integer or float operands
// and don't attempt to implement overflow-to-float semantics.
fn fold_mul<'a>(x: TypedValue<'a>, y: TypedValue<'a>) -> Option<TypedValue<'a>> {
match (x, y) {
(TypedValue::Int(i1), TypedValue::Int(i2)) => Some(TypedValue::Int(
(std::num::Wrapping(i1) * std::num::Wrapping(i2)).0,
)),
(TypedValue::Float(i1), TypedValue::Float(i2)) => {
Some(TypedValue::float(i1.to_f64() * i2.to_f64()))
}
(TypedValue::Int(i1), TypedValue::Float(i2)) => {
Some(TypedValue::float(i1 as f64 * i2.to_f64()))
}
(TypedValue::Float(i1), TypedValue::Int(i2)) => {
Some(TypedValue::float(i1.to_f64() * i2 as f64))
}
_ => None,
}
}
// Arithmetic. Only on pure integer or float operands
// and don't attempt to implement overflow-to-float semantics.
fn fold_div<'a>(x: TypedValue<'a>, y: TypedValue<'a>) -> Option<TypedValue<'a>> {
match (x, y) {
(TypedValue::Int(i1), TypedValue::Int(i2)) if i2 != 0 && i1 % i2 == 0 => {
Some(TypedValue::Int(i1 / i2))
}
(TypedValue::Int(i1), TypedValue::Int(i2)) if i2 != 0 => {
Some(TypedValue::float(i1 as f64 / i2 as f64))
}
(TypedValue::Float(f1), TypedValue::Float(f2)) if f2.to_f64() != 0.0 => {
Some(TypedValue::float(f1.to_f64() / f2.to_f64()))
}
(TypedValue::Int(i1), TypedValue::Float(f2)) if f2.to_f64() != 0.0 => {
Some(TypedValue::float(i1 as f64 / f2.to_f64()))
}
(TypedValue::Float(f1), TypedValue::Int(i2)) if i2 != 0 => {
Some(TypedValue::float(f1.to_f64() / i2 as f64))
}
_ => None,
}
}
fn fold_shift_left<'a>(x: TypedValue<'a>, y: TypedValue<'a>) -> Option<TypedValue<'a>> {
match (x, y) {
(TypedValue::Int(_), TypedValue::Int(i2)) if i2 < 0 => None,
(TypedValue::Int(i1), TypedValue::Int(i2)) => i32::try_from(i2)
.ok()
.map(|i2| TypedValue::Int(i1 << (i2 % 64) as u32)),
_ => None,
}
}
// Arithmetic, only on pure integer operands.
fn fold_bitwise_or<'a>(x: TypedValue<'a>, y: TypedValue<'a>) -> Option<TypedValue<'a>> {
match (x, y) {
(TypedValue::Int(i1), TypedValue::Int(i2)) => Some(TypedValue::Int(i1 | i2)),
_ => None,
}
}
// String concatenation
fn fold_concat<'a>(
x: TypedValue<'a>,
y: TypedValue<'a>,
alloc: &'a bumpalo::Bump,
) -> Option<TypedValue<'a>> {
fn safe_to_cast(t: &TypedValue<'_>) -> bool {
matches!(
t,
TypedValue::Int(_) | TypedValue::String(_) | TypedValue::LazyClass(_)
)
}
if !safe_to_cast(&x) || !safe_to_cast(&y) {
return None;
}
let l = cast_to_string(x)?;
let r = cast_to_string(y)?;
Some(TypedValue::alloc_string(l + &r, alloc))
}
// Bitwise operations.
fn fold_bitwise_not<'a>(x: TypedValue<'a>) -> Option<TypedValue<'a>> {
match x {
TypedValue::Int(i) => Some(TypedValue::Int(!i)),
_ => None,
}
}
fn fold_logical_not<'a>(x: TypedValue<'a>) -> Option<TypedValue<'a>> {
Some(TypedValue::Bool(!cast_to_bool(x)))
}
/// Cast to a boolean: the (bool) operator in PHP
pub fn cast_to_bool(x: TypedValue<'_>) -> bool {
match x {
TypedValue::Uninit => false, // Should not happen
TypedValue::Bool(b) => b,
TypedValue::Null => false,
TypedValue::String(s) => !s.is_empty() && s.unsafe_as_str() != "0",
TypedValue::LazyClass(_) => true,
TypedValue::Int(i) => i != 0,
TypedValue::Float(f) => f.to_f64() != 0.0,
// Empty collections cast to false if empty, otherwise true
TypedValue::Vec(v) => !v.is_empty(),
TypedValue::Keyset(v) => !v.is_empty(),
TypedValue::Dict(v) => !v.is_empty(),
}
}
/// Cast to an integer: the (int) operator in PHP. Return None if we can't
/// or won't produce the correct value
pub fn cast_to_int(x: TypedValue<'_>) -> Option<i64> {
match x {
TypedValue::Uninit => None, // Should not happen
// Unreachable - the only calliste of to_int is cast_to_arraykey, which never
// calls it with String
TypedValue::String(_) => None, // not worth it
TypedValue::LazyClass(_) => None, // not worth it
TypedValue::Int(i) => Some(i),
TypedValue::Float(f) => match f.to_f64().classify() {
std::num::FpCategory::Nan | std::num::FpCategory::Infinite => {
Some(if f.to_f64() == f64::INFINITY {
0
} else {
std::i64::MIN
})
}
_ => todo!(),
},
v => Some(if cast_to_bool(v) { 1 } else { 0 }),
}
}
/// Cast to a float: the (float) operator in PHP. Return None if we can't
/// or won't produce the correct value
pub fn cast_to_float(v: TypedValue<'_>) -> Option<f64> {
match v {
TypedValue::Uninit => None, // Should not happen
TypedValue::String(_) => None, // not worth it
TypedValue::LazyClass(_) => None, // not worth it
TypedValue::Int(i) => Some(i as f64),
TypedValue::Float(f) => Some(f.to_f64()),
_ => Some(if cast_to_bool(v) { 1.0 } else { 0.0 }),
}
}
/// Cast to a string: the (string) operator in PHP. Return Err if we can't
/// or won't produce the correct value *)
pub fn cast_to_string(x: TypedValue<'_>) -> Option<String> {
match x {
TypedValue::Uninit => None, // Should not happen
TypedValue::Bool(false) => Some("".into()),
TypedValue::Bool(true) => Some("1".into()),
TypedValue::Null => Some("".into()),
TypedValue::Int(i) => Some(i.to_string()),
TypedValue::String(s) => Some(s.unsafe_as_str().into()),
TypedValue::LazyClass(s) => Some(s.unsafe_as_str().into()),
_ => None,
}
}
#[cfg(test)]
mod cast_tests {
use super::*;
#[test]
fn non_numeric_string_to_int() {
let res = cast_to_int(TypedValue::string("foo"));
assert!(res.is_none());
}
#[test]
fn nan_to_int() {
let res = cast_to_int(TypedValue::float(std::f64::NAN)).unwrap();
assert_eq!(res, std::i64::MIN);
}
} |
Rust | hhvm/hphp/hack/src/hackc/emitter/emitter.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::borrow::Cow;
use std::collections::BTreeSet;
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
use std::path::Path;
use std::sync::Arc;
use decl_provider::DeclProvider;
use decl_provider::MemoProvider;
use ffi::Slice;
use ffi::Str;
use global_state::GlobalState;
use hash::IndexSet;
use hhbc::ClassName;
use hhbc::ConstName;
use hhbc::FunctionName;
use hhbc::IncludePath;
use hhbc::IncludePathSet;
use hhbc::Local;
use hhbc::SymbolRefs;
use options::Options;
use oxidized::ast;
use oxidized::ast_defs;
use oxidized::pos::Pos;
use print_expr::HhasBodyEnv;
use relative_path::RelativePath;
use statement_state::StatementState;
use crate::adata_state::AdataState;
use crate::ClassExpr;
use crate::IterGen;
use crate::LabelGen;
use crate::LocalGen;
#[derive(Debug)]
pub struct Emitter<'arena, 'decl> {
/// Options are frozen/const after emitter is constructed
opts: Options,
/// systemlib is part of context, changed externally
systemlib: bool,
// the rest is being mutated during emittance
label_gen: LabelGen,
local_gen: LocalGen,
iterator: IterGen,
named_locals: IndexSet<Str<'arena>>,
pub filepath: RelativePath,
pub for_debugger_eval: bool,
pub alloc: &'arena bumpalo::Bump,
pub adata_state: Option<AdataState<'arena>>,
pub statement_state_: Option<StatementState<'arena>>,
symbol_refs_state: SymbolRefsState<'arena>,
/// State is also frozen and set after closure conversion
pub global_state_: Option<GlobalState<'arena>>,
/// Controls whether we call the decl provider for testing purposes.
/// Some(provider) => use the given DeclProvider, which may return NotFound.
/// None => do not look up any decls. For now this is the same as as a
/// DeclProvider that always returns NotFound, but this behavior may later
/// diverge from None provider behavior.
pub decl_provider: Option<Arc<dyn DeclProvider<'decl> + 'decl>>,
}
impl<'arena, 'decl> Emitter<'arena, 'decl> {
pub fn new(
opts: Options,
systemlib: bool,
for_debugger_eval: bool,
alloc: &'arena bumpalo::Bump,
decl_provider: Option<Arc<dyn DeclProvider<'decl> + 'decl>>,
filepath: RelativePath,
) -> Emitter<'arena, 'decl> {
Emitter {
opts,
systemlib,
for_debugger_eval,
decl_provider: decl_provider
.map(|p| Arc::new(MemoProvider::new(p)) as Arc<dyn DeclProvider<'decl> + 'decl>),
alloc,
label_gen: LabelGen::new(),
local_gen: LocalGen::new(),
iterator: Default::default(),
named_locals: Default::default(),
filepath,
adata_state: None,
statement_state_: None,
symbol_refs_state: Default::default(),
global_state_: None,
}
}
pub fn options(&self) -> &Options {
&self.opts
}
pub fn iterator(&self) -> &IterGen {
&self.iterator
}
pub fn iterator_mut(&mut self) -> &mut IterGen {
&mut self.iterator
}
pub fn label_gen_mut(&mut self) -> &mut LabelGen {
&mut self.label_gen
}
pub fn local_gen_mut(&mut self) -> &mut LocalGen {
&mut self.local_gen
}
pub fn local_gen(&self) -> &LocalGen {
&self.local_gen
}
/// Initialize the named locals table. Canonical HHBC numbering
/// puts the parameters first in left-to-right order, then local varables
/// that have names from the source text. In HHAS those names must appear
/// in the `.decl_vars` directive.
pub fn init_named_locals(&mut self, names: impl IntoIterator<Item = Str<'arena>>) {
assert!(self.named_locals.is_empty());
self.named_locals = names.into_iter().collect();
}
pub fn clear_named_locals(&mut self) {
self.named_locals = Default::default();
}
/// Given a name, return corresponding local. Panic if the local is unknown,
/// indicating a logic bug in the compiler; all params and named locals must
/// be provided in advance to init_named_locals().
pub fn named_local(&self, name: Str<'_>) -> Local {
match self.named_locals.get_index_of(&name).map(Local::new) {
Some(local) => local,
None => panic!(
"{}: local not found among {:#?}",
name.unsafe_as_str(),
self.named_locals
.iter()
.map(|name| name.unsafe_as_str())
.collect::<Vec<_>>()
),
}
}
/// Given a named local, return its name. Panic for unnamed locals
/// indicating a logic bug in the compiler.
pub fn local_name(&self, local: Local) -> &Str<'_> {
self.named_locals.get_index(local.idx as usize).unwrap()
}
pub fn local_scope<R, F: FnOnce(&mut Self) -> R>(&mut self, f: F) -> R {
let counter = self.local_gen.counter;
self.local_gen.dedicated.temp_map.push();
let r = f(self);
self.local_gen.counter = counter;
self.local_gen.dedicated.temp_map.pop();
r
}
pub fn systemlib(&self) -> bool {
self.systemlib
}
pub fn adata_state(&self) -> &AdataState<'arena> {
self.adata_state.as_ref().expect("uninit'd adata_state")
}
pub fn adata_state_mut(&mut self) -> &mut AdataState<'arena> {
self.adata_state.get_or_insert_with(Default::default)
}
pub fn statement_state(&self) -> &StatementState<'arena> {
self.statement_state_
.as_ref()
.expect("uninit'd statement_state")
}
pub fn statement_state_mut(&mut self) -> &mut StatementState<'arena> {
self.statement_state_
.get_or_insert_with(StatementState::init)
}
pub fn global_state(&self) -> &GlobalState<'arena> {
self.global_state_.as_ref().expect("uninit'd global_state")
}
pub fn global_state_mut(&mut self) -> &mut GlobalState<'arena> {
self.global_state_.get_or_insert_with(GlobalState::init)
}
pub fn add_include_ref(&mut self, inc: IncludePath<'arena>) {
match inc {
IncludePath::SearchPathRelative(p)
| IncludePath::DocRootRelative(p)
| IncludePath::Absolute(p) => {
let path = Path::new(OsStr::from_bytes(&p));
if path.exists() {
self.symbol_refs_state.includes.insert(inc);
}
}
IncludePath::IncludeRootRelative(_, _) => {}
};
}
pub fn add_constant_ref(&mut self, s: ConstName<'arena>) {
if !s.is_empty() {
self.symbol_refs_state.constants.insert(s);
}
}
pub fn add_class_ref(&mut self, s: ClassName<'arena>) {
if !s.is_empty() {
self.symbol_refs_state.classes.insert(s);
}
}
pub fn add_function_ref(&mut self, s: FunctionName<'arena>) {
if !s.is_empty() {
self.symbol_refs_state.functions.insert(s);
}
}
pub fn finish_symbol_refs(&mut self) -> SymbolRefs<'arena> {
let state = std::mem::take(&mut self.symbol_refs_state);
state.to_hhas(self.alloc)
}
}
impl<'arena, 'decl> print_expr::SpecialClassResolver for Emitter<'arena, 'decl> {
fn resolve<'a>(&self, env: Option<&'a HhasBodyEnv<'_>>, id: &'a str) -> Cow<'a, str> {
let class_expr = match env {
None => ClassExpr::expr_to_class_expr_(
self,
true,
true,
None,
None,
ast::Expr(
(),
Pos::NONE,
ast::Expr_::mk_id(ast_defs::Id(Pos::NONE, id.into())),
),
),
Some(body_env) => ClassExpr::expr_to_class_expr_(
self,
true,
true,
body_env.class_info.as_ref().map(|(k, s)| (k.clone(), *s)),
body_env.parent_name.clone().map(|s| s.to_owned()),
ast::Expr(
(),
Pos::NONE,
ast::Expr_::mk_id(ast_defs::Id(Pos::NONE, id.into())),
),
),
};
match class_expr {
ClassExpr::Id(ast_defs::Id(_, name)) => Cow::Owned(name),
_ => Cow::Borrowed(id),
}
}
}
#[derive(Clone, Debug, Default)]
struct SymbolRefsState<'arena> {
includes: IncludePathSet<'arena>,
constants: BTreeSet<ConstName<'arena>>,
functions: BTreeSet<FunctionName<'arena>>,
classes: BTreeSet<ClassName<'arena>>,
}
impl<'arena> SymbolRefsState<'arena> {
fn to_hhas(self, alloc: &'arena bumpalo::Bump) -> SymbolRefs<'arena> {
SymbolRefs {
includes: Slice::new(alloc.alloc_slice_fill_iter(self.includes.into_iter())),
constants: Slice::new(alloc.alloc_slice_fill_iter(self.constants.into_iter())),
functions: Slice::new(alloc.alloc_slice_fill_iter(self.functions.into_iter())),
classes: Slice::new(alloc.alloc_slice_fill_iter(self.classes.into_iter())),
}
}
} |
Rust | hhvm/hphp/hack/src/hackc/emitter/emit_adata.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use env::emitter::Emitter;
use error::Error;
use error::Result;
use hhbc::AdataId;
use hhbc::ClassName;
use hhbc::TypedValue;
use instruction_sequence::instr;
use instruction_sequence::InstrSeq;
pub fn typed_value_into_instr<'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
tv: TypedValue<'arena>,
) -> Result<InstrSeq<'arena>> {
match tv {
TypedValue::Uninit => Err(Error::unrecoverable("rewrite_typed_value: uninit")),
TypedValue::Null => Ok(instr::null()),
TypedValue::Bool(true) => Ok(instr::true_()),
TypedValue::Bool(false) => Ok(instr::false_()),
TypedValue::Int(i) => Ok(instr::int(i)),
TypedValue::String(s) => Ok(instr::string(e.alloc, s.unsafe_as_str())),
TypedValue::LazyClass(s) => {
let classid = ClassName::from_ast_name_and_mangle(e.alloc, s.unsafe_as_str());
Ok(instr::lazy_class(classid))
}
TypedValue::Float(f) => Ok(instr::double(f)),
TypedValue::Keyset(_) => {
let arrayid = get_array_identifier(e, tv);
Ok(instr::keyset(arrayid))
}
TypedValue::Vec(_) => {
let arrayid = get_array_identifier(e, tv);
Ok(instr::vec(arrayid))
}
TypedValue::Dict(_) => {
let arrayid = get_array_identifier(e, tv);
Ok(instr::dict(arrayid))
}
}
}
fn get_array_identifier<'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
tv: TypedValue<'arena>,
) -> AdataId<'arena> {
let alloc = e.alloc;
if e.options().hhbc.array_provenance {
e.adata_state_mut().push(alloc, tv)
} else {
e.adata_state_mut().intern(alloc, tv)
}
} |
Rust | hhvm/hphp/hack/src/hackc/emitter/emit_attribute.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use env::emitter::Emitter;
use env::Env;
use error::Error;
use error::Result;
use hhbc::Attribute;
use hhbc::TypedValue;
use naming_special_names::user_attributes as ua;
use naming_special_names_rust as naming_special_names;
use oxidized::aast::Expr;
use oxidized::aast::Expr_;
use oxidized::ast as a;
use crate::emit_expression;
pub fn from_asts<'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
attrs: &[a::UserAttribute],
) -> Result<Vec<Attribute<'arena>>> {
attrs.iter().map(|attr| from_ast(e, attr)).collect()
}
pub fn from_ast<'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
attr: &a::UserAttribute,
) -> Result<Attribute<'arena>> {
let mut arguments: Vec<Expr<_, _>> = attr
.params
.iter()
.map(|param| {
// Treat enum class label syntax Foo#Bar as "Bar" in attribute arguments.
if let Expr_::EnumClassLabel(ecl) = ¶m.2 {
let label = &ecl.1;
Expr(
param.0,
param.1.clone(),
Expr_::String(label.clone().into()),
)
} else {
param.clone()
}
})
.collect();
let arguments = constant_folder::literals_from_exprs(&mut arguments, e).map_err(|err| {
assert_eq!(
err,
constant_folder::Error::UserDefinedConstant,
"literals_from_expr should have panicked for an error other than UserDefinedConstant"
);
Error::fatal_parse(&attr.name.0, "Attribute arguments must be literals")
})?;
let fully_qualified_id = if attr.name.1.starts_with("__") {
// don't do anything to builtin attributes
&attr.name.1
} else {
hhbc::ClassName::from_ast_name_and_mangle(e.alloc, &attr.name.1).unsafe_as_str()
};
Ok(Attribute {
name: e.alloc.alloc_str(fully_qualified_id).into(),
arguments: e.alloc.alloc_slice_fill_iter(arguments.into_iter()).into(),
})
}
/// Adds an __Reified attribute for functions and classes with reified type
/// parameters. The arguments to __Reified are number of type parameters
/// followed by the indicies of these reified type parameters and whether they
/// are soft reified or not
pub fn add_reified_attribute<'arena>(
alloc: &'arena bumpalo::Bump,
tparams: &[a::Tparam],
) -> Option<Attribute<'arena>> {
let reified_data: Vec<(usize, bool, bool)> = tparams
.iter()
.enumerate()
.filter_map(|(i, tparam)| {
if tparam.reified == a::ReifyKind::Erased {
None
} else {
let soft = tparam.user_attributes.iter().any(|a| a.name.1 == ua::SOFT);
let warn = tparam.user_attributes.iter().any(|a| a.name.1 == ua::WARN);
Some((i, soft, warn))
}
})
.collect();
if reified_data.is_empty() {
return None;
}
let name = "__Reified".into();
let bool2i64 = |b| b as i64;
// NOTE(hrust) hopefully faster than .into_iter().flat_map(...).collect()
let mut arguments =
bumpalo::collections::vec::Vec::with_capacity_in(reified_data.len() * 3 + 1, alloc);
arguments.push(TypedValue::Int(tparams.len() as i64));
for (i, soft, warn) in reified_data.into_iter() {
arguments.push(TypedValue::Int(i as i64));
arguments.push(TypedValue::Int(bool2i64(soft)));
arguments.push(TypedValue::Int(bool2i64(warn)));
}
Some(Attribute {
name,
arguments: arguments.into_bump_slice().into(),
})
}
pub fn add_reified_parent_attribute<'a, 'arena>(
env: &Env<'a, 'arena>,
extends: &[a::Hint],
) -> Option<Attribute<'arena>> {
if let Some((_, hl)) = extends.first().and_then(|h| h.1.as_happly()) {
if emit_expression::has_non_tparam_generics(env, hl) {
return Some(Attribute {
name: "__HasReifiedParent".into(),
arguments: ffi::Slice::empty(),
});
}
}
None
} |
Rust | hhvm/hphp/hack/src/hackc/emitter/emit_body.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::sync::Arc;
use ast_scope::Scope;
use ast_scope::ScopeItem;
use bitflags::bitflags;
use emit_pos::emit_pos;
use emit_statement::emit_final_stmts;
use env::emitter::Emitter;
use env::ClassExpr;
use env::Env;
use error::Error;
use error::Result;
use ffi::Maybe;
use ffi::Maybe::*;
use ffi::Slice;
use ffi::Str;
use hash::HashSet;
use hhbc::decl_vars;
use hhbc::Body;
use hhbc::FCallArgs;
use hhbc::FCallArgsFlags;
use hhbc::IsTypeOp;
use hhbc::Label;
use hhbc::Local;
use hhbc::Param;
use hhbc::TypeInfo;
use hhbc::TypedValue;
use hhbc::UpperBound;
use hhbc_string_utils as string_utils;
use indexmap::IndexSet;
use instruction_sequence::instr;
use instruction_sequence::InstrSeq;
use oxidized::aast;
use oxidized::aast_defs::DocComment;
use oxidized::ast;
use oxidized::ast_defs;
use oxidized::namespace_env;
use oxidized::pos::Pos;
use print_expr::HhasBodyEnv;
use statement_state::StatementState;
use super::TypeRefinementInHint;
use crate::emit_expression;
use crate::emit_param;
use crate::emit_statement;
use crate::generator;
use crate::reified_generics_helpers as RGH;
static THIS: &str = "$this";
/// Optional arguments for emit_body; use Args::default() for defaults
pub struct Args<'a, 'arena> {
pub immediate_tparams: &'a Vec<ast::Tparam>,
pub class_tparam_names: &'a [&'a str],
pub ast_params: &'a Vec<ast::FunParam>,
pub ret: Option<&'a ast::Hint>,
pub pos: &'a Pos,
pub deprecation_info: &'a Option<&'a [TypedValue<'arena>]>,
pub doc_comment: Option<DocComment>,
pub default_dropthrough: Option<InstrSeq<'arena>>,
pub call_context: Option<String>,
pub flags: Flags,
}
bitflags! {
pub struct Flags: u8 {
const HAS_COEFFECTS_LOCAL = 1 << 0;
const SKIP_AWAITABLE = 1 << 1;
const MEMOIZE = 1 << 2;
const CLOSURE_BODY = 1 << 3;
const NATIVE = 1 << 4;
const ASYNC = 1 << 6;
const DEBUGGER_MODIFY_PROGRAM = 1 << 7;
}
}
pub fn emit_body<'b, 'arena, 'decl>(
alloc: &'arena bumpalo::Bump,
emitter: &mut Emitter<'arena, 'decl>,
namespace: Arc<namespace_env::Env>,
body: &'b [ast::Stmt],
return_value: InstrSeq<'arena>,
scope: Scope<'_, 'arena>,
args: Args<'_, 'arena>,
) -> Result<(Body<'arena>, bool, bool)> {
let tparams: Vec<ast::Tparam> = scope.get_tparams().into_iter().cloned().collect();
let mut tp_names = get_tp_names(&tparams);
let (is_generator, is_pair_generator) = generator::is_function_generator(body);
emitter.label_gen_mut().reset();
emitter.iterator_mut().reset();
let return_type_info = make_return_type_info(
alloc,
args.flags.contains(Flags::SKIP_AWAITABLE),
args.flags.contains(Flags::NATIVE),
args.ret,
&tp_names,
)?;
let params = make_params(emitter, &mut tp_names, args.ast_params, &scope, args.flags)?;
let upper_bounds = emit_generics_upper_bounds(
alloc,
args.immediate_tparams,
args.class_tparam_names,
args.flags.contains(Flags::SKIP_AWAITABLE),
);
let shadowed_tparams = emit_shadowed_tparams(args.immediate_tparams, args.class_tparam_names);
let decl_vars = make_decl_vars(
emitter,
&scope,
args.immediate_tparams,
¶ms,
body,
args.flags,
)?;
let decl_vars: Vec<Str<'arena>> = decl_vars
.into_iter()
.map(|name| Str::new_str(alloc, &name))
.collect();
let mut env = make_env(alloc, namespace, scope, args.call_context);
set_emit_statement_state(
emitter,
return_value,
¶ms,
&return_type_info,
args.ret,
args.pos,
args.default_dropthrough,
args.flags,
is_generator,
);
env.jump_targets_gen.reset();
// Params are numbered starting from 0, followed by decl_vars.
let should_reserve_locals = body_contains_finally(body);
let local_gen = emitter.local_gen_mut();
let num_locals = params.len() + decl_vars.len();
local_gen.reset(Local::new(num_locals));
if should_reserve_locals {
local_gen.reserve_retval_and_label_id_locals();
};
emitter.init_named_locals(
params
.iter()
.map(|(param, _)| param.name)
.chain(decl_vars.iter().copied()),
);
let body_instrs = make_body_instrs(
emitter,
&mut env,
¶ms,
&tparams,
body,
is_generator,
args.deprecation_info.clone(),
args.pos,
args.ast_params,
args.flags,
)?;
Ok((
make_body(
alloc,
emitter,
body_instrs,
decl_vars,
false, // is_memoize_wrapper
false, // is_memoize_wrapper_lsb
upper_bounds,
shadowed_tparams,
params,
Some(return_type_info),
args.doc_comment.to_owned(),
Some(&env),
)?,
is_generator,
is_pair_generator,
))
}
fn make_body_instrs<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
params: &[(Param<'arena>, Option<(Label, ast::Expr)>)],
tparams: &[ast::Tparam],
body: &[ast::Stmt],
is_generator: bool,
deprecation_info: Option<&[TypedValue<'arena>]>,
pos: &Pos,
ast_params: &[ast::FunParam],
flags: Flags,
) -> Result<InstrSeq<'arena>> {
let stmt_instrs = if flags.contains(Flags::NATIVE) {
instr::native_impl()
} else {
env.do_function(emitter, body, emit_final_stmts)?
};
let (begin_label, default_value_setters) =
emit_param::emit_param_default_value_setter(emitter, env, pos, params)?;
let header_content = make_header_content(
emitter,
env,
params,
tparams,
is_generator,
deprecation_info,
pos,
ast_params,
flags,
)?;
let header = InstrSeq::gather(vec![begin_label, header_content]);
let mut body_instrs = InstrSeq::gather(vec![header, stmt_instrs, default_value_setters]);
if flags.contains(Flags::DEBUGGER_MODIFY_PROGRAM) {
modify_prog_for_debugger_eval(&mut body_instrs);
};
Ok(body_instrs)
}
fn make_header_content<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
params: &[(Param<'arena>, Option<(Label, ast::Expr)>)],
tparams: &[ast::Tparam],
is_generator: bool,
deprecation_info: Option<&[TypedValue<'arena>]>,
pos: &Pos,
ast_params: &[ast::FunParam],
flags: Flags,
) -> Result<InstrSeq<'arena>> {
let alloc = env.arena;
let method_prolog = if flags.contains(Flags::NATIVE) {
instr::empty()
} else {
emit_method_prolog(emitter, env, pos, params, ast_params, tparams)?
};
let deprecation_warning =
emit_deprecation_info(alloc, &env.scope, deprecation_info, emitter.systemlib())?;
let generator_info = if is_generator {
InstrSeq::gather(vec![instr::create_cont(), instr::pop_c()])
} else {
instr::empty()
};
Ok(InstrSeq::gather(vec![
method_prolog,
deprecation_warning,
generator_info,
]))
}
fn make_decl_vars<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
scope: &Scope<'a, 'arena>,
immediate_tparams: &[ast::Tparam],
params: &[(Param<'arena>, Option<(Label, ast::Expr)>)],
body: &[ast::Stmt],
arg_flags: Flags,
) -> Result<Vec<String>> {
let explicit_use_set = &emitter.global_state().explicit_use_set;
let mut decl_vars =
decl_vars::from_ast(params, body, explicit_use_set).map_err(Error::unrecoverable)?;
let mut decl_vars = if arg_flags.contains(Flags::CLOSURE_BODY) {
let mut captured_vars = scope.get_captured_vars();
move_this(&mut decl_vars);
decl_vars.retain(|v| !captured_vars.contains(v));
captured_vars.extend_from_slice(decl_vars.as_slice());
captured_vars
} else {
match scope.items() {
[] | [.., ScopeItem::Class(_), _] => move_this(&mut decl_vars),
_ => {}
};
decl_vars
};
if arg_flags.contains(Flags::HAS_COEFFECTS_LOCAL) {
decl_vars.insert(0, string_utils::coeffects::LOCAL_NAME.into());
}
if !arg_flags.contains(Flags::CLOSURE_BODY)
&& immediate_tparams
.iter()
.any(|t| t.reified != ast::ReifyKind::Erased)
{
decl_vars.insert(0, string_utils::reified::GENERICS_LOCAL_NAME.into());
}
Ok(decl_vars)
}
pub fn emit_return_type_info<'arena>(
alloc: &'arena bumpalo::Bump,
tp_names: &[&str],
skip_awaitable: bool,
ret: Option<&aast::Hint>,
) -> Result<TypeInfo<'arena>> {
match ret {
None => Ok(TypeInfo::make(Just("".into()), hhbc::Constraint::default())),
Some(hint) => emit_type_hint::hint_to_type_info(
alloc,
&emit_type_hint::Kind::Return,
skip_awaitable,
false, // nullable
tp_names,
hint,
),
}
}
fn make_return_type_info<'arena>(
alloc: &'arena bumpalo::Bump,
skip_awaitable: bool,
is_native: bool,
ret: Option<&aast::Hint>,
tp_names: &[&str],
) -> Result<TypeInfo<'arena>> {
let return_type_info = emit_return_type_info(alloc, tp_names, skip_awaitable, ret);
if is_native {
return return_type_info.map(|rti| {
emit_type_hint::emit_type_constraint_for_native_function(alloc, tp_names, ret, rti)
});
};
return_type_info
}
pub fn make_env<'a, 'arena>(
alloc: &'arena bumpalo::Bump,
namespace: Arc<namespace_env::Env>,
scope: Scope<'a, 'arena>,
call_context: Option<String>,
) -> Env<'a, 'arena> {
let mut env = Env::default(alloc, namespace);
env.call_context = call_context;
env.scope = scope;
env
}
fn make_params<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
tp_names: &mut Vec<&str>,
ast_params: &[ast::FunParam],
scope: &Scope<'a, 'arena>,
flags: Flags,
) -> Result<Vec<(Param<'arena>, Option<(Label, ast::Expr)>)>> {
let generate_defaults = !flags.contains(Flags::MEMOIZE);
emit_param::from_asts(emitter, tp_names, generate_defaults, scope, ast_params)
}
pub fn make_body<'a, 'arena, 'decl>(
alloc: &'arena bumpalo::Bump,
emitter: &mut Emitter<'arena, 'decl>,
mut body_instrs: InstrSeq<'arena>,
decl_vars: Vec<Str<'arena>>,
is_memoize_wrapper: bool,
is_memoize_wrapper_lsb: bool,
upper_bounds: Vec<UpperBound<'arena>>,
shadowed_tparams: Vec<String>,
mut params: Vec<(Param<'arena>, Option<(Label, ast::Expr)>)>,
return_type_info: Option<TypeInfo<'arena>>,
doc_comment: Option<DocComment>,
opt_env: Option<&Env<'a, 'arena>>,
) -> Result<Body<'arena>> {
if emitter.options().compiler_flags.relabel {
label_rewriter::relabel_function(alloc, &mut params, &mut body_instrs);
}
let num_iters = if is_memoize_wrapper {
0
} else {
emitter.iterator().count()
};
let body_env = if let Some(env) = opt_env {
let is_namespaced = env.namespace.name.is_none();
if let Some(cd) = env.scope.get_class() {
Some(HhasBodyEnv {
is_namespaced,
class_info: Some((cd.get_kind().into(), cd.get_name_str())),
parent_name: ClassExpr::get_parent_class_name(cd),
})
} else {
Some(HhasBodyEnv {
is_namespaced,
class_info: None,
parent_name: None,
})
}
} else {
None
};
// Pretty-print the DV initializer expression as a Hack source code string,
// to make it available for reflection.
params.iter_mut().for_each(|(p, default_value)| {
p.default_value = Maybe::from(default_value.as_ref().map(|(label, expr)| {
use print_expr::Context;
use print_expr::ExprEnv;
let ctx = Context::new(emitter);
let expr_env = ExprEnv {
codegen_env: body_env.as_ref(),
};
let mut buf = Vec::new();
let expr = print_expr::print_expr(&ctx, &mut buf, &expr_env, expr).map_or_else(
|e| Str::new_str(alloc, &e.to_string()),
|_| Str::from_vec(alloc, buf),
);
hhbc::DefaultValue {
label: *label,
expr,
}
}));
});
// Now that we're done with this function, clear the named_local table.
emitter.clear_named_locals();
let params = Slice::fill_iter(alloc, params.into_iter().map(|(p, _)| p));
let body_instrs = body_instrs.compact(alloc);
let stack_depth = stack_depth::compute_stack_depth(params.as_ref(), body_instrs.as_ref())
.map_err(error::Error::from_error)?;
Ok(Body {
body_instrs,
decl_vars: Slice::fill_iter(alloc, decl_vars.into_iter()),
num_iters,
is_memoize_wrapper,
is_memoize_wrapper_lsb,
upper_bounds: Slice::fill_iter(alloc, upper_bounds.into_iter()),
shadowed_tparams: Slice::fill_iter(
alloc,
shadowed_tparams
.into_iter()
.map(|s| Str::new_str(alloc, &s)),
),
params,
return_type_info: return_type_info.into(),
doc_comment: doc_comment.map(|c| Str::new_str(alloc, &c.1)).into(),
stack_depth,
})
}
pub fn has_type_constraint<'a, 'arena>(
env: &Env<'a, 'arena>,
ti: Option<&TypeInfo<'_>>,
ast_param: &ast::FunParam,
) -> (RGH::ReificationLevel, Option<ast::Hint>) {
use RGH::ReificationLevel as L;
match (ti, &ast_param.type_hint.1) {
(Some(ti), Some(h)) if ti.has_type_constraint() => {
// TODO(hrust): how to avoid clone on h
let h = RGH::remove_erased_generics(env, h.clone());
(RGH::has_reified_type_constraint(env, &h), Some(h))
}
_ => (L::Unconstrained, None),
}
}
pub fn emit_method_prolog<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
pos: &Pos,
params: &[(Param<'arena>, Option<(Label, ast::Expr)>)],
ast_params: &[ast::FunParam],
tparams: &[ast::Tparam],
) -> Result<InstrSeq<'arena>> {
let mut make_param_instr =
|param: &Param<'arena>, ast_param: &ast::FunParam| -> Result<InstrSeq<'arena>> {
if param.is_variadic {
Ok(instr::empty())
} else {
use RGH::ReificationLevel as L;
let param_local = emitter.named_local(param.name);
match has_type_constraint(env, Option::from(param.type_info.as_ref()), ast_param) {
(L::Unconstrained, _) => Ok(instr::empty()),
(L::Not, _) => Ok(instr::empty()),
(L::Maybe, Some(h)) => {
if !RGH::happly_decl_has_reified_generics(env, emitter, &h) {
Ok(instr::empty())
} else {
Ok(InstrSeq::gather(vec![
emit_expression::get_type_structure_for_hint(
emitter,
tparams
.iter()
.map(|fp| fp.name.1.as_str())
.collect::<Vec<_>>()
.as_slice(),
&IndexSet::new(),
TypeRefinementInHint::Allowed,
&h,
)?,
instr::verify_param_type_ts(param_local),
]))
}
}
(L::Definitely, Some(h)) => {
if !RGH::happly_decl_has_reified_generics(env, emitter, &h) {
Ok(instr::empty())
} else {
let check =
instr::is_type_l(emitter.named_local(param.name), IsTypeOp::Null);
let verify_instr = instr::verify_param_type_ts(param_local);
RGH::simplify_verify_type(emitter, env, pos, check, &h, verify_instr)
}
}
_ => Err(Error::unrecoverable("impossible")),
}
}
};
let ast_params = ast_params
.iter()
.filter(|p| !(p.is_variadic && p.name == "..."))
.collect::<Vec<_>>();
if params.len() != ast_params.len() {
return Err(Error::unrecoverable("length mismatch"));
}
let mut instrs = Vec::with_capacity(1 + params.len());
instrs.push(emit_pos(pos));
for ((param, _), ast_param) in params.iter().zip(ast_params.into_iter()) {
instrs.push(make_param_instr(param, ast_param)?);
}
Ok(InstrSeq::gather(instrs))
}
pub fn emit_deprecation_info<'a, 'arena>(
alloc: &'arena bumpalo::Bump,
scope: &Scope<'a, 'arena>,
deprecation_info: Option<&[TypedValue<'arena>]>,
is_systemlib: bool,
) -> Result<InstrSeq<'arena>> {
Ok(match deprecation_info {
None => instr::empty(),
Some(args) => {
fn strip_id<'a>(id: &'a ast::Id) -> &'a str {
string_utils::strip_global_ns(id.1.as_str())
}
let (class_name, trait_instrs, concat_instruction): (String, _, _) =
match scope.get_class() {
None => ("".into(), instr::empty(), instr::empty()),
Some(c) if c.get_kind() == ast::ClassishKind::Ctrait => (
"::".into(),
InstrSeq::gather(vec![instr::self_cls(), instr::class_name()]),
instr::concat(),
),
Some(c) => (
strip_id(c.get_name()).to_string() + "::",
instr::empty(),
instr::empty(),
),
};
let fn_name = match scope.top() {
Some(ScopeItem::Function(f)) => strip_id(f.get_name()),
Some(ScopeItem::Method(m)) => strip_id(m.get_name()),
_ => {
return Err(Error::unrecoverable("deprecated functions must have names"));
}
};
let deprecation_string = class_name
+ fn_name
+ ": "
+ (if args.is_empty() {
"deprecated function"
} else if let TypedValue::String(s) = &args[0] {
s.unsafe_as_str()
} else {
return Err(Error::unrecoverable(
"deprecated attribute first argument is not a string",
));
});
let sampling_rate = if args.len() <= 1 {
1i64
} else if let Some(TypedValue::Int(i)) = args.get(1) {
*i
} else {
return Err(Error::unrecoverable(
"deprecated attribute second argument is not an integer",
));
};
let error_code = if is_systemlib {
/*E_DEPRECATED*/
8192
} else {
/*E_USER_DEPRECATED*/
16384
};
if sampling_rate <= 0 {
instr::empty()
} else {
InstrSeq::gather(vec![
instr::null_uninit(),
instr::null_uninit(),
trait_instrs,
instr::string(alloc, deprecation_string),
concat_instruction,
instr::int(sampling_rate),
instr::int(error_code),
instr::f_call_func_d(
FCallArgs::new(
FCallArgsFlags::default(),
1,
3,
Slice::empty(),
Slice::empty(),
None,
None,
),
hhbc::FunctionName::from_raw_string(alloc, "trigger_sampled_error"),
),
instr::pop_c(),
])
}
}
})
}
fn set_emit_statement_state<'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
default_return_value: InstrSeq<'arena>,
params: &[(Param<'arena>, Option<(Label, ast::Expr)>)],
return_type_info: &TypeInfo<'_>,
return_type: Option<&ast::Hint>,
pos: &Pos,
default_dropthrough: Option<InstrSeq<'arena>>,
flags: Flags,
is_generator: bool,
) {
let verify_return = match &return_type_info.user_type {
Just(s) if s.unsafe_as_str() == "" => None,
_ if return_type_info.has_type_constraint() && !is_generator => return_type.cloned(),
_ => None,
};
let default_dropthrough = if default_dropthrough.is_some() {
default_dropthrough
} else if flags.contains(Flags::ASYNC) && verify_return.is_some() {
Some(InstrSeq::gather(vec![
instr::null(),
instr::verify_ret_type_c(),
instr::ret_c(),
]))
} else {
None
};
let (num_out, verify_out) = emit_verify_out(params);
emit_statement::set_state(
emitter,
StatementState {
verify_return,
default_return_value,
default_dropthrough,
verify_out,
function_pos: pos.clone(),
num_out,
},
)
}
fn emit_verify_out<'arena>(
params: &[(Param<'arena>, Option<(Label, ast::Expr)>)],
) -> (usize, InstrSeq<'arena>) {
let param_instrs: Vec<InstrSeq<'arena>> = params
.iter()
.enumerate()
.filter_map(|(i, (p, _))| {
if p.is_inout {
let local = Local::new(i);
Some(InstrSeq::gather(vec![
instr::c_get_l(local),
match p.type_info.as_ref() {
Just(TypeInfo { user_type, .. })
if user_type.as_ref().map_or(true, |t| {
!(t.unsafe_as_str().ends_with("HH\\mixed")
|| t.unsafe_as_str().ends_with("HH\\dynamic"))
}) =>
{
instr::verify_out_type(local)
}
_ => instr::empty(),
},
]))
} else {
None
}
})
.collect();
(
param_instrs.len(),
InstrSeq::gather(param_instrs.into_iter().rev().collect()),
)
}
pub fn emit_generics_upper_bounds<'arena>(
alloc: &'arena bumpalo::Bump,
immediate_tparams: &[ast::Tparam],
class_tparam_names: &[&str],
skip_awaitable: bool,
) -> Vec<UpperBound<'arena>> {
let constraint_filter = |(kind, hint): &(ast_defs::ConstraintKind, ast::Hint)| {
if let ast_defs::ConstraintKind::ConstraintAs = &kind {
let mut tparam_names = get_tp_names(immediate_tparams);
tparam_names.extend_from_slice(class_tparam_names);
emit_type_hint::hint_to_type_info(
alloc,
&emit_type_hint::Kind::UpperBound,
skip_awaitable,
false, // nullable
&tparam_names,
hint,
)
.ok() //TODO(hrust) propagate Err result
} else {
None
}
};
let tparam_filter = |tparam: &ast::Tparam| {
let ubs = tparam
.constraints
.iter()
.filter_map(constraint_filter)
.collect::<Vec<_>>();
match &ubs[..] {
[] => None,
_ => Some(UpperBound {
name: Str::new_str(alloc, get_tp_name(tparam)),
bounds: Slice::fill_iter(alloc, ubs.into_iter()),
}),
}
};
immediate_tparams
.iter()
.filter_map(tparam_filter)
.collect::<Vec<_>>()
}
fn emit_shadowed_tparams(
immediate_tparams: &[ast::Tparam],
class_tparam_names: &[&str],
) -> Vec<String> {
let s1 = get_tp_names_set(immediate_tparams);
let s2: HashSet<&str> = class_tparam_names.iter().cloned().collect();
// TODO(hrust): remove sort after Rust emitter released
let mut r = s1
.intersection(&s2)
.map(|s| (*s).into())
.collect::<Vec<_>>();
r.sort();
r
}
fn move_this(vars: &mut Vec<String>) {
if vars.iter().any(|v| v == THIS) {
vars.retain(|s| s != THIS);
vars.push(String::from(THIS));
}
}
fn get_tp_name(tparam: &ast::Tparam) -> &str {
let ast_defs::Id(_, name) = &tparam.name;
name
}
pub fn get_tp_names(tparams: &[ast::Tparam]) -> Vec<&str> {
tparams.iter().map(get_tp_name).collect()
}
pub fn get_tp_names_set(tparams: &[ast::Tparam]) -> HashSet<&str> {
tparams.iter().map(get_tp_name).collect()
}
fn modify_prog_for_debugger_eval<'arena>(_body_instrs: &mut InstrSeq<'arena>) {
unimplemented!() // SF(2021-03-17): I found it like this.
}
/// Scan through the AST looking to see if the body contains a non-empty
/// `finally` clause (or a `using` which is morally equivalent).
fn body_contains_finally(body: &[ast::Stmt]) -> bool {
struct V {
has_finally: bool,
}
use oxidized::aast_visitor::AstParams;
use oxidized::aast_visitor::Node;
use oxidized::aast_visitor::Visitor;
use oxidized::ast::Expr_;
use oxidized::ast::Stmt_;
impl<'a> Visitor<'a> for V {
type Params = AstParams<(), ()>;
fn object(&mut self) -> &mut dyn Visitor<'a, Params = Self::Params> {
self
}
fn visit_stmt_(&mut self, c: &mut (), p: &Stmt_) -> Result<(), ()> {
match p {
Stmt_::Try(x) => {
let (_, _, b2) = &**x;
if !b2.is_empty() {
self.has_finally = true;
// Not a real error - just early out.
return Err(());
}
}
Stmt_::Using(_) => {
self.has_finally = true;
// Not a real error - just early out.
return Err(());
}
_ => {}
}
p.recurse(c, self.object())
}
fn visit_expr_(&mut self, c: &mut (), p: &Expr_) -> Result<(), ()> {
// It's probably good enough to only check the stack on Expr_ since
// that's where we can get really deep.
stack_limit::maybe_grow(|| {
match p {
Expr_::Efun(_) | Expr_::Lfun(_) => {
// Don't recurse into lambda bodies.
Ok(())
}
_ => p.recurse(c, self.object()),
}
})
}
}
let mut v = V { has_finally: false };
let _ = body.recurse(&mut (), &mut v);
v.has_finally
} |
Rust | hhvm/hphp/hack/src/hackc/emitter/emit_class.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::collections::BTreeMap;
use emit_property::PropAndInit;
use env::emitter::Emitter;
use env::Env;
use error::Error;
use error::Result;
use ffi::Maybe;
use ffi::Maybe::*;
use ffi::Slice;
use ffi::Str;
use hhbc::Class;
use hhbc::ClassName;
use hhbc::Coeffects;
use hhbc::Constant;
use hhbc::CtxConstant;
use hhbc::FCallArgs;
use hhbc::FCallArgsFlags;
use hhbc::FatalOp;
use hhbc::Local;
use hhbc::Method;
use hhbc::MethodFlags;
use hhbc::Param;
use hhbc::Property;
use hhbc::ReadonlyOp;
use hhbc::Requirement;
use hhbc::Span;
use hhbc::SpecialClsRef;
use hhbc::TraitReqKind;
use hhbc::TypeConstant;
use hhbc::TypeInfo;
use hhbc::TypedValue;
use hhbc::Visibility;
use hhbc_string_utils as string_utils;
use hhvm_types_ffi::ffi::Attr;
use hhvm_types_ffi::ffi::TypeConstraintFlags;
use instruction_sequence::instr;
use instruction_sequence::InstrSeq;
use itertools::Itertools;
use oxidized::ast;
use oxidized::ast::ClassReq;
use oxidized::ast::Hint;
use oxidized::ast::ReifyKind;
use oxidized::ast::RequireKind;
use super::TypeRefinementInHint;
use crate::emit_adata;
use crate::emit_attribute;
use crate::emit_body;
use crate::emit_constant;
use crate::emit_expression;
use crate::emit_memoize_method;
use crate::emit_method;
use crate::emit_property;
use crate::emit_type_constant;
use crate::emit_xhp;
use crate::xhp_attribute::XhpAttribute;
fn add_symbol_refs<'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
base: Option<&ClassName<'arena>>,
implements: &[ClassName<'arena>],
uses: &[ClassName<'arena>],
requirements: &[hhbc::Requirement<'arena>],
) {
base.iter().for_each(|&x| emitter.add_class_ref(*x));
implements.iter().for_each(|x| emitter.add_class_ref(*x));
uses.iter().for_each(|x| emitter.add_class_ref(*x));
requirements
.iter()
.for_each(|r| emitter.add_class_ref(r.name));
}
fn make_86method<'arena, 'decl>(
alloc: &'arena bumpalo::Bump,
emitter: &mut Emitter<'arena, 'decl>,
name: hhbc::MethodName<'arena>,
params: Vec<Param<'arena>>,
is_static: bool,
visibility: Visibility,
is_abstract: bool,
span: Span,
coeffects: Coeffects<'arena>,
instrs: InstrSeq<'arena>,
) -> Result<Method<'arena>> {
// TODO: move this. We just know that there are no iterators in 86methods
emitter.iterator_mut().reset();
let mut attrs = Attr::AttrNone;
attrs.add(Attr::AttrNoInjection);
attrs.set(Attr::AttrAbstract, is_abstract);
attrs.set(Attr::AttrStatic, is_static);
attrs.set(Attr::AttrBuiltin, emitter.systemlib());
attrs.set(Attr::AttrPersistent, emitter.systemlib());
attrs.add(Attr::from(visibility));
let attributes = vec![];
let flags = MethodFlags::empty();
let method_decl_vars = vec![];
let method_return_type = None;
let method_doc_comment = None;
let method_is_memoize_wrapper = false;
let method_is_memoize_wrapper_lsb = false;
let method_env = None;
let body = emit_body::make_body(
alloc,
emitter,
instrs,
method_decl_vars,
method_is_memoize_wrapper,
method_is_memoize_wrapper_lsb,
vec![],
vec![],
params.into_iter().map(|p| (p, None)).collect::<Vec<_>>(),
method_return_type,
method_doc_comment,
method_env,
)?;
Ok(Method {
body,
attributes: Slice::fill_iter(alloc, attributes.into_iter()),
name,
flags,
span,
coeffects,
visibility,
attrs,
})
}
fn from_extends<'arena>(
alloc: &'arena bumpalo::Bump,
is_enum: bool,
is_enum_class: bool,
is_abstract: bool,
extends: &[ast::Hint],
) -> Option<ClassName<'arena>> {
if is_enum {
// Do not use special_names:: as there's a prefix \ which breaks HHVM
if is_enum_class {
if is_abstract {
Some(ClassName::from_raw_string(
alloc,
"HH\\BuiltinAbstractEnumClass",
))
} else {
Some(ClassName::from_raw_string(alloc, "HH\\BuiltinEnumClass"))
}
} else {
Some(ClassName::from_raw_string(alloc, "HH\\BuiltinEnum"))
}
} else {
extends
.first()
.map(|x| emit_type_hint::hint_to_class(alloc, x))
}
}
fn from_implements<'arena>(
alloc: &'arena bumpalo::Bump,
implements: &[ast::Hint],
) -> Vec<ClassName<'arena>> {
implements
.iter()
.map(|x| emit_type_hint::hint_to_class(alloc, x))
.collect()
}
fn from_includes<'arena>(
alloc: &'arena bumpalo::Bump,
includes: &[ast::Hint],
) -> Vec<ClassName<'arena>> {
includes
.iter()
.map(|x| emit_type_hint::hint_to_class(alloc, x))
.collect()
}
fn from_type_constant<'a, 'arena, 'decl>(
alloc: &'arena bumpalo::Bump,
emitter: &mut Emitter<'arena, 'decl>,
tc: &'a ast::ClassTypeconstDef,
) -> Result<TypeConstant<'arena>> {
use ast::ClassTypeconst;
let name = tc.name.1.to_string();
let initializer = match &tc.kind {
ClassTypeconst::TCAbstract(ast::ClassAbstractTypeconst { default: None, .. }) => None,
ClassTypeconst::TCAbstract(ast::ClassAbstractTypeconst {
default: Some(init),
..
})
| ClassTypeconst::TCConcrete(ast::ClassConcreteTypeconst { c_tc_type: init }) => {
// TODO: Deal with the constraint
// Type constants do not take type vars hence tparams:[]
Some(emit_type_constant::hint_to_type_constant(
alloc,
emitter.options(),
&[],
&BTreeMap::new(),
init,
TypeRefinementInHint::Disallowed,
)?)
}
};
let is_abstract = match &tc.kind {
ClassTypeconst::TCConcrete(_) => false,
_ => true,
};
Ok(TypeConstant {
name: Str::new_str(alloc, &name),
initializer: Maybe::from(initializer),
is_abstract,
})
}
fn from_ctx_constant<'a, 'arena>(
alloc: &'arena bumpalo::Bump,
tc: &'a ast::ClassTypeconstDef,
) -> Result<CtxConstant<'arena>> {
use ast::ClassTypeconst;
let name = tc.name.1.to_string();
let (recognized, unrecognized) = match &tc.kind {
ClassTypeconst::TCAbstract(ast::ClassAbstractTypeconst { default: None, .. }) => {
(Slice::empty(), Slice::empty())
}
ClassTypeconst::TCAbstract(ast::ClassAbstractTypeconst {
default: Some(hint),
..
})
| ClassTypeconst::TCConcrete(ast::ClassConcreteTypeconst { c_tc_type: hint }) => {
let x = Coeffects::from_ctx_constant(hint);
let r: Slice<'arena, Str<'_>> = Slice::from_vec(
alloc,
x.0.iter()
.map(|ctx| Str::new_str(alloc, &ctx.to_string()))
.collect(),
);
let u: Slice<'arena, Str<'_>> =
Slice::from_vec(alloc, x.1.iter().map(|s| Str::new_str(alloc, s)).collect());
(r, u)
}
};
let is_abstract = match &tc.kind {
ClassTypeconst::TCConcrete(_) => false,
_ => true,
};
Ok(CtxConstant {
name: Str::new_str(alloc, &name),
recognized,
unrecognized,
is_abstract,
})
}
fn from_class_elt_classvars<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
ast_class: &'a ast::Class_,
class_is_const: bool,
tparams: &[&str],
is_closure: bool,
) -> Result<Vec<PropAndInit<'arena>>> {
// TODO: we need to emit doc comments for each property,
// not one per all properties on the same line
// The doc comment is only for the first name in the list.
// Currently this is organized in the ast_to_nast module
ast_class
.vars
.iter()
.map(|cv| {
let hint = if cv.is_promoted_variadic {
None
} else {
cv.type_.1.as_ref()
};
emit_property::from_ast(
emitter,
ast_class,
tparams,
class_is_const,
is_closure,
emit_property::FromAstArgs {
user_attributes: &cv.user_attributes,
id: &cv.id,
initial_value: &cv.expr,
typehint: hint,
// Doc comments are weird. T40098274
doc_comment: cv.doc_comment.clone(),
visibility: cv.visibility, // This used to be cv_kinds
is_static: cv.is_static,
is_abstract: cv.abstract_,
is_readonly: cv.readonly,
},
)
})
.collect()
}
fn from_class_elt_constants<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
class_: &'a ast::Class_,
) -> Result<Vec<(Constant<'arena>, Option<InstrSeq<'arena>>)>> {
use oxidized::aast::ClassConstKind;
class_
.consts
.iter()
.map(|x| {
// start unnamed local numbers at 1 for constants to not clobber $constVars
emitter.local_gen_mut().reset(Local::new(1));
let (is_abstract, init_opt) = match &x.kind {
ClassConstKind::CCAbstract(default) => (true, default.as_ref()),
ClassConstKind::CCConcrete(expr) => (false, Some(expr)),
};
emit_constant::from_ast(emitter, env, &x.id, is_abstract, init_opt)
})
.collect()
}
fn from_class_elt_requirements<'a, 'arena>(
alloc: &'arena bumpalo::Bump,
class_: &'a ast::Class_,
) -> Vec<Requirement<'arena>> {
class_
.reqs
.iter()
.map(|ClassReq(h, req_kind)| {
let name = emit_type_hint::hint_to_class(alloc, h);
let kind = match *req_kind {
RequireKind::RequireExtends => TraitReqKind::MustExtend,
RequireKind::RequireImplements => TraitReqKind::MustImplement,
RequireKind::RequireClass => TraitReqKind::MustBeClass,
};
Requirement { name, kind }
})
.collect()
}
fn from_enum_type<'arena>(
alloc: &'arena bumpalo::Bump,
opt: Option<&ast::Enum_>,
) -> Result<Option<TypeInfo<'arena>>> {
use hhbc::Constraint;
opt.map(|e| {
let type_info_user_type = Just(Str::new_str(
alloc,
&emit_type_hint::fmt_hint(alloc, &[], true, &e.base)?,
));
let type_info_type_constraint =
Constraint::make(Nothing, TypeConstraintFlags::ExtendedHint);
Ok(TypeInfo::make(
type_info_user_type,
type_info_type_constraint,
))
})
.transpose()
}
fn emit_reified_extends_params<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
ast_class: &'a ast::Class_,
) -> Result<InstrSeq<'arena>> {
match &ast_class.extends[..] {
[h, ..] => match h.1.as_happly() {
Some((_, l)) if !l.is_empty() => {
return Ok(InstrSeq::gather(vec![
emit_expression::emit_reified_targs(e, env, &ast_class.span, l.iter())?,
instr::record_reified_generic(),
]));
}
_ => {}
},
_ => {}
}
let tv = TypedValue::Vec(Slice::empty());
emit_adata::typed_value_into_instr(e, tv)
}
fn emit_reified_init_body<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
num_reified: usize,
ast_class: &'a ast::Class_,
init_meth_param_local: Local,
) -> Result<InstrSeq<'arena>> {
use string_utils::reified::INIT_METH_NAME;
use string_utils::reified::PROP_NAME;
let alloc = env.arena;
let check_length = InstrSeq::gather(vec![
instr::c_get_l(init_meth_param_local),
instr::check_cls_reified_generic_mismatch(),
]);
let set_prop = if num_reified == 0 {
instr::empty()
} else {
InstrSeq::gather(vec![
check_length,
instr::check_this(),
instr::c_get_l(init_meth_param_local),
instr::base_h(),
instr::set_m_pt(
0,
hhbc::PropName::from_raw_string(alloc, PROP_NAME),
ReadonlyOp::Any,
),
instr::pop_c(),
])
};
let return_instr = InstrSeq::gather(vec![instr::null(), instr::ret_c()]);
Ok(if ast_class.extends.is_empty() {
InstrSeq::gather(vec![set_prop, return_instr])
} else {
let generic_arr = emit_reified_extends_params(e, env, ast_class)?;
let call_parent = InstrSeq::gather(vec![
instr::null_uninit(),
instr::null_uninit(),
generic_arr,
instr::f_call_cls_method_sd(
FCallArgs::new(
FCallArgsFlags::default(),
1,
1,
Slice::empty(),
Slice::empty(),
None,
None,
),
SpecialClsRef::ParentCls,
hhbc::MethodName::from_raw_string(alloc, INIT_METH_NAME),
),
instr::pop_c(),
]);
InstrSeq::gather(vec![set_prop, call_parent, return_instr])
})
}
fn emit_reified_init_method<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
ast_class: &'a ast::Class_,
) -> Result<Option<Method<'arena>>> {
use hhbc::Constraint;
let alloc = env.arena;
let num_reified = ast_class
.tparams
.iter()
.filter(|x| x.reified != ReifyKind::Erased)
.count();
let maybe_has_reified_parents = match ast_class.extends.first().as_ref() {
Some(Hint(_, h)) if h.as_happly().map_or(false, |(_, l)| !l.is_empty()) => true,
_ => false, // Hack classes can only extend a single parent
};
if num_reified == 0 && !maybe_has_reified_parents {
Ok(None)
} else {
let tc = Constraint::make(Just("HH\\varray".into()), TypeConstraintFlags::NoFlags);
let param_local = Local::new(0);
let params = vec![Param {
name: Str::new_str(alloc, string_utils::reified::INIT_METH_PARAM_NAME),
is_variadic: false,
is_inout: false,
is_readonly: false,
user_attributes: Slice::empty(),
type_info: Just(TypeInfo::make(Just("HH\\varray".into()), tc)),
default_value: Nothing,
}];
let body_instrs =
emit_reified_init_body(emitter, env, num_reified, ast_class, param_local)?;
let instrs = emit_pos::emit_pos_then(&ast_class.span, body_instrs);
Ok(Some(make_86method(
alloc,
emitter,
hhbc::MethodName::new(Str::new_str(alloc, string_utils::reified::INIT_METH_NAME)),
params,
false, // is_static
Visibility::Public,
false, // is_abstract
Span::from_pos(&ast_class.span),
Coeffects::pure(alloc),
instrs,
)?))
}
}
fn make_init_method<'arena, 'decl>(
alloc: &'arena bumpalo::Bump,
emitter: &mut Emitter<'arena, 'decl>,
properties: &mut [PropAndInit<'arena>],
filter: impl Fn(&Property<'arena>) -> bool,
name: &'static str,
span: Span,
) -> Result<Option<Method<'arena>>> {
let mut has_inits = false;
let instrs = InstrSeq::gather(
properties
.iter_mut()
.filter_map(|p| match p.init {
Some(_) if filter(&p.prop) => {
has_inits = true;
p.init.take()
}
_ => None,
})
.collect(),
);
if has_inits {
let instrs = InstrSeq::gather(vec![instrs, instr::null(), instr::ret_c()]);
Ok(Some(make_86method(
alloc,
emitter,
hhbc::MethodName::new(Str::new_str(alloc, name)),
vec![],
true, // is_static
Visibility::Private,
false, // is_abstract
span,
Coeffects::pure(alloc),
instrs,
)?))
} else {
Ok(None)
}
}
pub fn emit_class<'a, 'arena, 'decl>(
alloc: &'arena bumpalo::Bump,
emitter: &mut Emitter<'arena, 'decl>,
ast_class: &'a ast::Class_,
) -> Result<Class<'arena>> {
let mut env = Env::make_class_env(alloc, ast_class);
// TODO: communicate this without looking at the name
let is_closure = ast_class.name.1.starts_with("Closure$");
let mut attributes = emit_attribute::from_asts(emitter, &ast_class.user_attributes)?;
if !is_closure {
attributes
.extend(emit_attribute::add_reified_attribute(alloc, &ast_class.tparams).into_iter());
attributes.extend(
emit_attribute::add_reified_parent_attribute(&env, &ast_class.extends).into_iter(),
)
}
let is_const = hhbc::has_const(attributes.as_ref());
// In the future, we intend to set class_no_dynamic_props independently from
// class_is_const, but for now class_is_const is the only thing that turns
// it on.
let no_dynamic_props = is_const;
let name = ClassName::from_ast_name_and_mangle(alloc, &ast_class.name.1);
let is_trait = ast_class.kind == ast::ClassishKind::Ctrait;
let is_interface = ast_class.kind == ast::ClassishKind::Cinterface;
let uses: Vec<ClassName<'arena>> = ast_class
.uses
.iter()
.filter_map(|Hint(pos, hint)| match hint.as_ref() {
ast::Hint_::Happly(ast::Id(_, name), _) => {
if is_interface {
Some(Err(Error::fatal_parse(pos, "Interfaces cannot use traits")))
} else {
Some(Ok(ClassName::from_ast_name_and_mangle(
alloc,
name.as_str(),
)))
}
}
_ => None,
})
.collect::<Result<Vec<_>>>()?
.into_iter()
.unique()
.collect();
let enum_type = if ast_class.kind.is_cenum() || ast_class.kind.is_cenum_class() {
from_enum_type(alloc, ast_class.enum_.as_ref())?
} else {
None
};
let is_enum_class = ast_class.kind.is_cenum_class();
let xhp_attributes: Vec<_> = ast_class
.xhp_attrs
.iter()
.map(
|ast::XhpAttr(type_, class_var, tag, maybe_enum)| XhpAttribute {
type_: type_.1.as_ref(),
class_var,
tag: *tag,
maybe_enum: maybe_enum.as_ref(),
},
)
.collect();
let xhp_children = ast_class.xhp_children.first().map(|(p, sl)| (p, vec![sl]));
let xhp_categories: Option<(_, Vec<_>)> = ast_class
.xhp_category
.as_ref()
.map(|(p, c)| (p, c.iter().map(|x| &x.1).collect()));
let is_abstract = match ast_class.kind {
ast::ClassishKind::Cclass(k) => k.is_abstract(),
ast::ClassishKind::CenumClass(k) => k.is_abstract(),
_ => false,
};
let is_final = ast_class.final_ || is_trait;
let is_sealed = hhbc::has_sealed(attributes.as_ref());
let tparams: Vec<&str> = ast_class
.tparams
.iter()
.map(|x| x.name.1.as_ref())
.collect();
let base = if is_interface {
None
} else {
from_extends(
alloc,
enum_type.is_some(),
is_enum_class,
is_abstract,
&ast_class.extends,
)
};
let base_is_closure = || {
base.as_ref().map_or(false, |cls| {
cls.unsafe_as_str().eq_ignore_ascii_case("closure")
})
};
if !is_closure && base_is_closure() {
return Err(Error::fatal_runtime(
&ast_class.name.0,
"Class cannot extend Closure",
));
}
let implements = if is_interface {
&ast_class.extends
} else {
&ast_class.implements
};
let implements = from_implements(alloc, implements);
let enum_includes = if ast_class.kind.is_cenum() || ast_class.kind.is_cenum_class() {
match &ast_class.enum_ {
None => vec![],
Some(enum_) => from_includes(alloc, &enum_.includes),
}
} else {
vec![]
};
let span = Span::from_pos(&ast_class.span);
let mut additional_methods: Vec<Method<'arena>> = vec![];
if let Some(cats) = xhp_categories {
additional_methods.push(emit_xhp::from_category_declaration(
emitter, ast_class, &cats,
)?)
}
if let Some(children) = xhp_children {
additional_methods.push(emit_xhp::from_children_declaration(
emitter, ast_class, &children,
)?)
}
let no_xhp_attributes = xhp_attributes.is_empty() && ast_class.xhp_attr_uses.is_empty();
if !no_xhp_attributes {
additional_methods.push(emit_xhp::from_attribute_declaration(
emitter,
ast_class,
&xhp_attributes,
&ast_class.xhp_attr_uses,
)?)
}
emitter.label_gen_mut().reset();
let mut properties =
from_class_elt_classvars(emitter, ast_class, is_const, &tparams, is_closure)?;
let mut constants = from_class_elt_constants(emitter, &env, ast_class)?;
let requirements = from_class_elt_requirements(alloc, ast_class);
let pinit_method = make_init_method(
alloc,
emitter,
&mut properties,
|p| !p.flags.is_static(),
"86pinit",
span,
)?;
let sinit_method = make_init_method(
alloc,
emitter,
&mut properties,
|p| p.flags.is_static() && !p.flags.is_lsb(),
"86sinit",
span,
)?;
let linit_method = make_init_method(
alloc,
emitter,
&mut properties,
|p| p.flags.is_static() && p.flags.is_lsb(),
"86linit",
span,
)?;
let initialized_constants: Vec<_> = constants
.iter_mut()
.filter_map(|(Constant { ref name, .. }, instrs)| {
instrs
.take()
.map(|instrs| (name, emitter.label_gen_mut().next_regular(), instrs))
})
.collect();
let cinit_method = if initialized_constants.is_empty() {
None
} else {
let param_name = Str::new_str(alloc, "$constName");
let param_local = Local::new(0);
let params = vec![Param {
name: param_name,
is_variadic: false,
is_inout: false,
is_readonly: false,
user_attributes: Slice::empty(),
type_info: Nothing, // string?
default_value: Nothing,
}];
let default_label = emitter.label_gen_mut().next_regular();
let mut cases =
bumpalo::collections::Vec::with_capacity_in(initialized_constants.len() + 1, alloc);
for (name, label, _) in &initialized_constants {
let n: &str = alloc.alloc_str((*name).unsafe_as_str());
cases.push((n, *label))
}
cases.push((alloc.alloc_str("default"), default_label));
let pos = &ast_class.span;
let instrs = InstrSeq::gather(vec![
emit_pos::emit_pos(pos),
instr::c_get_l(param_local),
instr::s_switch(alloc, cases),
InstrSeq::gather(
initialized_constants
.into_iter()
.map(|(_, label, init_instrs)| {
// one case for each constant
InstrSeq::gather(vec![
instr::label(label),
init_instrs,
emit_pos::emit_pos(pos),
instr::ret_c(),
])
})
.collect(),
),
// default case for constant-not-found
instr::label(default_label),
emit_pos::emit_pos(pos),
instr::string(alloc, "Could not find initializer for "),
instr::c_get_l(param_local),
instr::string(alloc, " in 86cinit"),
instr::concat_n(3),
instr::fatal(FatalOp::Runtime),
]);
Some(make_86method(
alloc,
emitter,
hhbc::MethodName::new(Str::new_str(alloc, "86cinit")),
params,
true, /* is_static */
Visibility::Private,
is_interface, /* is_abstract */
span,
Coeffects::default(),
instrs,
)?)
};
let should_emit_reified_init = !(emitter.systemlib() || is_closure || is_interface || is_trait);
let reified_init_method = if should_emit_reified_init {
emit_reified_init_method(emitter, &env, ast_class)?
} else {
None
};
let needs_no_reifiedinit = reified_init_method.is_some() && ast_class.extends.is_empty();
additional_methods.extend(reified_init_method.into_iter());
additional_methods.extend(pinit_method.into_iter());
additional_methods.extend(sinit_method.into_iter());
additional_methods.extend(linit_method.into_iter());
additional_methods.extend(cinit_method.into_iter());
let mut methods = emit_method::from_asts(emitter, ast_class, &ast_class.methods)?;
methods.extend(additional_methods.into_iter());
let (ctxconsts, tconsts): (Vec<_>, Vec<_>) =
ast_class.typeconsts.iter().partition(|x| x.is_ctx);
let type_constants = tconsts
.iter()
.map(|x| from_type_constant(alloc, emitter, x))
.collect::<Result<Vec<TypeConstant<'_>>>>()?;
let ctx_constants = ctxconsts
.iter()
.map(|x| from_ctx_constant(alloc, x))
.collect::<Result<Vec<CtxConstant<'_>>>>()?;
let upper_bounds = emit_body::emit_generics_upper_bounds(alloc, &ast_class.tparams, &[], false);
if !no_xhp_attributes {
properties.push(emit_xhp::properties_for_cache(
emitter, ast_class, is_const, is_closure,
)?);
}
let info = emit_memoize_method::make_info(ast_class, name, &ast_class.methods)?;
methods.extend(emit_memoize_method::emit_wrapper_methods(
emitter,
&mut env,
&info,
ast_class,
&ast_class.methods,
)?);
let doc_comment = ast_class.doc_comment.clone();
let is_closure = methods.iter().any(|x| x.is_closure_body());
let is_systemlib = emitter.systemlib();
let mut flags = Attr::AttrNone;
flags.set(Attr::AttrAbstract, is_abstract);
flags.set(Attr::AttrBuiltin, is_systemlib);
flags.set(Attr::AttrFinal, is_final);
flags.set(Attr::AttrForbidDynamicProps, no_dynamic_props);
flags.set(Attr::AttrInterface, is_interface);
flags.set(Attr::AttrIsConst, is_const);
flags.set(Attr::AttrNoOverride, is_closure);
flags.set(Attr::AttrNoReifiedInit, needs_no_reifiedinit);
flags.set(Attr::AttrPersistent, is_systemlib);
flags.set(Attr::AttrSealed, is_sealed);
flags.set(Attr::AttrTrait, is_trait);
flags.set(Attr::AttrEnumClass, hhbc::has_enum_class(&attributes));
flags.set(Attr::AttrIsFoldable, hhbc::has_foldable(&attributes));
flags.set(
Attr::AttrDynamicallyConstructible,
hhbc::has_dynamically_constructible(&attributes),
);
flags.set(
Attr::AttrEnum,
enum_type.is_some() && !hhbc::has_enum_class(&attributes),
);
flags.set(Attr::AttrInternal, ast_class.internal);
flags.set(Attr::AttrIsClosureClass, is_closure);
add_symbol_refs(emitter, base.as_ref(), &implements, &uses, &requirements);
Ok(Class {
attributes: Slice::fill_iter(alloc, attributes.into_iter()),
base: Maybe::from(base),
implements: Slice::fill_iter(alloc, implements.into_iter()),
enum_includes: Slice::fill_iter(alloc, enum_includes.into_iter()),
name,
span,
flags,
doc_comment: Maybe::from(doc_comment.map(|c| Str::new_str(alloc, &c.1))),
uses: Slice::fill_iter(alloc, uses.into_iter()),
methods: Slice::fill_iter(alloc, methods.into_iter()),
enum_type: Maybe::from(enum_type),
upper_bounds: Slice::fill_iter(alloc, upper_bounds.into_iter()),
properties: Slice::fill_iter(alloc, properties.into_iter().map(|p| p.prop)),
requirements: Slice::fill_iter(alloc, requirements.into_iter()),
type_constants: Slice::fill_iter(alloc, type_constants.into_iter()),
ctx_constants: Slice::fill_iter(alloc, ctx_constants.into_iter()),
constants: Slice::fill_iter(alloc, constants.into_iter().map(|(c, _)| c)),
})
}
pub fn emit_classes_from_program<'a, 'arena, 'decl>(
alloc: &'arena bumpalo::Bump,
emitter: &mut Emitter<'arena, 'decl>,
ast: &'a [ast::Def],
) -> Result<Vec<Class<'arena>>> {
ast.iter()
.filter_map(|class| {
if let ast::Def::Class(cd) = class {
Some(emit_class(alloc, emitter, cd))
} else {
None
}
})
.collect()
} |
Rust | hhvm/hphp/hack/src/hackc/emitter/emit_constant.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use core_utils_rust as utils;
use emit_type_hint::Kind;
use env::emitter::Emitter;
use env::Env;
use error::Result;
use ffi::Maybe;
use ffi::Slice;
use ffi::Str;
use hhbc::Coeffects;
use hhbc::Constant;
use hhbc::Function;
use hhbc::FunctionFlags;
use hhbc::Span;
use hhbc::TypedValue;
use hhbc_string_utils::strip_global_ns;
use hhvm_types_ffi::ffi::Attr;
use instruction_sequence::instr;
use instruction_sequence::InstrSeq;
use oxidized::ast;
use crate::emit_body;
use crate::emit_expression;
fn emit_constant_cinit<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
constant: &'a ast::Gconst,
init: Option<InstrSeq<'arena>>,
) -> Result<Option<Function<'arena>>> {
let alloc = env.arena;
let const_name = hhbc::ConstName::from_ast_name(alloc, &constant.name.1);
let (ns, name) = utils::split_ns_from_name(const_name.unsafe_as_str());
let name = String::new() + strip_global_ns(ns) + "86cinit_" + name;
let original_name = hhbc::FunctionName::new(Str::new_str(alloc, &name));
let ret = constant.type_.as_ref();
let return_type_info = ret
.map(|h| {
emit_type_hint::hint_to_type_info(
alloc,
&Kind::Return,
false, /* skipawaitable */
false, /* nullable */
&[], /* tparams */
h,
)
})
.transpose()?;
init.map(|instrs| {
let verify_instr = match return_type_info {
None => instr::empty(),
Some(_) => instr::verify_ret_type_c(),
};
let instrs = InstrSeq::gather(vec![instrs, verify_instr, instr::ret_c()]);
let body = emit_body::make_body(
alloc,
e,
instrs,
vec![],
false, /* is_memoize_wrapper */
false, /* is_memoize_wrapper_lsb */
vec![], /* upper_bounds */
vec![], /* shadowed_params */
vec![], /* params */
return_type_info,
None, /* doc_comment */
Some(env),
)?;
let mut attrs = Attr::AttrNoInjection;
attrs.set(Attr::AttrPersistent, e.systemlib());
attrs.set(Attr::AttrBuiltin, e.systemlib());
Ok(Function {
attributes: Slice::empty(),
name: original_name,
body,
span: Span::from_pos(&constant.span),
coeffects: Coeffects::default(),
flags: FunctionFlags::empty(),
attrs,
})
})
.transpose()
}
fn emit_constant<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
constant: &'a ast::Gconst,
) -> Result<(Constant<'arena>, Option<Function<'arena>>)> {
let (c, init) = from_ast(e, env, &constant.name, false, Some(&constant.value))?;
let f = emit_constant_cinit(e, env, constant, init)?;
Ok((c, f))
}
pub fn emit_constants_from_program<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
defs: &'a [ast::Def],
) -> Result<(Vec<Constant<'arena>>, Vec<Function<'arena>>)> {
let const_tuples = defs
.iter()
.filter_map(|d| d.as_constant().map(|c| emit_constant(e, env, c)))
.collect::<Result<Vec<_>>>()?;
let (contants, inits): (Vec<_>, Vec<_>) = const_tuples.into_iter().unzip();
Ok((contants, inits.into_iter().flatten().collect()))
}
pub fn from_ast<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
id: &'a ast::Id,
is_abstract: bool,
expr: Option<&ast::Expr>,
) -> Result<(Constant<'arena>, Option<InstrSeq<'arena>>)> {
let alloc = env.arena;
let (value, initializer_instrs) = match expr {
None => (None, None),
Some(init) => match constant_folder::expr_to_typed_value(emitter, init) {
Ok(v) => (Some(v), None),
Err(_) => (
Some(TypedValue::Uninit),
Some(emit_expression::emit_expr(emitter, env, init)?),
),
},
};
let mut attrs = Attr::AttrNone;
attrs.set(Attr::AttrPersistent, emitter.systemlib());
attrs.set(Attr::AttrAbstract, is_abstract);
let constant = Constant {
name: hhbc::ConstName::from_ast_name(alloc, id.name()),
value: Maybe::from(value),
attrs,
};
Ok((constant, initializer_instrs))
} |
Rust | hhvm/hphp/hack/src/hackc/emitter/emit_expression.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::borrow::Cow;
use std::collections::BTreeMap;
use std::iter;
use std::str::FromStr;
use bstr::ByteSlice;
use emit_pos::emit_pos;
use emit_pos::emit_pos_then;
use env::emitter::Emitter;
use env::ClassExpr;
use env::Env;
use env::Flags as EnvFlags;
use error::Error;
use error::Result;
use ffi::Slice;
use ffi::Str;
use hash::HashSet;
use hhbc::BareThisOp;
use hhbc::CollectionType;
use hhbc::FCallArgs;
use hhbc::FCallArgsFlags;
use hhbc::HasGenericsOp;
use hhbc::IncDecOp;
use hhbc::IncludePath;
use hhbc::Instruct;
use hhbc::IsLogAsDynamicCallOp;
use hhbc::IsTypeOp;
use hhbc::IterArgs;
use hhbc::Label;
use hhbc::Local;
use hhbc::MOpMode;
use hhbc::MemberKey;
use hhbc::MethodName;
use hhbc::OODeclExistsOp;
use hhbc::ObjMethodOp;
use hhbc::Opcode;
use hhbc::QueryMOp;
use hhbc::ReadonlyOp;
use hhbc::SetOpOp;
use hhbc::SetRangeOp;
use hhbc::SpecialClsRef;
use hhbc::StackIndex;
use hhbc::TypeStructResolveOp;
use hhbc::TypedValue;
use hhbc_string_utils as string_utils;
use indexmap::IndexSet;
use instruction_sequence::instr;
use instruction_sequence::InstrSeq;
use itertools::Itertools;
use lazy_static::lazy_static;
use naming_special_names_rust::emitter_special_functions;
use naming_special_names_rust::fb;
use naming_special_names_rust::pseudo_consts;
use naming_special_names_rust::pseudo_functions;
use naming_special_names_rust::special_functions;
use naming_special_names_rust::special_idents;
use naming_special_names_rust::superglobals;
use naming_special_names_rust::typehints;
use naming_special_names_rust::user_attributes;
use oxidized::aast;
use oxidized::aast_defs;
use oxidized::aast_visitor::visit;
use oxidized::aast_visitor::visit_mut;
use oxidized::aast_visitor::AstParams;
use oxidized::aast_visitor::Node;
use oxidized::aast_visitor::NodeMut;
use oxidized::aast_visitor::Visitor;
use oxidized::aast_visitor::VisitorMut;
use oxidized::ast;
use oxidized::ast_defs;
use oxidized::ast_defs::ParamKind;
use oxidized::local_id;
use oxidized::pos::Pos;
use regex::Regex;
use serde_json::json;
use super::TypeRefinementInHint;
use crate::emit_adata;
use crate::emit_fatal;
use crate::emit_type_constant;
#[derive(Debug)]
pub struct EmitJmpResult<'arena> {
/// Generated instruction sequence.
pub instrs: InstrSeq<'arena>,
/// Does instruction sequence fall through?
is_fallthrough: bool,
/// Was label associated with emit operation used?
is_label_used: bool,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum LValOp {
Set,
SetOp(SetOpOp),
IncDec(IncDecOp),
Unset,
}
impl LValOp {
fn is_incdec(&self) -> bool {
if let Self::IncDec(_) = self {
return true;
};
false
}
}
pub fn is_local_this<'a, 'arena>(env: &Env<'a, 'arena>, lid: &local_id::LocalId) -> bool {
local_id::get_name(lid) == special_idents::THIS
&& env.scope.has_this()
&& !env.scope.is_toplevel()
}
mod inout_locals {
use std::marker::PhantomData;
use hash::HashMap;
use oxidized::aast_defs::Lid;
use oxidized::aast_visitor;
use oxidized::aast_visitor::Node;
use oxidized::ast;
use oxidized::ast_defs;
use super::Emitter;
use super::Env;
use super::Local;
use super::ParamKind;
pub(super) struct AliasInfo {
first_inout: isize,
last_write: isize,
num_uses: usize,
}
impl Default for AliasInfo {
fn default() -> Self {
AliasInfo {
first_inout: std::isize::MAX,
last_write: std::isize::MIN,
num_uses: 0,
}
}
}
impl AliasInfo {
pub(super) fn add_inout(&mut self, i: isize) {
if i < self.first_inout {
self.first_inout = i;
}
}
pub(super) fn add_write(&mut self, i: isize) {
if i > self.last_write {
self.last_write = i;
}
}
pub(super) fn add_use(&mut self) {
self.num_uses += 1
}
pub(super) fn in_range(&self, i: isize) -> bool {
i > self.first_inout || i <= self.last_write
}
pub(super) fn has_single_ref(&self) -> bool {
self.num_uses < 2
}
}
pub(super) type AliasInfoMap<'ast> = HashMap<&'ast str, AliasInfo>;
pub(super) fn new_alias_info_map<'ast>() -> AliasInfoMap<'ast> {
HashMap::default()
}
fn add_write<'ast>(name: &'ast str, i: usize, map: &mut AliasInfoMap<'ast>) {
map.entry(name.as_ref()).or_default().add_write(i as isize);
}
fn add_inout<'ast>(name: &'ast str, i: usize, map: &mut AliasInfoMap<'ast>) {
map.entry(name.as_ref()).or_default().add_inout(i as isize);
}
fn add_use<'ast>(name: &'ast str, map: &mut AliasInfoMap<'ast>) {
map.entry(name.as_ref()).or_default().add_use();
}
// determines if value of a local 'name' that appear in parameter 'i'
// should be saved to local because it might be overwritten later
pub(super) fn should_save_local_value(
name: &str,
i: usize,
aliases: &AliasInfoMap<'_>,
) -> bool {
aliases
.get(name)
.map_or(false, |alias| alias.in_range(i as isize))
}
pub(super) fn should_move_local_value(
e: &Emitter<'_, '_>,
local: Local,
aliases: &AliasInfoMap<'_>,
) -> bool {
let name = e.local_name(local);
aliases
.get(name.unsafe_as_str())
.map_or(true, |alias| alias.has_single_ref())
}
pub(super) fn collect_written_variables<'ast, 'arena>(
env: &Env<'ast, 'arena>,
args: &'ast [(ParamKind, ast::Expr)],
) -> AliasInfoMap<'ast> {
let mut acc = HashMap::default();
args.iter()
.enumerate()
.for_each(|(i, (pk, arg))| handle_arg(env, true, i, pk, arg, &mut acc));
acc
}
fn handle_arg<'ast, 'arena>(
env: &Env<'ast, 'arena>,
is_top: bool,
i: usize,
pk: &ParamKind,
arg: &'ast ast::Expr,
acc: &mut AliasInfoMap<'ast>,
) {
use ast::Expr;
use ast::Expr_;
let Expr(_, _, e) = arg;
// inout $v
if let (ParamKind::Pinout(_), Expr_::Lvar(lid)) = (pk, e) {
let Lid(_, lid) = &**lid;
if !super::is_local_this(env, lid) {
add_use(&lid.1, acc);
return if is_top {
add_inout(lid.1.as_str(), i, acc);
} else {
add_write(lid.1.as_str(), i, acc);
};
}
}
// $v
if let Some(Lid(_, (_, id))) = e.as_lvar() {
return add_use(id.as_str(), acc);
}
// dive into argument value
aast_visitor::visit(
&mut Visitor(PhantomData),
&mut Ctx { state: acc, env, i },
arg,
)
.unwrap();
}
struct Visitor<'r, 'arena>(PhantomData<(&'arena (), &'r ())>);
pub struct Ctx<'r, 'ast, 'arena> {
state: &'r mut AliasInfoMap<'ast>,
env: &'r Env<'ast, 'arena>,
i: usize,
}
impl<'r, 'ast: 'r, 'arena: 'r> aast_visitor::Visitor<'ast> for Visitor<'r, 'arena> {
type Params = aast_visitor::AstParams<Ctx<'r, 'ast, 'arena>, ()>;
fn object(&mut self) -> &mut dyn aast_visitor::Visitor<'ast, Params = Self::Params> {
self
}
fn visit_expr_(
&mut self,
c: &mut Ctx<'r, 'ast, 'arena>,
p: &'ast ast::Expr_,
) -> Result<(), ()> {
// f(inout $v) or f(&$v)
if let ast::Expr_::Call(expr) = p {
let ast::CallExpr {
args, unpacked_arg, ..
} = &**expr;
args.iter()
.for_each(|(pk, arg)| handle_arg(c.env, false, c.i, pk, arg, c.state));
if let Some(arg) = unpacked_arg.as_ref() {
handle_arg(c.env, false, c.i, &ParamKind::Pnormal, arg, c.state)
}
Ok(())
} else {
p.recurse(c, self.object())?;
Ok(match p {
// lhs op= _
ast::Expr_::Binop(expr) => {
let ast::Binop { bop, lhs: left, .. } = &**expr;
if let ast_defs::Bop::Eq(_) = bop {
collect_lvars_hs(c, left)
}
}
// $i++ or $i--
ast::Expr_::Unop(expr) => {
let (uop, e) = &**expr;
match uop {
ast_defs::Uop::Uincr | ast_defs::Uop::Udecr => collect_lvars_hs(c, e),
_ => {}
}
}
// $v
ast::Expr_::Lvar(expr) => {
let Lid(_, (_, id)) = &**expr;
add_use(id, c.state);
}
_ => {}
})
}
}
} // impl<'ast, 'a, 'arena> aast_visitor::Visitor<'ast> for Visitor<'a, 'arena>
// collect lvars on the left hand side of '=' operator
fn collect_lvars_hs<'r, 'ast, 'arena>(ctx: &mut Ctx<'r, 'ast, 'arena>, expr: &'ast ast::Expr) {
let ast::Expr(_, _, e) = expr;
match e {
ast::Expr_::Lvar(lid) => {
let Lid(_, lid) = &**lid;
if !super::is_local_this(ctx.env, lid) {
add_use(lid.1.as_str(), ctx.state);
add_write(lid.1.as_str(), ctx.i, ctx.state);
}
}
ast::Expr_::List(exprs) => exprs.iter().for_each(|expr| collect_lvars_hs(ctx, expr)),
_ => {}
}
}
} //mod inout_locals
pub(crate) fn get_type_structure_for_hint<'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
tparams: &[&str],
targ_map: &IndexSet<&str>,
type_refinement_in_hint: TypeRefinementInHint,
hint: &aast::Hint,
) -> Result<InstrSeq<'arena>> {
let targ_map: BTreeMap<&str, i64> = targ_map
.iter()
.enumerate()
.map(|(i, n)| (*n, i as i64))
.collect();
let tv = emit_type_constant::hint_to_type_constant(
e.alloc,
e.options(),
tparams,
&targ_map,
hint,
type_refinement_in_hint,
)?;
emit_adata::typed_value_into_instr(e, tv)
}
pub struct SetRange {
pub op: SetRangeOp,
pub size: usize,
pub vec: bool,
}
/// kind of value stored in local
#[derive(Debug, Clone, Copy)]
pub enum StoredValueKind {
Local,
Expr,
}
/// represents sequence of instructions interleaved with temp locals.
/// <(i, None) :: rest> - is emitted i :: <rest> (commonly used for final instructions in sequence)
/// <(i, Some(l, local_kind)) :: rest> is emitted as
///
/// i
/// .try {
/// setl/popl l; depending on local_kind
/// <rest>
/// } .catch {
/// unset l
/// throw
/// }
/// unsetl l
type InstrSeqWithLocals<'arena> = Vec<(InstrSeq<'arena>, Option<(Local, StoredValueKind)>)>;
/// result of emit_array_get
enum ArrayGetInstr<'arena> {
/// regular $a[..] that does not need to spill anything
Regular(InstrSeq<'arena>),
/// subscript expression used as inout argument that need to spill intermediate values:
Inout {
/// instruction sequence with locals to load value
load: InstrSeqWithLocals<'arena>,
/// instruction to set value back (can use locals defined in load part)
store: InstrSeq<'arena>,
},
}
struct ArrayGetBaseData<'arena, T> {
base_instrs: T,
cls_instrs: InstrSeq<'arena>,
setup_instrs: InstrSeq<'arena>,
base_stack_size: StackIndex,
cls_stack_size: StackIndex,
}
/// result of emit_base
enum ArrayGetBase<'arena> {
/// regular <base> part in <base>[..] that does not need to spill anything
Regular(ArrayGetBaseData<'arena, InstrSeq<'arena>>),
/// base of subscript expression used as inout argument that need to spill
/// intermediate values
Inout {
/// instructions to load base part
load: ArrayGetBaseData<'arena, InstrSeqWithLocals<'arena>>,
/// instruction to load base part for setting inout argument back
store: InstrSeq<'arena>,
},
}
pub fn emit_expr<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
expression: &ast::Expr,
) -> Result<InstrSeq<'arena>> {
stack_limit::maybe_grow(|| {
use ast::Expr_;
let ast::Expr(_, pos, expr) = expression;
match expr {
Expr_::Float(_)
| Expr_::String(_)
| Expr_::Int(_)
| Expr_::Null
| Expr_::False
| Expr_::True => emit_lit(emitter, env, pos, expression),
Expr_::EnumClassLabel(label) => emit_label(emitter, env, pos, label),
Expr_::PrefixedString(e) => emit_expr(emitter, env, &e.1),
Expr_::Lvar(e) => emit_lvar(emitter, env, pos, e),
Expr_::ClassConst(e) => emit_class_const(emitter, env, pos, &e.0, &e.1),
Expr_::Unop(e) => emit_unop(emitter, env, pos, e),
Expr_::Binop(_) => emit_binop(emitter, env, pos, expression),
Expr_::Pipe(e) => emit_pipe(emitter, env, e),
Expr_::Is(is_expr) => emit_is_expr(emitter, env, pos, is_expr),
Expr_::As(e) => emit_as(emitter, env, pos, e),
Expr_::Upcast(e) => emit_expr(emitter, env, &e.0),
Expr_::Cast(e) => emit_cast(emitter, env, pos, &(e.0).1, &e.1),
Expr_::Eif(e) => emit_conditional_expr(emitter, env, pos, &e.0, e.1.as_ref(), &e.2),
Expr_::ArrayGet(e) => emit_array_get_expr(emitter, env, pos, e),
Expr_::ObjGet(e) => emit_obj_get_expr(emitter, env, pos, e),
Expr_::Call(c) => emit_call_expr(emitter, env, pos, None, false, c),
Expr_::New(e) => emit_new(emitter, env, pos, e, false),
Expr_::FunctionPointer(fp) => emit_function_pointer(emitter, env, pos, &fp.0, &fp.1),
Expr_::Darray(e) => emit_darray(emitter, env, pos, e, expression),
Expr_::Varray(e) => emit_varray(emitter, env, pos, e, expression),
Expr_::Collection(e) => emit_named_collection_str(emitter, env, expression, e),
Expr_::ValCollection(e) => emit_val_collection(emitter, env, pos, e, expression),
Expr_::Pair(e) => emit_pair(emitter, env, pos, e, expression),
Expr_::KeyValCollection(e) => {
emit_keyval_collection_expr(emitter, env, pos, e, expression)
}
Expr_::Clone(e) => Ok(emit_pos_then(pos, emit_clone(emitter, env, e)?)),
Expr_::Shape(e) => Ok(emit_pos_then(pos, emit_shape(emitter, env, expression, e)?)),
Expr_::Await(e) => emit_await(emitter, env, pos, e),
Expr_::ReadonlyExpr(e) => emit_readonly_expr(emitter, env, pos, e),
Expr_::Yield(e) => emit_yield(emitter, env, pos, e),
Expr_::Efun(e) => Ok(emit_pos_then(
pos,
emit_lambda(emitter, env, &e.use_, &e.closure_class_name)?,
)),
Expr_::ClassGet(e) => emit_class_get_expr(emitter, env, pos, e),
Expr_::String2(es) => emit_string2(emitter, env, pos, es),
Expr_::Id(e) => Ok(emit_pos_then(pos, emit_id(emitter, env, e)?)),
Expr_::Xml(_) => Err(Error::unrecoverable(
"emit_xhp: syntax should have been converted during rewriting",
)),
Expr_::Import(e) => emit_import(emitter, env, pos, &e.0, &e.1),
Expr_::Omitted => Err(Error::unrecoverable(
"emit_expr: Omitted should never be encountered by codegen",
)),
Expr_::Lfun(_) => Err(Error::unrecoverable(
"expected Lfun to be converted to Efun during closure conversion emit_expr",
)),
Expr_::List(_) => Err(Error::fatal_parse(
pos,
"list() can only be used as an lvar. Did you mean to use tuple()?",
)),
Expr_::Tuple(e) => Ok(emit_pos_then(
pos,
emit_collection(emitter, env, expression, &mk_afvalues(e), None)?,
)),
Expr_::This | Expr_::Lplaceholder(_) | Expr_::Dollardollar(_) => {
unimplemented!("TODO(hrust) Codegen after naming pass on AAST")
}
Expr_::ExpressionTree(et) => emit_expr(emitter, env, &et.runtime_expr),
Expr_::ETSplice(_) => Err(Error::unrecoverable(
"expression trees: splice should be erased during rewriting",
)),
Expr_::Invalid(_) => Err(Error::unrecoverable(
"emit_expr: Invalid should never be encountered by codegen",
)),
Expr_::MethodCaller(_) | Expr_::Hole(_) => {
unimplemented!("TODO(hrust)")
}
Expr_::Package(_) => Err(Error::unrecoverable(
"package should have been converted into package_exists during rewriting",
)),
}
})
}
fn emit_exprs_and_error_on_inout<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
exprs: &[(ParamKind, ast::Expr)],
fn_name: &str,
) -> Result<InstrSeq<'arena>> {
if exprs.is_empty() {
Ok(instr::empty())
} else {
Ok(InstrSeq::gather(
exprs
.iter()
.map(|(pk, expr)| match pk {
ParamKind::Pnormal => emit_expr(e, env, expr),
ParamKind::Pinout(p) => Err(Error::fatal_parse(
&Pos::merge(p, expr.pos()).map_err(Error::unrecoverable)?,
format!(
"Unexpected `inout` argument on pseudofunction: `{}`",
fn_name
),
)),
})
.collect::<Result<Vec<_>>>()?,
))
}
}
fn emit_exprs<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
exprs: &[ast::Expr],
) -> Result<InstrSeq<'arena>> {
if exprs.is_empty() {
Ok(instr::empty())
} else {
Ok(InstrSeq::gather(
exprs
.iter()
.map(|expr| emit_expr(e, env, expr))
.collect::<Result<Vec<_>>>()?,
))
}
}
fn emit_id<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
id: &ast::Sid,
) -> Result<InstrSeq<'arena>> {
let alloc = env.arena; // Should this be emitter.alloc?
let ast_defs::Id(p, s) = id;
match s.as_str() {
pseudo_consts::G__FILE__ => Ok(instr::instr(Instruct::Opcode(Opcode::File))),
pseudo_consts::G__DIR__ => Ok(instr::instr(Instruct::Opcode(Opcode::Dir))),
pseudo_consts::G__METHOD__ => Ok(instr::instr(Instruct::Opcode(Opcode::Method))),
pseudo_consts::G__FUNCTION_CREDENTIAL__ => {
Ok(instr::instr(Instruct::Opcode(Opcode::FuncCred)))
}
pseudo_consts::G__CLASS__ => Ok(InstrSeq::gather(vec![
instr::self_cls(),
instr::class_name(),
])),
pseudo_consts::G__COMPILER_FRONTEND__ => Ok(instr::string(alloc, "hackc")),
pseudo_consts::G__LINE__ => Ok(instr::int(p.info_pos_extended().1.try_into().map_err(
|_| Error::fatal_parse(p, "error converting end of line from usize to isize"),
)?)),
pseudo_consts::G__NAMESPACE__ => Ok(instr::string(
alloc,
env.namespace.name.as_ref().map_or("", |s| &s[..]),
)),
pseudo_consts::EXIT | pseudo_consts::DIE => emit_exit(emitter, env, None),
_ => {
// panic!("TODO: uncomment after D19350786 lands")
// let cid: ConstId = hhbc::ConstName::from_ast_name(&s);
let cid = hhbc::ConstName::new(Str::new_str(alloc, string_utils::strip_global_ns(s)));
emitter.add_constant_ref(cid.clone());
Ok(emit_pos_then(
p,
instr::instr(Instruct::Opcode(Opcode::CnsE(cid))),
))
}
}
}
fn emit_exit<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
expr_opt: Option<&ast::Expr>,
) -> Result<InstrSeq<'arena>> {
Ok(InstrSeq::gather(vec![
expr_opt.map_or_else(|| Ok(instr::int(0)), |e| emit_expr(emitter, env, e))?,
instr::exit(),
]))
}
fn emit_yield<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
af: &ast::Afield,
) -> Result<InstrSeq<'arena>> {
Ok(match af {
ast::Afield::AFvalue(v) => {
InstrSeq::gather(vec![emit_expr(e, env, v)?, emit_pos(pos), instr::yield_()])
}
ast::Afield::AFkvalue(k, v) => InstrSeq::gather(vec![
emit_expr(e, env, k)?,
emit_expr(e, env, v)?,
emit_pos(pos),
instr::yield_k(),
]),
})
}
fn parse_include<'arena>(alloc: &'arena bumpalo::Bump, e: &ast::Expr) -> IncludePath<'arena> {
fn strip_backslash(s: &mut String) {
if s.starts_with('/') {
*s = s[1..].into()
}
}
fn split_var_lit(e: &ast::Expr) -> (String, String) {
match &e.2 {
ast::Expr_::Binop(x) if x.bop.is_dot() => {
let (v, l) = split_var_lit(&x.rhs);
if v.is_empty() {
let (var, lit) = split_var_lit(&x.lhs);
(var, format!("{}{}", lit, l))
} else {
(v, String::new())
}
}
ast::Expr_::String(lit) => (String::new(), lit.to_string()),
_ => (text_of_expr(e), String::new()),
}
}
let (mut var, mut lit) = split_var_lit(e);
if var == pseudo_consts::G__DIR__ {
var = String::new();
strip_backslash(&mut lit);
}
if var.is_empty() {
if std::path::Path::new(lit.as_str()).is_relative() {
IncludePath::SearchPathRelative(Str::new_str(alloc, &lit))
} else {
IncludePath::Absolute(Str::new_str(alloc, &lit))
}
} else {
strip_backslash(&mut lit);
IncludePath::IncludeRootRelative(Str::new_str(alloc, &var), Str::new_str(alloc, &lit))
}
}
fn text_of_expr(e: &ast::Expr) -> String {
match &e.2 {
ast::Expr_::String(s) => format!("\'{}\'", s),
ast::Expr_::Id(id) => id.1.to_string(),
ast::Expr_::Lvar(lid) => local_id::get_name(&lid.1).to_string(),
ast::Expr_::ArrayGet(x) => match ((x.0).2.as_lvar(), x.1.as_ref()) {
(Some(ast::Lid(_, id)), Some(e_)) => {
format!("{}[{}]", local_id::get_name(id), text_of_expr(e_))
}
_ => "unknown".into(),
},
_ => "unknown".into(),
}
}
fn text_of_class_id(cid: &ast::ClassId) -> String {
match &cid.2 {
ast::ClassId_::CIparent => "parent".into(),
ast::ClassId_::CIself => "self".into(),
ast::ClassId_::CIstatic => "static".into(),
ast::ClassId_::CIexpr(e) => text_of_expr(e),
ast::ClassId_::CI(ast_defs::Id(_, id)) => id.into(),
}
}
fn text_of_prop(prop: &ast::ClassGetExpr) -> String {
match prop {
ast::ClassGetExpr::CGstring((_, s)) => s.into(),
ast::ClassGetExpr::CGexpr(e) => text_of_expr(e),
}
}
fn emit_import<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
flavor: &ast::ImportFlavor,
expr: &ast::Expr,
) -> Result<InstrSeq<'arena>> {
use ast::ImportFlavor;
let alloc = env.arena; // Should this be emitter.alloc?
let inc = parse_include(alloc, expr);
let filepath = e.filepath.clone();
let resolved_inc = inc.resolve_include_roots(alloc, &e.options().hhvm.include_roots, &filepath);
let (expr_instrs, import_op_instr) = match flavor {
ImportFlavor::Include => (emit_expr(e, env, expr)?, instr::incl()),
ImportFlavor::Require => (emit_expr(e, env, expr)?, instr::req()),
ImportFlavor::IncludeOnce => (emit_expr(e, env, expr)?, instr::incl_once()),
ImportFlavor::RequireOnce => match &resolved_inc {
IncludePath::DocRootRelative(path) => {
let expr = ast::Expr(
(),
pos.clone(),
ast::Expr_::String(path.unsafe_as_str().into()),
);
(emit_expr(e, env, &expr)?, instr::req_doc())
}
_ => (emit_expr(e, env, expr)?, instr::req_once()),
},
};
e.add_include_ref(resolved_inc);
Ok(InstrSeq::gather(vec![
expr_instrs,
emit_pos(pos),
import_op_instr,
]))
}
fn emit_string2<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
es: &[ast::Expr],
) -> Result<InstrSeq<'arena>> {
if es.is_empty() {
Err(Error::unrecoverable(
"String2 with zero araguments is impossible",
))
} else if es.len() == 1 {
Ok(InstrSeq::gather(vec![
emit_expr(e, env, &es[0])?,
emit_pos(pos),
instr::cast_string(),
]))
} else {
Ok(InstrSeq::gather(vec![
emit_two_exprs(e, env, &es[0].1, &es[0], &es[1])?,
emit_pos(pos),
instr::concat(),
InstrSeq::gather(
es[2..]
.iter()
.map(|expr| {
Ok(InstrSeq::gather(vec![
emit_expr(e, env, expr)?,
emit_pos(pos),
instr::concat(),
]))
})
.collect::<Result<_>>()?,
),
]))
}
}
fn emit_clone<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
expr: &ast::Expr,
) -> Result<InstrSeq<'arena>> {
Ok(InstrSeq::gather(vec![
emit_expr(e, env, expr)?,
instr::clone(),
]))
}
fn emit_lambda<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
ids: &[ast::CaptureLid],
closure_class_name: &Option<String>,
) -> Result<InstrSeq<'arena>> {
let closure_class_name = if let Some(n) = closure_class_name {
n
} else {
return Err(Error::unrecoverable(
"Closure conversion should have set closure_class_name",
));
};
let explicit_use = e
.global_state()
.explicit_use_set
.contains(closure_class_name);
let is_in_lambda = env.scope.is_in_lambda();
Ok(InstrSeq::gather(vec![
InstrSeq::gather(
ids.iter()
.map(|ast::CaptureLid(_, ast::Lid(pos, id))| {
match string_utils::reified::is_captured_generic(local_id::get_name(id)) {
Some((is_fun, i)) => {
if is_in_lambda {
let name = string_utils::reified::reified_generic_captured_name(
is_fun, i as usize,
);
Ok(instr::c_get_l(e.named_local(name.as_str().into())))
} else {
emit_reified_generic_instrs(e, &Pos::NONE, is_fun, i as usize)
}
}
None => Ok({
let lid = get_local(e, env, pos, local_id::get_name(id))?;
if explicit_use {
instr::c_get_l(lid)
} else {
instr::cu_get_l(lid)
}
}),
}
})
.collect::<Result<Vec<_>>>()?,
),
instr::create_cl(
ids.len() as u32,
hhbc::ClassName::from_raw_string(e.alloc, closure_class_name),
),
]))
}
pub fn emit_await<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
expr: &ast::Expr,
) -> Result<InstrSeq<'arena>> {
let ast::Expr(_, _, e) = expr;
let can_inline_gen_functions = !emitter
.options()
.function_is_renamable(emitter_special_functions::GENA.into());
match e.as_call() {
Some(ast::CallExpr {
func: ast::Expr(_, _, ast::Expr_::Id(id)),
args,
unpacked_arg: None,
..
}) if (can_inline_gen_functions
&& args.len() == 1
&& string_utils::strip_global_ns(&id.1) == emitter_special_functions::GENA) =>
{
inline_gena_call(emitter, env, error::expect_normal_paramkind(&args[0])?)
}
_ => {
let after_await = emitter.label_gen_mut().next_regular();
let instrs = match e {
ast::Expr_::Call(c) => {
emit_call_expr(emitter, env, pos, Some(after_await.clone()), false, c)?
}
_ => emit_expr(emitter, env, expr)?,
};
Ok(InstrSeq::gather(vec![
instrs,
emit_pos(pos),
instr::dup(),
instr::is_type_c(IsTypeOp::Null),
instr::jmp_nz(after_await.clone()),
instr::await_(),
instr::label(after_await),
]))
}
}
}
fn inline_gena_call<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
arg: &ast::Expr,
) -> Result<InstrSeq<'arena>> {
let load_arr = emit_expr(emitter, env, arg)?;
let async_eager_label = emitter.label_gen_mut().next_regular();
scope::with_unnamed_local(emitter, |e, arr_local| {
let alloc = e.alloc;
let before = InstrSeq::gather(vec![load_arr, instr::cast_dict(), instr::pop_l(arr_local)]);
let inner = InstrSeq::gather(vec![
instr::null_uninit(),
instr::null_uninit(),
instr::c_get_l(arr_local),
instr::f_call_cls_method_d(
FCallArgs::new(
FCallArgsFlags::default(),
1,
1,
Slice::empty(),
Slice::empty(),
Some(async_eager_label),
None,
),
hhbc::MethodName::from_raw_string(alloc, "fromDict"),
hhbc::ClassName::from_raw_string(alloc, "HH\\AwaitAllWaitHandle"),
),
instr::await_(),
instr::label(async_eager_label),
instr::pop_c(),
emit_iter(e, instr::c_get_l(arr_local), |val_local, key_local| {
InstrSeq::gather(vec![
instr::c_get_l(val_local),
instr::wh_result(),
instr::base_l(
arr_local,
MOpMode::Define,
ReadonlyOp::Any, // TODO, handle await assignment statements correctly
),
instr::set_m(0, MemberKey::EL(key_local, ReadonlyOp::Any)),
instr::pop_c(),
])
})?,
]);
let after = instr::push_l(arr_local);
Ok((before, inner, after))
})
}
fn emit_iter<'arena, 'decl, F: FnOnce(Local, Local) -> InstrSeq<'arena>>(
e: &mut Emitter<'arena, 'decl>,
collection: InstrSeq<'arena>,
f: F,
) -> Result<InstrSeq<'arena>> {
scope::with_unnamed_locals_and_iterators(e, |e| {
let iter_id = e.iterator_mut().get();
let val_id = e.local_gen_mut().get_unnamed();
let key_id = e.local_gen_mut().get_unnamed();
let loop_end = e.label_gen_mut().next_regular();
let loop_next = e.label_gen_mut().next_regular();
let iter_args = IterArgs {
iter_id,
key_id,
val_id,
};
let iter_init = InstrSeq::gather(vec![
collection,
instr::iter_init(iter_args.clone(), loop_end),
]);
let iterate = InstrSeq::gather(vec![
instr::label(loop_next),
f(val_id, key_id),
instr::iter_next(iter_args, loop_next),
]);
let iter_done = InstrSeq::gather(vec![
instr::unset_l(val_id),
instr::unset_l(key_id),
instr::label(loop_end),
]);
Ok((iter_init, iterate, iter_done))
})
}
fn emit_shape<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
expr: &ast::Expr,
fl: &[(ast_defs::ShapeFieldName, ast::Expr)],
) -> Result<InstrSeq<'arena>> {
fn extract_shape_field_name_pstring<'a, 'arena>(
env: &Env<'a, 'arena>,
pos: &Pos,
field: &ast_defs::ShapeFieldName,
) -> Result<ast::Expr_> {
use ast_defs::ShapeFieldName as SF;
Ok(match field {
SF::SFlitInt(s) => ast::Expr_::mk_int(s.1.clone()),
SF::SFlitStr(s) => ast::Expr_::mk_string(s.1.clone()),
SF::SFclassConst(id, p) => {
if is_reified_tparam(env, true, &id.1).is_some()
|| is_reified_tparam(env, false, &id.1).is_some()
{
return Err(Error::fatal_parse(
&id.0,
"Reified generics cannot be used in shape keys",
));
} else {
ast::Expr_::mk_class_const(
ast::ClassId((), pos.clone(), ast::ClassId_::CI(id.clone())),
p.clone(),
)
}
}
})
}
let pos = &expr.1;
// TODO(hrust): avoid clone
let fl = fl
.iter()
.map(|(f, e)| {
Ok((
ast::Expr(
(),
pos.clone(),
extract_shape_field_name_pstring(env, pos, f)?,
),
e.clone(),
))
})
.collect::<Result<Vec<_>>>()?;
emit_expr(
emitter,
env,
&ast::Expr((), pos.clone(), ast::Expr_::mk_darray(None, fl)),
)
}
fn emit_vec_collection<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
fields: &[ast::Afield],
) -> Result<InstrSeq<'arena>> {
match constant_folder::vec_to_typed_value(e, fields) {
Ok(tv) => {
let instr = emit_adata::typed_value_into_instr(e, tv)?;
emit_static_collection(env, None, pos, instr)
}
Err(_) => {
emit_value_only_collection(e, env, pos, fields, |v| Instruct::Opcode(Opcode::NewVec(v)))
}
}
}
fn emit_named_collection<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
expr: &ast::Expr,
fields: &[ast::Afield],
collection_type: CollectionType,
) -> Result<InstrSeq<'arena>> {
let emit_vector_like = |e: &mut Emitter<'arena, 'decl>, collection_type| {
Ok(if fields.is_empty() {
emit_pos_then(pos, instr::new_col(collection_type))
} else {
InstrSeq::gather(vec![
emit_vec_collection(e, env, pos, fields)?,
instr::col_from_array(collection_type),
])
})
};
let emit_map_or_set = |e: &mut Emitter<'arena, 'decl>, collection_type| {
if fields.is_empty() {
Ok(emit_pos_then(pos, instr::new_col(collection_type)))
} else {
emit_collection(e, env, expr, fields, Some(collection_type))
}
};
use CollectionType as C;
match collection_type {
C::Vector | C::ImmVector => emit_vector_like(e, collection_type),
C::Map | C::ImmMap | C::Set | C::ImmSet => emit_map_or_set(e, collection_type),
C::Pair => Ok(InstrSeq::gather(vec![
InstrSeq::gather(
fields
.iter()
.map(|f| match f {
ast::Afield::AFvalue(v) => emit_expr(e, env, v),
_ => Err(Error::unrecoverable("impossible Pair argument")),
})
.collect::<Result<_>>()?,
),
instr::new_pair(),
])),
_ => Err(Error::unrecoverable("Unexpected named collection type")),
}
}
fn emit_named_collection_str<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
expr: &ast::Expr,
(ast_defs::Id(pos, name), _, fields): &(
ast::Sid,
Option<ast::CollectionTarg>,
Vec<ast::Afield>,
),
) -> Result<InstrSeq<'arena>> {
let name = string_utils::strip_ns(name);
let name = string_utils::types::fix_casing(name);
let ctype = match name {
"Vector" => CollectionType::Vector,
"ImmVector" => CollectionType::ImmVector,
"Map" => CollectionType::Map,
"ImmMap" => CollectionType::ImmMap,
"Set" => CollectionType::Set,
"ImmSet" => CollectionType::ImmSet,
"Pair" => CollectionType::Pair,
_ => {
return Err(Error::unrecoverable(format!(
"collection: {} does not exist",
name
)));
}
};
emit_named_collection(e, env, pos, expr, fields, ctype)
}
fn mk_afkvalues(es: impl Iterator<Item = (ast::Expr, ast::Expr)>) -> Vec<ast::Afield> {
es.map(|(e1, e2)| ast::Afield::mk_afkvalue(e1, e2))
.collect()
}
fn mk_afvalues(es: &[ast::Expr]) -> Vec<ast::Afield> {
es.iter().cloned().map(ast::Afield::mk_afvalue).collect()
}
fn emit_collection<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
expr: &ast::Expr,
fields: &[ast::Afield],
transform_to_collection: Option<CollectionType>,
) -> Result<InstrSeq<'arena>> {
let pos = &expr.1;
match constant_folder::expr_to_typed_value_(e, expr, true /*allow_map*/) {
Ok(tv) => {
let instr = emit_adata::typed_value_into_instr(e, tv)?;
emit_static_collection(env, transform_to_collection, pos, instr)
}
Err(_) => emit_dynamic_collection(e, env, expr, fields),
}
}
fn emit_static_collection<'a, 'arena>(
_env: &Env<'a, 'arena>,
transform_to_collection: Option<CollectionType>,
pos: &Pos,
instr: InstrSeq<'arena>,
) -> Result<InstrSeq<'arena>> {
let transform_instr = match transform_to_collection {
Some(collection_type) => instr::col_from_array(collection_type),
_ => instr::empty(),
};
Ok(InstrSeq::gather(vec![
emit_pos(pos),
instr,
transform_instr,
]))
}
fn expr_and_new<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
instr_to_add_new: InstrSeq<'arena>,
instr_to_add: InstrSeq<'arena>,
field: &ast::Afield,
) -> Result<InstrSeq<'arena>> {
match field {
ast::Afield::AFvalue(v) => Ok(InstrSeq::gather(vec![
emit_expr(e, env, v)?,
emit_pos(pos),
instr_to_add_new,
])),
ast::Afield::AFkvalue(k, v) => Ok(InstrSeq::gather(vec![
emit_two_exprs(e, env, &k.1, k, v)?,
instr_to_add,
])),
}
}
fn emit_container<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
fields: &[ast::Afield],
constructor: Instruct<'arena>,
add_elem_instr: InstrSeq<'arena>,
transform_instr: InstrSeq<'arena>,
emitted_pos: InstrSeq<'arena>,
) -> Result<InstrSeq<'arena>> {
Ok(InstrSeq::gather(vec![
InstrSeq::<'arena>::clone(&emitted_pos),
instr::instr(constructor),
fields
.iter()
.map(|f| {
expr_and_new(
e,
env,
pos,
InstrSeq::<'arena>::clone(&add_elem_instr),
instr::add_elem_c(),
f,
)
})
.collect::<Result<_>>()
.map(InstrSeq::gather)?,
emitted_pos,
transform_instr,
]))
}
fn emit_keyvalue_collection<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
fields: &[ast::Afield],
ctype: CollectionType,
constructor: Instruct<'arena>,
) -> Result<InstrSeq<'arena>> {
let transform_instr = instr::col_from_array(ctype);
let add_elem_instr = InstrSeq::gather(vec![instr::dup(), instr::add_elem_c()]);
let emitted_pos = emit_pos(pos);
emit_container(
e,
env,
pos,
fields,
constructor,
add_elem_instr,
transform_instr,
emitted_pos,
)
}
fn emit_array<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
fields: &[ast::Afield],
constructor: Instruct<'arena>,
) -> Result<InstrSeq<'arena>> {
let add_elem_instr = instr::add_new_elem_c();
let emitted_pos = emit_pos(pos);
emit_container(
e,
env,
pos,
fields,
constructor,
add_elem_instr,
instr::empty(),
emitted_pos,
)
}
fn non_numeric(s: &str) -> bool {
// Note(hrust): OCaml Int64.of_string and float_of_string ignore underscores
let s = s.replace('_', "");
lazy_static! {
static ref HEX: Regex = Regex::new(r"(?P<sign>^-?)0[xX](?P<digits>.*)").unwrap();
static ref OCTAL: Regex = Regex::new(r"(?P<sign>^-?)0[oO](?P<digits>.*)").unwrap();
static ref BINARY: Regex = Regex::new(r"(?P<sign>^-?)0[bB](?P<digits>.*)").unwrap();
static ref FLOAT: Regex =
Regex::new(r"(?P<int>\d*)\.(?P<dec>[0-9--0]*)(?P<zeros>0*)").unwrap();
static ref NEG_FLOAT: Regex =
Regex::new(r"(?P<int>-\d*)\.(?P<dec>[0-9--0]*)(?P<zeros>0*)").unwrap();
static ref HEX_RADIX: u32 = 16;
static ref OCTAL_RADIX: u32 = 8;
static ref BINARY_RADIX: u32 = 2;
}
fn int_from_str(s: &str) -> Result<i64, ()> {
// Note(hrust): OCaml Int64.of_string reads decimal, hexadecimal, octal, and binary
(if HEX.is_match(s) {
u64::from_str_radix(&HEX.replace(s, "${sign}${digits}"), *HEX_RADIX).map(|x| x as i64)
} else if OCTAL.is_match(s) {
u64::from_str_radix(&OCTAL.replace(s, "${sign}${digits}"), *OCTAL_RADIX)
.map(|x| x as i64)
} else if BINARY.is_match(s) {
u64::from_str_radix(&BINARY.replace(s, "${sign}${digits}"), *BINARY_RADIX)
.map(|x| x as i64)
} else {
i64::from_str(s)
})
.map_err(|_| ())
}
fn float_from_str_radix(s: &str, radix: u32) -> Result<f64, ()> {
let i = i64::from_str_radix(&s.replace('.', ""), radix).map_err(|_| ())?;
Ok(match s.matches('.').count() {
0 => i as f64,
1 => {
let pow = s.split('.').last().unwrap().len();
(i as f64) / f64::from(radix).powi(pow as i32)
}
_ => return Err(()),
})
}
fn out_of_bounds(s: &str) -> bool {
// compare strings instead of floats to avoid rounding imprecision
if FLOAT.is_match(s) {
FLOAT.replace(s, "${int}.${dec}").trim_end_matches('.') > i64::MAX.to_string().as_str()
} else if NEG_FLOAT.is_match(s) {
NEG_FLOAT.replace(s, "${int}.${dec}").trim_end_matches('.')
> i64::MIN.to_string().as_str()
} else {
false
}
}
fn float_from_str(s: &str) -> Result<f64, ()> {
// Note(hrust): OCaml float_of_string ignores leading whitespace,
// reads decimal and hexadecimal
let s = s.trim_start();
if HEX.is_match(s) {
float_from_str_radix(&HEX.replace(s, "${sign}${digits}"), *HEX_RADIX)
} else {
let out_of_bounds =
|f: f64| out_of_bounds(s) && (f > i64::MAX as f64 || f < i64::MIN as f64);
let validate_float = |f: f64| {
if out_of_bounds(f) || f.is_infinite() || f.is_nan() {
Err(())
} else {
Ok(f)
}
};
f64::from_str(s).map_err(|_| ()).and_then(validate_float)
}
}
int_from_str(&s).is_err() && float_from_str(&s).is_err()
}
fn is_struct_init<'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
fields: &[ast::Afield],
allow_numerics: bool,
) -> Result<bool> {
let mut are_all_keys_non_numeric_strings = true;
let mut uniq_keys = HashSet::<bstr::BString>::default();
for f in fields.iter() {
if let ast::Afield::AFkvalue(key, _) = f {
// TODO(hrust): if key is String, don't clone and call fold_expr
let mut key = key.clone();
constant_folder::fold_expr(&mut key, e)
.map_err(|e| Error::unrecoverable(format!("{}", e)))?;
if let ast::Expr(_, _, ast::Expr_::String(s)) = key {
are_all_keys_non_numeric_strings = are_all_keys_non_numeric_strings
&& non_numeric(
// FIXME: This is not safe--string literals are binary strings.
// There's no guarantee that they're valid UTF-8.
unsafe { std::str::from_utf8_unchecked(s.as_slice()) },
);
uniq_keys.insert(s);
} else {
are_all_keys_non_numeric_strings = false;
}
continue;
}
are_all_keys_non_numeric_strings = false;
}
let num_keys = fields.len();
let limit = e.options().max_array_elem_size_on_the_stack;
Ok((allow_numerics || are_all_keys_non_numeric_strings)
&& uniq_keys.len() == num_keys
&& num_keys <= limit
&& num_keys != 0)
}
fn emit_struct_array<
'a,
'arena,
'decl,
C: FnOnce(
&'arena bumpalo::Bump,
&mut Emitter<'arena, 'decl>,
&'arena [&'arena str],
) -> Result<InstrSeq<'arena>>,
>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
fields: &[ast::Afield],
ctor: C,
) -> Result<InstrSeq<'arena>> {
use ast::Expr;
use ast::Expr_;
let alloc = env.arena;
let (keys, value_instrs): (Vec<String>, _) = fields
.iter()
.map(|f| match f {
ast::Afield::AFkvalue(k, v) => match k {
Expr(_, _, Expr_::String(s)) => Ok((
// FIXME: This is not safe--string literals are binary strings.
// There's no guarantee that they're valid UTF-8.
unsafe { String::from_utf8_unchecked(s.clone().into()) },
emit_expr(e, env, v)?,
)),
_ => {
let mut k = k.clone();
constant_folder::fold_expr(&mut k, e)
.map_err(|e| Error::unrecoverable(format!("{}", e)))?;
match k {
Expr(_, _, Expr_::String(s)) => Ok((
// FIXME: This is not safe--string literals are binary strings.
// There's no guarantee that they're valid UTF-8.
unsafe { String::from_utf8_unchecked(s.into()) },
emit_expr(e, env, v)?,
)),
_ => Err(Error::unrecoverable("Key must be a string")),
}
}
},
_ => Err(Error::unrecoverable("impossible")),
})
.collect::<Result<Vec<(String, InstrSeq<'arena>)>>>()?
.into_iter()
.unzip();
let keys_ = bumpalo::collections::Vec::from_iter_in(
keys.into_iter()
.map(|x| bumpalo::collections::String::from_str_in(x.as_str(), alloc).into_bump_str()),
alloc,
)
.into_bump_slice();
Ok(InstrSeq::gather(vec![
InstrSeq::gather(value_instrs),
emit_pos(pos),
ctor(alloc, e, keys_)?,
]))
}
fn emit_dynamic_collection<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
expr: &ast::Expr,
fields: &[ast::Afield],
) -> Result<InstrSeq<'arena>> {
let pos = &expr.1;
let count = fields.len() as u32;
let emit_dict = |e: &mut Emitter<'arena, 'decl>| {
if is_struct_init(e, fields, true)? {
emit_struct_array(e, env, pos, fields, |alloc, _, x| {
Ok(instr::new_struct_dict(alloc, x))
})
} else {
let ctor = Instruct::Opcode(Opcode::NewDictArray(count));
emit_array(e, env, pos, fields, ctor)
}
};
let emit_collection_helper = |e: &mut Emitter<'arena, 'decl>, ctype| {
if is_struct_init(e, fields, true)? {
Ok(InstrSeq::gather(vec![
emit_struct_array(e, env, pos, fields, |alloc, _, x| {
Ok(instr::new_struct_dict(alloc, x))
})?,
emit_pos(pos),
instr::col_from_array(ctype),
]))
} else {
let ctor = Instruct::Opcode(Opcode::NewDictArray(count));
emit_keyvalue_collection(e, env, pos, fields, ctype, ctor)
}
};
use ast::Expr_;
match &expr.2 {
Expr_::ValCollection(v) if v.0.1 == ast::VcKind::Vec => {
emit_value_only_collection(e, env, pos, fields, |v| Instruct::Opcode(Opcode::NewVec(v)))
}
Expr_::Tuple(_) => {
emit_value_only_collection(e, env, pos, fields, |v| Instruct::Opcode(Opcode::NewVec(v)))
}
Expr_::ValCollection(v) if v.0.1 == ast::VcKind::Keyset => {
emit_value_only_collection(e, env, pos, fields, |v| {
Instruct::Opcode(Opcode::NewKeysetArray(v))
})
}
Expr_::KeyValCollection(v) if v.0.1 == ast::KvcKind::Dict => emit_dict(e),
Expr_::Collection(v) if string_utils::strip_ns(&(v.0).1) == "Set" => {
emit_collection_helper(e, CollectionType::Set)
}
Expr_::ValCollection(v) if v.0.1 == ast::VcKind::Set => {
emit_collection_helper(e, CollectionType::Set)
}
Expr_::Collection(v) if string_utils::strip_ns(&(v.0).1) == "ImmSet" => {
emit_collection_helper(e, CollectionType::ImmSet)
}
Expr_::ValCollection(v) if v.0.1 == ast::VcKind::ImmSet => {
emit_collection_helper(e, CollectionType::ImmSet)
}
Expr_::Collection(v) if string_utils::strip_ns(&(v.0).1) == "Map" => {
emit_collection_helper(e, CollectionType::Map)
}
Expr_::KeyValCollection(v) if v.0.1 == ast::KvcKind::Map => {
emit_collection_helper(e, CollectionType::Map)
}
Expr_::Collection(v) if string_utils::strip_ns(&(v.0).1) == "ImmMap" => {
emit_collection_helper(e, CollectionType::ImmMap)
}
Expr_::KeyValCollection(v) if v.0.1 == ast::KvcKind::ImmMap => {
emit_collection_helper(e, CollectionType::ImmMap)
}
Expr_::Varray(_) => {
let instrs = emit_value_only_collection(e, env, pos, fields, |v| {
Instruct::Opcode(Opcode::NewVec(v))
});
Ok(instrs?)
}
Expr_::Darray(_) => {
if is_struct_init(e, fields, false /* allow_numerics */)? {
let instrs = emit_struct_array(e, env, pos, fields, |alloc, _, arg| {
let instr = instr::new_struct_dict(alloc, arg);
Ok(emit_pos_then(pos, instr))
});
Ok(instrs?)
} else {
let constr = Instruct::Opcode(Opcode::NewDictArray(count));
let instrs = emit_array(e, env, pos, fields, constr);
Ok(instrs?)
}
}
_ => Err(Error::unrecoverable(
"plain PHP arrays cannot be constructed",
)),
}
}
fn emit_value_only_collection<'a, 'arena, 'decl, F: FnOnce(u32) -> Instruct<'arena>>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
fields: &[ast::Afield],
constructor: F,
) -> Result<InstrSeq<'arena>> {
let limit = e.options().max_array_elem_size_on_the_stack;
let inline =
|e: &mut Emitter<'arena, 'decl>, exprs: &[ast::Afield]| -> Result<InstrSeq<'arena>> {
let mut instrs = vec![];
for expr in exprs.iter() {
instrs.push(emit_expr(e, env, expr.value())?)
}
Ok(InstrSeq::gather(vec![
InstrSeq::gather(instrs),
emit_pos(pos),
instr::instr(constructor(exprs.len() as u32)),
]))
};
let outofline =
|e: &mut Emitter<'arena, 'decl>, exprs: &[ast::Afield]| -> Result<InstrSeq<'arena>> {
let mut instrs = vec![];
for expr in exprs.iter() {
instrs.push(emit_expr(e, env, expr.value())?);
instrs.push(instr::add_new_elem_c());
}
Ok(InstrSeq::gather(instrs))
};
let (x1, x2) = fields.split_at(std::cmp::min(fields.len(), limit));
Ok(match (x1, x2) {
([], []) => instr::empty(),
(_, []) => inline(e, x1)?,
_ => {
let outofline_instrs = outofline(e, x2)?;
let inline_instrs = inline(e, x1)?;
InstrSeq::gather(vec![inline_instrs, outofline_instrs])
}
})
}
fn emit_call_isset_expr<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
outer_pos: &Pos,
pk: &ParamKind,
expr: &ast::Expr,
) -> Result<InstrSeq<'arena>> {
if pk.is_pinout() {
return Err(Error::fatal_parse(
outer_pos,
"`isset` cannot take an argument by `inout`",
));
}
let alloc = env.arena;
let pos = &expr.1;
if let Some((base_expr, opt_elem_expr)) = expr.2.as_array_get() {
return Ok(emit_array_get(
e,
env,
pos,
None,
QueryMOp::Isset,
base_expr,
opt_elem_expr.as_ref(),
false,
false,
)?
.0);
}
if let Some((cid, id, _)) = expr.2.as_class_get() {
return emit_class_get(e, env, QueryMOp::Isset, cid, id, ReadonlyOp::Any);
}
if let Some((expr_, prop, nullflavor, _)) = expr.2.as_obj_get() {
return Ok(emit_obj_get(
e,
env,
pos,
QueryMOp::Isset,
expr_,
prop,
nullflavor,
false,
false,
)?
.0);
}
if let Some(lid) = expr.2.as_lvar() {
let name = local_id::get_name(&lid.1);
return Ok(if superglobals::is_any_global(name) {
InstrSeq::gather(vec![
emit_pos(outer_pos),
instr::string(alloc, string_utils::locals::strip_dollar(name)),
emit_pos(outer_pos),
instr::isset_g(),
])
} else if is_local_this(env, &lid.1) && !env.flags.contains(env::Flags::NEEDS_LOCAL_THIS) {
InstrSeq::gather(vec![
emit_pos(outer_pos),
emit_local(e, env, BareThisOp::NoNotice, lid)?,
emit_pos(outer_pos),
instr::is_type_c(IsTypeOp::Null),
instr::not(),
])
} else {
emit_pos_then(outer_pos, instr::isset_l(get_local(e, env, &lid.0, name)?))
});
}
Ok(InstrSeq::gather(vec![
emit_expr(e, env, expr)?,
instr::is_type_c(IsTypeOp::Null),
instr::not(),
]))
}
fn emit_call_isset_exprs<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
exprs: &[(ParamKind, ast::Expr)],
) -> Result<InstrSeq<'arena>> {
match exprs {
[] => Err(Error::fatal_parse(
pos,
"Cannot use isset() without any arguments",
)),
[(pk, expr)] => emit_call_isset_expr(e, env, pos, pk, expr),
_ => {
let its_done = e.label_gen_mut().next_regular();
Ok(InstrSeq::gather(vec![
InstrSeq::gather(
exprs
.iter()
.enumerate()
.map(|(i, (pk, expr))| {
Ok(InstrSeq::gather(vec![
emit_call_isset_expr(e, env, pos, pk, expr)?,
if i < exprs.len() - 1 {
InstrSeq::gather(vec![
instr::dup(),
instr::jmp_z(its_done),
instr::pop_c(),
])
} else {
instr::empty()
},
]))
})
.collect::<Result<Vec<_>>>()?,
),
instr::label(its_done),
]))
}
}
}
fn emit_tag_provenance_here<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
es: &[(ParamKind, ast::Expr)],
) -> Result<InstrSeq<'arena>> {
let pop = if es.len() == 1 {
instr::empty()
} else {
instr::pop_c()
};
Ok(InstrSeq::gather(vec![
emit_exprs_and_error_on_inout(e, env, es, "HH\\tag_provenance_here")?,
emit_pos(pos),
pop,
]))
}
fn emit_array_mark_legacy<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
es: &[(ParamKind, ast::Expr)],
legacy: bool,
) -> Result<InstrSeq<'arena>> {
let default = if es.len() == 1 {
instr::false_()
} else {
instr::empty()
};
let mark = if legacy {
instr::instr(Instruct::Opcode(Opcode::ArrayMarkLegacy))
} else {
instr::instr(Instruct::Opcode(Opcode::ArrayUnmarkLegacy))
};
Ok(InstrSeq::gather(vec![
emit_exprs_and_error_on_inout(e, env, es, "HH\\array_mark_legacy")?,
emit_pos(pos),
default,
mark,
]))
}
fn emit_idx<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
es: &[(ParamKind, ast::Expr)],
) -> Result<InstrSeq<'arena>> {
let default = if es.len() == 2 {
instr::null()
} else {
instr::empty()
};
Ok(InstrSeq::gather(vec![
emit_exprs_and_error_on_inout(e, env, es, "idx")?,
emit_pos(pos),
default,
instr::idx(),
]))
}
fn emit_call<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
expr: &ast::Expr,
targs: &[ast::Targ],
args: &[(ParamKind, ast::Expr)],
uarg: Option<&ast::Expr>,
async_eager_label: Option<Label>,
readonly_return: bool,
) -> Result<InstrSeq<'arena>> {
let alloc = env.arena;
if let Some(ast_defs::Id(_, s)) = expr.as_id() {
let fid = hhbc::FunctionName::<'arena>::from_ast_name(alloc, s);
e.add_function_ref(fid);
}
let readonly_this = match &expr.2 {
ast::Expr_::ReadonlyExpr(_) => true,
_ => false,
};
let fcall_args = get_fcall_args(
alloc,
args,
uarg,
async_eager_label,
env.call_context.clone(),
false,
readonly_return,
readonly_this,
);
match expr.2.as_id() {
None => emit_call_default(e, env, pos, expr, targs, args, uarg, fcall_args),
Some(ast_defs::Id(_, id)) => {
let fq = hhbc::FunctionName::<'arena>::from_ast_name(alloc, id);
let lower_fq_name = fq.unsafe_as_str();
emit_special_function(e, env, pos, targs, args, uarg, lower_fq_name)
.transpose()
.unwrap_or_else(|| {
emit_call_default(e, env, pos, expr, targs, args, uarg, fcall_args)
})
}
}
}
fn emit_call_default<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
expr: &ast::Expr,
targs: &[ast::Targ],
args: &[(ParamKind, ast::Expr)],
uarg: Option<&ast::Expr>,
fcall_args: FCallArgs<'arena>,
) -> Result<InstrSeq<'arena>> {
scope::with_unnamed_locals(e, |em| {
let FCallArgs { num_rets, .. } = &fcall_args;
let num_uninit = num_rets - 1;
let (lhs, fcall) = emit_call_lhs_and_fcall(em, env, expr, fcall_args, targs, None)?;
let (args, inout_setters) = emit_args_inout_setters(em, env, args)?;
let uargs = match uarg {
Some(uarg) => emit_expr(em, env, uarg)?,
None => instr::empty(),
};
Ok((
instr::empty(),
InstrSeq::gather(vec![
InstrSeq::gather(
iter::repeat_with(instr::null_uninit)
.take(num_uninit as usize)
.collect_vec(),
),
lhs,
args,
uargs,
emit_pos(pos),
fcall,
inout_setters,
]),
instr::empty(),
))
})
}
fn is_soft(ual: &[ast::UserAttribute]) -> bool {
ual.iter().any(|ua| user_attributes::is_soft(&ua.name.1))
}
pub fn emit_reified_targs<'a, 'arena, 'decl, I>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
targs: I,
) -> Result<InstrSeq<'arena>>
where
I: Iterator<Item = &'a ast::Hint> + ExactSizeIterator + Clone,
{
let alloc = env.arena;
let current_fun_tparams = env.scope.get_fun_tparams();
let current_cls_tparams = env.scope.get_class_tparams();
let is_in_lambda = env.scope.is_in_lambda();
fn same_as_targs<'a, I>(targs: I, tparams: &[ast::Tparam]) -> bool
where
I: Iterator<Item = &'a ast::Hint> + ExactSizeIterator + Clone,
{
tparams.len() == targs.len()
&& tparams.iter().zip(targs).all(|(tp, ta)| {
ta.1.as_happly().map_or(false, |(id, hs)| {
id.1 == tp.name.1
&& hs.is_empty()
&& !is_soft(&tp.user_attributes)
&& tp.reified.is_reified()
})
})
}
Ok(
if !is_in_lambda && same_as_targs(targs.clone(), current_fun_tparams) {
instr::c_get_l(e.named_local(string_utils::reified::GENERICS_LOCAL_NAME.into()))
} else if !is_in_lambda && same_as_targs(targs.clone(), current_cls_tparams) {
InstrSeq::gather(vec![
instr::check_this(),
instr::base_h(),
instr::query_m(
0,
QueryMOp::CGet,
MemberKey::PT(
hhbc::PropName::from_raw_string(alloc, string_utils::reified::PROP_NAME),
ReadonlyOp::Any,
),
),
])
} else {
let targs_len = targs.len() as u32;
InstrSeq::gather(vec![
InstrSeq::gather(
targs
.map(|h| Ok(emit_reified_arg(e, env, pos, false, h)?.0))
.collect::<Result<Vec<_>>>()?,
),
instr::new_vec(targs_len),
])
},
)
}
fn get_erased_tparams<'a, 'arena>(env: &'a Env<'a, 'arena>) -> Vec<&'a str> {
env.scope
.get_tparams()
.iter()
.filter_map(|tparam| match tparam.reified {
ast::ReifyKind::Erased => Some(tparam.name.1.as_str()),
_ => None,
})
.collect()
}
pub fn has_non_tparam_generics(env: &Env<'_, '_>, hints: &[ast::Hint]) -> bool {
let erased_tparams = get_erased_tparams(env);
hints.iter().any(|hint| {
hint.1
.as_happly()
.map_or(true, |(id, _)| !erased_tparams.contains(&id.1.as_str()))
})
}
fn has_non_tparam_generics_targs(env: &Env<'_, '_>, targs: &[ast::Targ]) -> bool {
let erased_tparams = get_erased_tparams(env);
targs.iter().any(|targ| {
(targ.1)
.1
.as_happly()
.map_or(true, |(id, _)| !erased_tparams.contains(&id.1.as_str()))
})
}
fn from_ast_null_flavor(nullflavor: ast::OgNullFlavor) -> ObjMethodOp {
match nullflavor {
ast::OgNullFlavor::OGNullsafe => ObjMethodOp::NullSafe,
ast::OgNullFlavor::OGNullthrows => ObjMethodOp::NullThrows,
}
}
fn emit_object_expr<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
expr: &ast::Expr,
) -> Result<InstrSeq<'arena>> {
match &expr.2 {
ast::Expr_::Lvar(x) if is_local_this(env, &x.1) => Ok(instr::this()),
_ => emit_expr(e, env, expr),
}
}
fn emit_call_lhs_and_fcall<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
expr: &ast::Expr,
mut fcall_args: FCallArgs<'arena>,
targs: &[ast::Targ],
caller_readonly_opt: Option<&Pos>,
) -> Result<(InstrSeq<'arena>, InstrSeq<'arena>)> {
let ast::Expr(_, pos, expr_) = expr;
use ast::Expr;
use ast::Expr_;
let alloc = env.arena;
let emit_generics =
|e: &mut Emitter<'arena, 'decl>, env, fcall_args: &mut FCallArgs<'arena>| {
let does_not_have_non_tparam_generics = !has_non_tparam_generics_targs(env, targs);
if does_not_have_non_tparam_generics {
Ok(instr::empty())
} else {
fcall_args.flags |= FCallArgsFlags::HasGenerics;
emit_reified_targs(e, env, pos, targs.iter().map(|targ| &targ.1))
}
};
let emit_fcall_func = |e: &mut Emitter<'arena, 'decl>,
env,
expr: &ast::Expr,
fcall_args: FCallArgs<'arena>,
caller_readonly_opt: Option<&Pos>|
-> Result<(InstrSeq<'arena>, InstrSeq<'arena>)> {
let tmp = e.local_gen_mut().get_unnamed();
// if the original expression was wrapped in readonly, emit a readonly expression here
let res = if let Some(p) = caller_readonly_opt {
emit_readonly_expr(e, env, p, expr)?
} else {
emit_expr(e, env, expr)?
};
Ok((
InstrSeq::gather(vec![
instr::null_uninit(),
instr::null_uninit(),
res,
instr::pop_l(tmp),
]),
InstrSeq::gather(vec![instr::push_l(tmp), instr::f_call_func(fcall_args)]),
))
};
match expr_ {
Expr_::ReadonlyExpr(r) => {
// If calling a Readonly expression, first recurse inside to
// handle ObjGet and ClassGet prop call cases. Keep track of the position of the
// outer readonly expression for use later.
// TODO: use the fact that this is a readonly call in HHVM enforcement
emit_call_lhs_and_fcall(e, env, r, fcall_args, targs, Some(pos))
}
Expr_::ObjGet(o) if o.as_ref().3 == ast::PropOrMethod::IsMethod => {
// Case $x->foo(...).
// TODO: utilize caller_readonly_opt here for method calls
let emit_id = |e: &mut Emitter<'arena, 'decl>,
obj,
id,
null_flavor: &ast::OgNullFlavor,
mut fcall_args| {
let name =
hhbc::MethodName::new(Str::new_str(alloc, string_utils::strip_global_ns(id)));
let obj = emit_object_expr(e, env, obj)?;
let generics = emit_generics(e, env, &mut fcall_args)?;
let null_flavor = from_ast_null_flavor(*null_flavor);
Ok((
InstrSeq::gather(vec![obj, instr::null_uninit()]),
InstrSeq::gather(vec![
generics,
instr::f_call_obj_method_d_(fcall_args, name, null_flavor),
]),
))
};
match o.as_ref() {
(obj, Expr(_, _, Expr_::String(id)), null_flavor, _) => {
emit_id(
e,
obj,
// FIXME: This is not safe--string literals are binary strings.
// There's no guarantee that they're valid UTF-8.
unsafe { std::str::from_utf8_unchecked(id.as_slice()) },
null_flavor,
fcall_args,
)
}
(Expr(_, pos, Expr_::New(new_exp)), Expr(_, _, Expr_::Id(id)), null_flavor, _)
if fcall_args.num_args == 0 =>
{
let cexpr =
ClassExpr::class_id_to_class_expr(e, false, false, &env.scope, &new_exp.0);
match &cexpr {
ClassExpr::Id(ast_defs::Id(_, name))
if string_utils::strip_global_ns(name) == "ReflectionClass" =>
{
let fid = match string_utils::strip_global_ns(&id.1) {
"isAbstract" => Some("__SystemLib\\reflection_class_is_abstract"),
"isInterface" => Some("__SystemLib\\reflection_class_is_interface"),
"isFinal" => Some("__SystemLib\\reflection_class_is_final"),
"getName" => Some("__SystemLib\\reflection_class_get_name"),
_ => None,
};
match fid {
None => emit_id(e, &o.as_ref().0, &id.1, null_flavor, fcall_args),
Some(fid) => {
let fcall_args = FCallArgs::new(
FCallArgsFlags::default(),
1,
1,
Slice::empty(),
Slice::empty(),
None,
None,
);
let newobj_instrs = emit_new(e, env, pos, new_exp, true);
Ok((
InstrSeq::gather(vec![
instr::null_uninit(),
instr::null_uninit(),
newobj_instrs?,
]),
InstrSeq::gather(vec![instr::f_call_func_d(
fcall_args,
hhbc::FunctionName::<'arena>::from_ast_name(alloc, fid),
)]),
))
}
}
}
_ => emit_id(e, &o.as_ref().0, &id.1, null_flavor, fcall_args),
}
}
(obj, Expr(_, _, Expr_::Id(id)), null_flavor, _) => {
emit_id(e, obj, &id.1, null_flavor, fcall_args)
}
(obj, method_expr, null_flavor, _) => {
let obj = emit_object_expr(e, env, obj)?;
let tmp = e.local_gen_mut().get_unnamed();
let null_flavor = from_ast_null_flavor(*null_flavor);
Ok((
InstrSeq::gather(vec![
obj,
instr::null_uninit(),
emit_expr(e, env, method_expr)?,
instr::pop_l(tmp),
]),
InstrSeq::gather(vec![
instr::push_l(tmp),
instr::f_call_obj_method(fcall_args, null_flavor),
]),
))
}
}
}
Expr_::ClassConst(cls_const) => {
let (cid, (_, id)) = &**cls_const;
let mut cexpr = ClassExpr::class_id_to_class_expr(e, false, false, &env.scope, cid);
if let ClassExpr::Id(ast_defs::Id(_, name)) = &cexpr {
if let Some(reified_var_cexpr) = get_reified_var_cexpr(e, env, pos, name)? {
cexpr = reified_var_cexpr;
}
}
let method_name =
hhbc::MethodName::new(Str::new_str(alloc, string_utils::strip_global_ns(id)));
Ok(match cexpr {
// Statically known
ClassExpr::Id(ast_defs::Id(_, cname)) => {
let cid = hhbc::ClassName::<'arena>::from_ast_name_and_mangle(alloc, &cname);
e.add_class_ref(cid.clone());
let generics = emit_generics(e, env, &mut fcall_args)?;
(
InstrSeq::gather(vec![instr::null_uninit(), instr::null_uninit()]),
InstrSeq::gather(vec![
generics,
instr::f_call_cls_method_d(fcall_args, method_name, cid),
]),
)
}
ClassExpr::Special(clsref) => {
let generics = emit_generics(e, env, &mut fcall_args)?;
(
InstrSeq::gather(vec![instr::null_uninit(), instr::null_uninit()]),
InstrSeq::gather(vec![
generics,
instr::f_call_cls_method_sd(fcall_args, clsref, method_name),
]),
)
}
ClassExpr::Expr(expr) => {
let generics = emit_generics(e, env, &mut fcall_args)?;
(
InstrSeq::gather(vec![instr::null_uninit(), instr::null_uninit()]),
InstrSeq::gather(vec![
generics,
emit_expr(e, env, &expr)?,
instr::f_call_cls_method_m(
IsLogAsDynamicCallOp::DontLogAsDynamicCall,
fcall_args,
method_name,
),
]),
)
}
ClassExpr::Reified(instrs) => {
let tmp = e.local_gen_mut().get_unnamed();
(
InstrSeq::gather(vec![
instr::null_uninit(),
instr::null_uninit(),
instrs,
instr::pop_l(tmp),
]),
InstrSeq::gather(vec![
instr::push_l(tmp),
instr::f_call_cls_method_m(
IsLogAsDynamicCallOp::DontLogAsDynamicCall,
fcall_args,
method_name,
),
]),
)
}
})
}
Expr_::ClassGet(c) if c.as_ref().2 == ast::PropOrMethod::IsMethod => {
// Case Foo::bar(...).
let (cid, cls_get_expr, _) = &**c;
let mut cexpr = ClassExpr::class_id_to_class_expr(e, false, false, &env.scope, cid);
if let ClassExpr::Id(ast_defs::Id(_, name)) = &cexpr {
if let Some(reified_var_cexpr) = get_reified_var_cexpr(e, env, pos, name)? {
cexpr = reified_var_cexpr;
}
}
let emit_meth_name = |e: &mut Emitter<'arena, 'decl>| match &cls_get_expr {
ast::ClassGetExpr::CGstring((pos, id)) => {
Ok(emit_pos_then(pos, instr::c_get_l(e.named_local(id.into()))))
}
ast::ClassGetExpr::CGexpr(expr) => emit_expr(e, env, expr),
};
Ok(match cexpr {
ClassExpr::Id(cid) => {
let tmp = e.local_gen_mut().get_unnamed();
(
InstrSeq::gather(vec![
instr::null_uninit(),
instr::null_uninit(),
emit_meth_name(e)?,
instr::pop_l(tmp),
]),
InstrSeq::gather(vec![
instr::push_l(tmp),
emit_known_class_id(alloc, e, &cid),
instr::f_call_cls_method(
IsLogAsDynamicCallOp::LogAsDynamicCall,
fcall_args,
),
]),
)
}
ClassExpr::Special(clsref) => {
let tmp = e.local_gen_mut().get_unnamed();
(
InstrSeq::gather(vec![
instr::null_uninit(),
instr::null_uninit(),
emit_meth_name(e)?,
instr::pop_l(tmp),
]),
InstrSeq::gather(vec![
instr::push_l(tmp),
instr::f_call_cls_method_s(fcall_args, clsref),
]),
)
}
ClassExpr::Expr(expr) => {
let cls = e.local_gen_mut().get_unnamed();
let meth = e.local_gen_mut().get_unnamed();
(
InstrSeq::gather(vec![
instr::null_uninit(),
instr::null_uninit(),
emit_expr(e, env, &expr)?,
instr::pop_l(cls),
emit_meth_name(e)?,
instr::pop_l(meth),
]),
InstrSeq::gather(vec![
instr::push_l(meth),
instr::push_l(cls),
instr::class_get_c(),
instr::f_call_cls_method(
IsLogAsDynamicCallOp::LogAsDynamicCall,
fcall_args,
),
]),
)
}
ClassExpr::Reified(instrs) => {
let cls = e.local_gen_mut().get_unnamed();
let meth = e.local_gen_mut().get_unnamed();
(
InstrSeq::gather(vec![
instr::null_uninit(),
instr::null_uninit(),
instrs,
instr::pop_l(cls),
emit_meth_name(e)?,
instr::pop_l(meth),
]),
InstrSeq::gather(vec![
instr::push_l(meth),
instr::push_l(cls),
instr::class_get_c(),
instr::f_call_cls_method(
IsLogAsDynamicCallOp::LogAsDynamicCall,
fcall_args,
),
]),
)
}
})
}
Expr_::Id(id) => {
let FCallArgs {
flags, num_args, ..
} = fcall_args;
let fq_id = match string_utils::strip_global_ns(&id.1) {
"min" if num_args == 2 && !flags.contains(FCallArgsFlags::HasUnpack) => {
hhbc::FunctionName::<'arena>::from_ast_name(alloc, "__SystemLib\\min2")
}
"max" if num_args == 2 && !flags.contains(FCallArgsFlags::HasUnpack) => {
hhbc::FunctionName::<'arena>::from_ast_name(alloc, "__SystemLib\\max2")
}
_ => hhbc::FunctionName::new(Str::new_str(
alloc,
string_utils::strip_global_ns(&id.1),
)),
};
let generics = emit_generics(e, env, &mut fcall_args)?;
Ok((
InstrSeq::gather(vec![instr::null_uninit(), instr::null_uninit()]),
InstrSeq::gather(vec![generics, instr::f_call_func_d(fcall_args, fq_id)]),
))
}
Expr_::String(s) => {
// TODO(hrust) should be able to accept `let fq_id = function::from_raw_string(s);`
let fq_id = hhbc::FunctionName::new(Str::new_str(alloc, s.to_string().as_str()));
let generics = emit_generics(e, env, &mut fcall_args)?;
Ok((
InstrSeq::gather(vec![instr::null_uninit(), instr::null_uninit()]),
InstrSeq::gather(vec![generics, instr::f_call_func_d(fcall_args, fq_id)]),
))
}
_ => emit_fcall_func(e, env, expr, fcall_args, caller_readonly_opt),
}
}
fn get_reified_var_cexpr<'a, 'arena>(
e: &Emitter<'arena, '_>,
env: &Env<'a, 'arena>,
pos: &Pos,
name: &str,
) -> Result<Option<ClassExpr<'arena>>> {
Ok(emit_reified_type_opt(e, env, pos, name)?.map(|instrs| {
ClassExpr::Reified(InstrSeq::gather(vec![
instrs,
instr::base_c(0, MOpMode::Warn),
instr::query_m(
1,
QueryMOp::CGet,
MemberKey::ET(Str::from("classname"), ReadonlyOp::Any),
),
]))
}))
}
fn emit_args_inout_setters<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
args: &[(ParamKind, ast::Expr)],
) -> Result<(InstrSeq<'arena>, InstrSeq<'arena>)> {
let aliases = if has_inout_arg(args) {
inout_locals::collect_written_variables(env, args)
} else {
inout_locals::new_alias_info_map()
};
fn emit_arg_and_inout_setter<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
i: usize,
pk: &ParamKind,
arg: &ast::Expr,
aliases: &inout_locals::AliasInfoMap<'_>,
) -> Result<(InstrSeq<'arena>, InstrSeq<'arena>)> {
use ast::Expr_;
match (pk, &arg.2) {
// inout $var
(ParamKind::Pinout(_), Expr_::Lvar(l)) => {
let local = get_local(e, env, &l.0, local_id::get_name(&l.1))?;
let move_instrs = if !env.flags.contains(env::Flags::IN_TRY)
&& inout_locals::should_move_local_value(e, local, aliases)
{
InstrSeq::gather(vec![instr::null(), instr::pop_l(local)])
} else {
instr::empty()
};
Ok((
InstrSeq::gather(vec![instr::c_get_l(local), move_instrs]),
instr::pop_l(local),
))
}
// inout $arr[...][...]
(ParamKind::Pinout(_), Expr_::ArrayGet(ag)) => {
let array_get_result = emit_array_get_(
e,
env,
&arg.1,
None,
QueryMOp::InOut,
&ag.0,
ag.1.as_ref(),
false,
false,
Some((i, aliases)),
)?
.0;
Ok(match array_get_result {
ArrayGetInstr::Regular(instrs) => {
let setter_base = emit_array_get(
e,
env,
&arg.1,
Some(MOpMode::Define),
QueryMOp::InOut,
&ag.0,
ag.1.as_ref(),
true,
false,
)?
.0;
let (mk, warninstr) = get_elem_member_key(e, env, 0, ag.1.as_ref(), false)?;
let setter = InstrSeq::gather(vec![
warninstr,
setter_base,
instr::set_m(0, mk),
instr::pop_c(),
]);
(instrs, setter)
}
ArrayGetInstr::Inout { load, store } => {
let (mut ld, mut st) = (vec![], vec![store]);
for (instr, local_kind_opt) in load.into_iter() {
match local_kind_opt {
None => ld.push(instr),
Some((l, kind)) => {
let unset = instr::unset_l(l);
let set = match kind {
StoredValueKind::Expr => instr::set_l(l),
_ => instr::pop_l(l),
};
ld.push(instr);
ld.push(set);
st.push(unset);
}
}
}
(InstrSeq::gather(ld), InstrSeq::gather(st))
}
})
}
(ParamKind::Pinout(_), _) => Err(Error::unrecoverable(
"emit_arg_and_inout_setter: Unexpected inout expression type",
)),
_ => Ok((emit_expr(e, env, arg)?, instr::empty())),
}
}
let (instr_args, instr_setters): (Vec<InstrSeq<'_>>, Vec<InstrSeq<'_>>) = args
.iter()
.enumerate()
.map(|(i, (pk, arg))| emit_arg_and_inout_setter(e, env, i, pk, arg, &aliases))
.collect::<Result<Vec<_>>>()?
.into_iter()
.unzip();
let instr_args = InstrSeq::gather(instr_args);
let instr_setters = InstrSeq::gather(instr_setters);
if has_inout_arg(args) {
let retval = e.local_gen_mut().get_unnamed();
Ok((
instr_args,
InstrSeq::gather(vec![
instr::pop_l(retval),
instr_setters,
instr::push_l(retval),
]),
))
} else {
Ok((instr_args, instr::empty()))
}
}
/// You can think of Hack as having two "types" of function calls:
/// - Normal function calls, where the parameters might have non-standard calling convention
/// - "Special calls" where we expect all parameters to be passed in normally, mainly (if not
/// exclusively) object constructors
///
/// This function abstracts over these two kinds of calls: given a list of arguments and two
/// predicates (is this an `inout` argument, is this `readonly`) we build up an `FCallArgs` for the
/// given function call.
fn get_fcall_args_common<'arena, T>(
alloc: &'arena bumpalo::Bump,
args: &[T],
uarg: Option<&ast::Expr>,
async_eager_label: Option<Label>,
context: Option<String>,
lock_while_unwinding: bool,
readonly_return: bool,
readonly_this: bool,
readonly_predicate: fn(&T) -> bool,
is_inout_arg: fn(&T) -> bool,
) -> FCallArgs<'arena> {
let mut flags = FCallArgsFlags::default();
flags.set(FCallArgsFlags::HasUnpack, uarg.is_some());
flags.set(FCallArgsFlags::LockWhileUnwinding, lock_while_unwinding);
flags.set(FCallArgsFlags::EnforceMutableReturn, !readonly_return);
flags.set(FCallArgsFlags::EnforceReadonlyThis, readonly_this);
let readonly_args = if args.iter().any(readonly_predicate) {
Slice::fill_iter(alloc, args.iter().map(readonly_predicate))
} else {
Slice::empty()
};
FCallArgs::new(
flags,
1 + args.iter().filter(|e| is_inout_arg(e)).count() as u32,
args.len() as u32,
Slice::fill_iter(alloc, args.iter().map(is_inout_arg)),
readonly_args,
async_eager_label,
context
.map(|s| bumpalo::collections::String::from_str_in(s.as_str(), alloc).into_bump_str()),
)
}
fn get_fcall_args_no_inout<'arena>(
alloc: &'arena bumpalo::Bump,
args: &[ast::Expr],
uarg: Option<&ast::Expr>,
async_eager_label: Option<Label>,
context: Option<String>,
lock_while_unwinding: bool,
readonly_return: bool,
readonly_this: bool,
) -> FCallArgs<'arena> {
get_fcall_args_common(
alloc,
args,
uarg,
async_eager_label,
context,
lock_while_unwinding,
readonly_return,
readonly_this,
is_readonly_expr,
|_| false,
)
}
fn get_fcall_args<'arena>(
alloc: &'arena bumpalo::Bump,
args: &[(ParamKind, ast::Expr)],
uarg: Option<&ast::Expr>,
async_eager_label: Option<Label>,
context: Option<String>,
lock_while_unwinding: bool,
readonly_return: bool,
readonly_this: bool,
) -> FCallArgs<'arena> {
get_fcall_args_common(
alloc,
args,
uarg,
async_eager_label,
context,
lock_while_unwinding,
readonly_return,
readonly_this,
|(_, expr): &(ParamKind, ast::Expr)| is_readonly_expr(expr),
|(pk, _): &(ParamKind, ast::Expr)| pk.is_pinout(),
)
}
fn is_readonly_expr(e: &ast::Expr) -> bool {
match &e.2 {
ast::Expr_::ReadonlyExpr(_) => true,
_ => false,
}
}
fn has_inout_arg(es: &[(ParamKind, ast::Expr)]) -> bool {
es.iter().any(|(pk, _)| pk.is_pinout())
}
fn emit_special_function<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
targs: &[ast::Targ],
args: &[(ParamKind, ast::Expr)],
uarg: Option<&ast::Expr>,
lower_fq_name: &str,
) -> Result<Option<InstrSeq<'arena>>> {
use ast::Expr;
use ast::Expr_;
let alloc = env.arena;
let nargs = args.len() + uarg.map_or(0, |_| 1);
match (lower_fq_name, args) {
(id, _) if id == special_functions::ECHO => Ok(Some(InstrSeq::gather(
args.iter()
.enumerate()
.map(|(i, arg)| {
Ok(InstrSeq::gather(vec![
emit_expr(e, env, error::expect_normal_paramkind(arg)?)?,
emit_pos(pos),
instr::print(),
if i == nargs - 1 {
instr::empty()
} else {
instr::pop_c()
},
]))
})
.collect::<Result<_>>()?,
))),
("HH\\invariant", args) if args.len() >= 2 => {
let l = e.label_gen_mut().next_regular();
let expr_id = ast::Expr(
(),
pos.clone(),
ast::Expr_::mk_id(ast_defs::Id(
pos.clone(),
"\\HH\\invariant_violation".into(),
)),
);
let call = ast::Expr(
(),
pos.clone(),
ast::Expr_::mk_call(ast::CallExpr { func: expr_id, targs: vec![], args: args[1..].to_owned(), unpacked_arg: uarg.cloned() }),
);
let ignored_expr = emit_ignored_expr(e, env, &Pos::NONE, &call)?;
Ok(Some(InstrSeq::gather(vec![
emit_expr(e, env, error::expect_normal_paramkind(&args[0])?)?,
instr::jmp_nz(l),
ignored_expr,
emit_fatal::emit_fatal_runtime(alloc, pos, "invariant_violation"),
instr::label(l),
instr::null(),
])))
}
("class_exists", &[ref arg1, ..])
| ("trait_exists", &[ref arg1, ..])
| ("interface_exists", &[ref arg1, ..])
if nargs == 1 || nargs == 2 =>
{
let class_kind = match lower_fq_name {
"class_exists" => OODeclExistsOp::Class,
"interface_exists" => OODeclExistsOp::Interface,
"trait_exists" => OODeclExistsOp::Trait,
_ => return Err(Error::unrecoverable("emit_special_function: class_kind")),
};
Ok(Some(InstrSeq::gather(vec![
emit_expr(e, env, error::expect_normal_paramkind(arg1)?)?,
instr::cast_string(),
if nargs == 1 {
instr::true_()
} else {
InstrSeq::gather(vec![
emit_expr(e, env, error::expect_normal_paramkind(&args[1])?)?,
instr::cast_bool(),
])
},
instr::oo_decl_exists(class_kind),
])))
}
("exit", _) | ("die", _) if nargs == 0 || nargs == 1 => Ok(Some(emit_exit(
e,
env,
args.first()
.map(error::expect_normal_paramkind)
.transpose()?,
)?)),
("__SystemLib\\meth_caller", _) => {
// used by meth_caller() to directly emit func ptr
if nargs != 1 {
return Err(Error::fatal_runtime(
pos,
format!("fun() expects exactly 1 parameter, {} given", nargs),
));
}
match args {
// `inout` is dropped here, but it should be impossible to have an expression
// like: `foo(inout "literal")`
[(_, Expr(_, _, Expr_::String(ref func_name)))] => {
Ok(Some(instr::resolve_meth_caller(hhbc::FunctionName::new(
Str::new_str(
alloc,
string_utils::strip_global_ns(
// FIXME: This is not safe--string literals are binary strings.
// There's no guarantee that they're valid UTF-8.
unsafe { std::str::from_utf8_unchecked(func_name.as_slice()) },
),
),
))))
}
_ => Err(Error::fatal_runtime(
pos,
"Constant string expected in fun()",
)),
}
}
("__SystemLib\\__debugger_is_uninit", _) => {
if nargs != 1 {
Err(Error::fatal_runtime(
pos,
format!(
"__debugger_is_uninit() expects exactly 1 parameter {} given",
nargs
),
))
} else {
match args {
// Calling convention is dropped here, but given this is meant for the debugger
// I don't think it particularly matters.
[(_, Expr(_, _, Expr_::Lvar(id)))] => {
Ok(Some(instr::is_unset_l(get_local(e, env, pos, id.name())?)))
}
_ => Err(Error::fatal_runtime(
pos,
"Local variable expected in __debugger_is_uninit()",
)),
}
}
}
("__SystemLib\\get_enum_member_by_label", _) if e.systemlib() => {
let local = match args {
[(pk, Expr(_, _, Expr_::Lvar(id)))] => {
error::ensure_normal_paramkind(pk)?;
get_local(e, env, pos, id.name())
}
_ => Err(Error::fatal_runtime(
pos,
"Argument must be the label argument",
)),
}?;
Ok(Some(InstrSeq::gather(vec![
instr::late_bound_cls(),
instr::cls_cns_l(local),
])))
}
("HH\\global_set", _) => match *args {
[ref gkey, ref gvalue] => Ok(Some(InstrSeq::gather(vec![
emit_expr(e, env, error::expect_normal_paramkind(gkey)?)?,
emit_expr(e, env, error::expect_normal_paramkind(gvalue)?)?,
emit_pos(pos),
instr::set_g(),
instr::pop_c(),
instr::null(),
]))),
_ => Err(Error::fatal_runtime(
pos,
format!("global_set() expects exactly 2 parameters, {} given", nargs),
)),
},
("HH\\global_unset", _) => match *args {
[ref gkey] => Ok(Some(InstrSeq::gather(vec![
emit_expr(e, env, error::expect_normal_paramkind(gkey)?)?,
emit_pos(pos),
instr::unset_g(),
instr::null(),
]))),
_ => Err(Error::fatal_runtime(
pos,
format!(
"global_unset() expects exactly 1 parameter, {} given",
nargs
),
)),
},
("__hhvm_internal_whresult", &[(ref pk, Expr(_, _, Expr_::Lvar(ref param)))])
if e.systemlib() =>
{
error::ensure_normal_paramkind(pk)?;
Ok(Some(InstrSeq::gather(vec![
instr::c_get_l(e.named_local(local_id::get_name(¶m.1).into())),
instr::wh_result(),
])))
}
("HH\\array_mark_legacy", _) if args.len() == 1 || args.len() == 2 => {
Ok(Some(emit_array_mark_legacy(e, env, pos, args, true)?))
}
("HH\\array_unmark_legacy", _) if args.len() == 1 || args.len() == 2 => {
Ok(Some(emit_array_mark_legacy(e, env, pos, args, false)?))
}
("HH\\tag_provenance_here", _) if args.len() == 1 || args.len() == 2 => {
Ok(Some(emit_tag_provenance_here(e, env, pos, args)?))
}
("HH\\embed_type_decl", _)
// `enable_intrinsics_extension` is roughly being used as a proxy here for "are we in
// a non-production environment?" `embed_type_decl` is *not* fit for production use.
// The typechecker doesn't understand it anyhow.
if e.options().hhbc.enable_intrinsics_extension
&& args.is_empty()
&& targs.len() == 1
&& e.decl_provider.is_some() =>
{
match (targs[0].1).1.as_ref() {
aast_defs::Hint_::Happly(ast_defs::Id(_, id), _) => {
let str = match e.decl_provider.as_ref().unwrap().type_decl(id, 0) {
Ok(decl_provider::TypeDecl::Class(cls)) => json!({
"name": cls.name.1,
"final": cls.final_,
"abstract": cls.abstract_,
"kind": (match cls.kind {
ast_defs::ClassishKind::Cclass(_) => "class",
ast_defs::ClassishKind::Cinterface => "interface",
ast_defs::ClassishKind::Ctrait => "trait",
ast_defs::ClassishKind::Cenum => "enum",
ast_defs::ClassishKind::CenumClass(_) => "enum class",
})
})
.to_string(),
Ok(decl_provider::TypeDecl::Typedef(td)) => json!({
"kind": (match td.vis {
aast_defs::TypedefVisibility::Transparent => "type",
aast_defs::TypedefVisibility::Opaque => "newtype",
aast_defs::TypedefVisibility::OpaqueModule => "module newtype",
aast_defs::TypedefVisibility::CaseType => "case type",
})
})
.to_string(),
Err(e) => {
let s = format!("Error: {}", e);
serde_json::to_string(&s).unwrap()
}
};
Ok(Some(emit_adata::typed_value_into_instr(
e,
TypedValue::string(e.alloc.alloc_str(str.as_ref())),
)?))
}
// If we don't have a classish type hint, compile this as
// normal and let the call fail down the line (for now)
_ => Ok(None),
}
}
_ => Ok(
match (args, istype_op(lower_fq_name), is_isexp_op(lower_fq_name)) {
([arg_expr], _, Some(ref h)) => {
let is_expr = emit_is(e, env, pos, h)?;
Some(InstrSeq::gather(vec![
emit_expr(e, env, error::expect_normal_paramkind(arg_expr)?)?,
is_expr,
]))
}
(&[(ref pk, Expr(_, _, Expr_::Lvar(ref arg_id)))], Some(i), _)
if superglobals::is_any_global(arg_id.name()) =>
{
error::ensure_normal_paramkind(pk)?;
Some(InstrSeq::gather(vec![
emit_local(e, env, BareThisOp::NoNotice, arg_id)?,
emit_pos(pos),
instr::is_type_c(i),
]))
}
(&[(ref pk, Expr(_, _, Expr_::Lvar(ref arg_id)))], Some(i), _)
if !is_local_this(env, &arg_id.1) =>
{
error::ensure_normal_paramkind(pk)?;
Some(instr::is_type_l(
get_local(e, env, &arg_id.0, &(arg_id.1).1)?,
i,
))
}
(&[(ref pk, ref arg_expr)], Some(i), _) => {
error::ensure_normal_paramkind(pk)?;
Some(InstrSeq::gather(vec![
emit_expr(e, env, arg_expr)?,
emit_pos(pos),
instr::is_type_c(i),
]))
}
_ => match get_call_builtin_func_info(e, lower_fq_name) {
Some((nargs, i)) if nargs == args.len() => Some(InstrSeq::gather(vec![
emit_exprs_and_error_on_inout(e, env, args, lower_fq_name)?,
emit_pos(pos),
instr::instr(i),
])),
_ => None,
},
},
),
}
}
fn emit_class_meth_native<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
cid: &ast::ClassId,
method_name: MethodName<'arena>,
targs: &[ast::Targ],
) -> Result<InstrSeq<'arena>> {
let alloc = env.arena;
let mut cexpr = ClassExpr::class_id_to_class_expr(e, false, true, &env.scope, cid);
if let ClassExpr::Id(ast_defs::Id(_, name)) = &cexpr {
if let Some(reified_var_cexpr) = get_reified_var_cexpr(e, env, pos, name)? {
cexpr = reified_var_cexpr;
}
}
let has_generics = has_non_tparam_generics_targs(env, targs);
let mut emit_generics = || -> Result<InstrSeq<'arena>> {
emit_reified_targs(e, env, pos, targs.iter().map(|targ| &targ.1))
};
Ok(match cexpr {
ClassExpr::Id(ast_defs::Id(_, name)) if !has_generics => instr::resolve_cls_method_d(
hhbc::ClassName::<'arena>::from_ast_name_and_mangle(alloc, &name),
method_name,
),
ClassExpr::Id(ast_defs::Id(_, name)) => InstrSeq::gather(vec![
emit_generics()?,
instr::resolve_r_cls_method_d(
hhbc::ClassName::<'arena>::from_ast_name_and_mangle(alloc, &name),
method_name,
),
]),
ClassExpr::Special(clsref) if !has_generics => {
instr::resolve_cls_method_s(clsref, method_name)
}
ClassExpr::Special(clsref) => InstrSeq::gather(vec![
emit_generics()?,
instr::resolve_r_cls_method_s(clsref, method_name),
]),
ClassExpr::Reified(instrs) if !has_generics => InstrSeq::gather(vec![
instrs,
instr::class_get_c(),
instr::resolve_cls_method(method_name),
]),
ClassExpr::Reified(instrs) => InstrSeq::gather(vec![
instrs,
instr::class_get_c(),
emit_generics()?,
instr::resolve_r_cls_method(method_name),
]),
ClassExpr::Expr(_) => {
return Err(Error::unrecoverable(
"emit_class_meth_native: ClassExpr::Expr should be impossible",
));
}
})
}
fn get_call_builtin_func_info<'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
id: impl AsRef<str>,
) -> Option<(usize, Instruct<'arena>)> {
match id.as_ref() {
"array_key_exists" => Some((2, Instruct::Opcode(Opcode::AKExists))),
"hphp_array_idx" => Some((3, Instruct::Opcode(Opcode::ArrayIdx))),
"intval" => Some((1, Instruct::Opcode(Opcode::CastInt))),
"boolval" => Some((1, Instruct::Opcode(Opcode::CastBool))),
"strval" => Some((1, Instruct::Opcode(Opcode::CastString))),
"floatval" | "doubleval" => Some((1, Instruct::Opcode(Opcode::CastDouble))),
"HH\\vec" => Some((1, Instruct::Opcode(Opcode::CastVec))),
"HH\\keyset" => Some((1, Instruct::Opcode(Opcode::CastKeyset))),
"HH\\dict" => Some((1, Instruct::Opcode(Opcode::CastDict))),
"HH\\varray" => Some((1, Instruct::Opcode(Opcode::CastVec))),
"HH\\darray" => Some((1, Instruct::Opcode(Opcode::CastDict))),
"HH\\ImplicitContext\\_Private\\set_implicit_context_by_value" if e.systemlib() => {
Some((1, Instruct::Opcode(Opcode::SetImplicitContextByValue)))
}
"HH\\ImplicitContext\\_Private\\create_special_implicit_context" if e.systemlib() => {
Some((2, Instruct::Opcode(Opcode::CreateSpecialImplicitContext)))
}
// TODO: enforce that this returns readonly
"HH\\global_readonly_get" => Some((1, Instruct::Opcode(Opcode::CGetG))),
"HH\\global_get" => Some((1, Instruct::Opcode(Opcode::CGetG))),
"HH\\global_isset" => Some((1, Instruct::Opcode(Opcode::IssetG))),
_ => None,
}
}
fn emit_function_pointer<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
fpid: &ast::FunctionPtrId,
targs: &[ast::Targ],
) -> Result<InstrSeq<'arena>> {
let alloc = env.arena;
let instrs = match fpid {
// This is a function name. Equivalent to HH\fun('str')
ast::FunctionPtrId::FPId(id) => emit_hh_fun(e, env, pos, targs, id.name())?,
// class_meth
ast::FunctionPtrId::FPClassConst(cid, method_name) => {
// TODO(hrust) should accept
// `let method_name = hhbc::MethodName::from_ast_name(&(cc.1).1);`
let method_name = hhbc::MethodName::new(Str::new_str(
alloc,
string_utils::strip_global_ns(&method_name.1),
));
emit_class_meth_native(e, env, pos, cid, method_name, targs)?
}
};
Ok(emit_pos_then(pos, instrs))
}
fn emit_hh_fun<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
targs: &[ast::Targ],
fname: &str,
) -> Result<InstrSeq<'arena>> {
let alloc = env.arena;
let fname = string_utils::strip_global_ns(fname);
if has_non_tparam_generics_targs(env, targs) {
let generics = emit_reified_targs(e, env, pos, targs.iter().map(|targ| &targ.1))?;
Ok(InstrSeq::gather(vec![
generics,
instr::resolve_r_func(hhbc::FunctionName::new(Str::new_str(alloc, fname))),
]))
} else {
Ok(instr::resolve_func(hhbc::FunctionName::new(Str::new_str(
alloc, fname,
))))
}
}
fn emit_is<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
h: &ast::Hint,
) -> Result<InstrSeq<'arena>> {
let (ts_instrs, is_static) = emit_reified_arg(e, env, pos, true, h)?;
Ok(if is_static {
match &*h.1 {
aast_defs::Hint_::Happly(ast_defs::Id(_, id), hs)
if hs.is_empty() && string_utils::strip_hh_ns(id) == typehints::THIS =>
{
instr::is_late_bound_cls()
}
_ => InstrSeq::gather(vec![
get_type_structure_for_hint(
e,
&[],
&IndexSet::new(),
TypeRefinementInHint::Disallowed,
h,
)?,
instr::is_type_struct_c_resolve(),
]),
}
} else {
InstrSeq::gather(vec![ts_instrs, instr::is_type_struct_c_dontresolve()])
})
}
fn istype_op(id: impl AsRef<str>) -> Option<IsTypeOp> {
match id.as_ref() {
"is_int" | "is_integer" | "is_long" => Some(IsTypeOp::Int),
"is_bool" => Some(IsTypeOp::Bool),
"is_float" | "is_real" | "is_double" => Some(IsTypeOp::Dbl),
"is_string" => Some(IsTypeOp::Str),
"is_object" => Some(IsTypeOp::Obj),
"is_null" => Some(IsTypeOp::Null),
"is_scalar" => Some(IsTypeOp::Scalar),
"HH\\is_keyset" => Some(IsTypeOp::Keyset),
"HH\\is_dict" => Some(IsTypeOp::Dict),
"HH\\is_vec" => Some(IsTypeOp::Vec),
"HH\\is_varray" => Some(IsTypeOp::Vec),
"HH\\is_darray" => Some(IsTypeOp::Dict),
"HH\\is_any_array" => Some(IsTypeOp::ArrLike),
"HH\\is_class_meth" => Some(IsTypeOp::ClsMeth),
"HH\\is_fun" => Some(IsTypeOp::Func),
"HH\\is_php_array" => Some(IsTypeOp::LegacyArrLike),
"HH\\is_array_marked_legacy" => Some(IsTypeOp::LegacyArrLike),
"HH\\is_class" => Some(IsTypeOp::Class),
_ => None,
}
}
fn is_isexp_op(lower_fq_id: impl AsRef<str>) -> Option<ast::Hint> {
let h = |s: &str| {
Some(ast::Hint::new(
Pos::NONE,
ast::Hint_::mk_happly(ast::Id(Pos::NONE, s.into()), vec![]),
))
};
match lower_fq_id.as_ref() {
"is_int" | "is_integer" | "is_long" => h("\\HH\\int"),
"is_bool" => h("\\HH\\bool"),
"is_float" | "is_real" | "is_double" => h("\\HH\\float"),
"is_string" => h("\\HH\\string"),
"is_null" => h("\\HH\\void"),
"HH\\is_keyset" => h("\\HH\\keyset"),
"HH\\is_dict" => h("\\HH\\dict"),
"HH\\is_vec" => h("\\HH\\vec"),
_ => None,
}
}
fn emit_eval<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
expr: &ast::Expr,
) -> Result<InstrSeq<'arena>> {
Ok(InstrSeq::gather(vec![
emit_expr(e, env, expr)?,
emit_pos(pos),
instr::eval(),
]))
}
fn has_reified_types<'a, 'arena>(env: &Env<'a, 'arena>) -> bool {
for param in env.scope.get_tparams() {
match param.reified {
oxidized::ast::ReifyKind::Reified => {
return true;
}
_ => {}
}
}
false
}
fn emit_lvar<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
_pos: &Pos,
e: &'a aast_defs::Lid,
) -> Result<InstrSeq<'arena>> {
use aast_defs::Lid;
let Lid(pos, _) = e;
Ok(InstrSeq::gather(vec![
emit_pos(pos),
emit_local(emitter, env, BareThisOp::Notice, e)?,
]))
}
fn emit_lit<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
_env: &Env<'a, 'arena>,
pos: &Pos,
expression: &ast::Expr,
) -> Result<InstrSeq<'arena>> {
let tv = constant_folder::expr_to_typed_value(emitter, expression)
.map_err(|_| Error::unrecoverable("expr_to_typed_value failed"))?;
Ok(emit_pos_then(
pos,
emit_adata::typed_value_into_instr(emitter, tv)?,
))
}
fn emit_is_expr<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
is_expr: &'a (ast::Expr, aast::Hint),
) -> Result<InstrSeq<'arena>> {
let (e, h) = is_expr;
let is = emit_is(emitter, env, pos, h)?;
Ok(InstrSeq::gather(vec![emit_expr(emitter, env, e)?, is]))
}
fn emit_array_get_expr<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
e: &'a (ast::Expr, Option<ast::Expr>),
) -> Result<InstrSeq<'arena>> {
let (base_expr, opt_elem_expr) = e;
Ok(emit_array_get(
emitter,
env,
pos,
None,
QueryMOp::CGet,
base_expr,
opt_elem_expr.as_ref(),
false,
false,
)?
.0)
}
fn emit_pair<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
e: &'a (Option<(ast::Targ, ast::Targ)>, ast::Expr, ast::Expr),
expression: &ast::Expr,
) -> Result<InstrSeq<'arena>> {
let (_, e1, e2) = e.to_owned();
let fields = mk_afvalues(&[e1, e2]);
emit_named_collection(emitter, env, pos, expression, &fields, CollectionType::Pair)
}
fn emit_keyval_collection_expr<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
e: &'a (
(Pos, ast::KvcKind),
Option<(ast::Targ, ast::Targ)>,
Vec<ast::Field>,
),
expression: &ast::Expr,
) -> Result<InstrSeq<'arena>> {
let (kind, _, fields) = e;
let fields = mk_afkvalues(
fields
.iter()
.map(|ast::Field(e1, e2)| (e1.clone(), e2.clone())),
);
let collection_typ = match kind.1 {
aast_defs::KvcKind::Dict => {
let instr = emit_collection(emitter, env, expression, &fields, None)?;
return Ok(emit_pos_then(&kind.0, instr));
}
aast_defs::KvcKind::Map => CollectionType::Map,
aast_defs::KvcKind::ImmMap => CollectionType::ImmMap,
};
emit_named_collection(emitter, env, pos, expression, &fields, collection_typ)
}
fn emit_val_collection<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
e: &'a ((Pos, ast::VcKind), Option<ast::Targ>, Vec<ast::Expr>),
expression: &ast::Expr,
) -> Result<InstrSeq<'arena>> {
let (kind, _, es) = e;
let fields = mk_afvalues(es);
let collection_typ = match kind.1 {
aast_defs::VcKind::Vec | aast_defs::VcKind::Keyset => {
let instr = emit_collection(emitter, env, expression, &fields, None)?;
return Ok(emit_pos_then(&kind.0, instr));
}
aast_defs::VcKind::Vector => CollectionType::Vector,
aast_defs::VcKind::ImmVector => CollectionType::ImmVector,
aast_defs::VcKind::Set => CollectionType::Set,
aast_defs::VcKind::ImmSet => CollectionType::ImmSet,
};
emit_named_collection(emitter, env, pos, expression, &fields, collection_typ)
}
fn emit_varray<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
e: &'a (Option<ast::Targ>, Vec<ast::Expr>),
expression: &ast::Expr,
) -> Result<InstrSeq<'arena>> {
Ok(emit_pos_then(
pos,
emit_collection(emitter, env, expression, &mk_afvalues(&e.1), None)?,
))
}
fn emit_class_get_expr<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
_pos: &Pos,
e: &'a (ast::ClassId, ast::ClassGetExpr, ast::PropOrMethod),
) -> Result<InstrSeq<'arena>> {
// class gets without a readonly expression must be mutable
emit_class_get(
emitter,
env,
QueryMOp::CGet,
&e.0,
&e.1,
ReadonlyOp::Mutable,
)
}
fn emit_darray<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
e: &'a (Option<(ast::Targ, ast::Targ)>, Vec<(ast::Expr, ast::Expr)>),
expression: &ast::Expr,
) -> Result<InstrSeq<'arena>> {
Ok(emit_pos_then(
pos,
emit_collection(
emitter,
env,
expression,
&mk_afkvalues(e.1.iter().cloned()),
None,
)?,
))
}
fn emit_obj_get_expr<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
e: &'a (
ast::Expr,
ast::Expr,
aast_defs::OgNullFlavor,
aast_defs::PropOrMethod,
),
) -> Result<InstrSeq<'arena>> {
Ok(emit_obj_get(
emitter,
env,
pos,
QueryMOp::CGet,
&e.0,
&e.1,
&e.2,
false,
false,
)?
.0)
}
fn emit_label<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
label: &'a (Option<aast_defs::ClassName>, String),
) -> Result<InstrSeq<'arena>> {
use ast::Expr_;
// emitting E#A as __SystemLib\create_opaque_value(OpaqueValue::EnumClassLabel, "A")
let create_opaque_value = "__SystemLib\\create_opaque_value".to_string();
let create_opaque_value = ast_defs::Id(pos.clone(), create_opaque_value);
let create_opaque_value = Expr_::Id(Box::new(create_opaque_value));
let create_opaque_value = ast::Expr((), pos.clone(), create_opaque_value);
// OpaqueValue::EnumClassLabel = 0 defined in
// hphp/runtime/ext/hh/ext_hh.php
let enum_class_label_index = Expr_::Int("0".to_string());
let enum_class_label_index = ast::Expr((), pos.clone(), enum_class_label_index);
let label_string = label.1.to_string();
let label = Expr_::String(bstr::BString::from(label_string));
let label = ast::Expr((), pos.clone(), label);
let call_expr = ast::CallExpr {
func: create_opaque_value,
targs: vec![],
args: vec![
(ParamKind::Pnormal, enum_class_label_index),
(ParamKind::Pnormal, label),
],
unpacked_arg: None,
};
emit_call_expr(emitter, env, pos, None, false, &call_expr)
}
fn emit_call_expr<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
async_eager_label: Option<Label>,
readonly_return: bool,
call_expr: &ast::CallExpr,
) -> Result<InstrSeq<'arena>> {
use ast::Expr;
use ast::Expr_;
let ast::CallExpr {
func,
targs,
args,
unpacked_arg,
} = call_expr;
match (&func.2, &args[..], unpacked_arg) {
(Expr_::Id(id), _, None) if id.1 == pseudo_functions::ISSET => {
emit_call_isset_exprs(e, env, pos, args)
}
(Expr_::Id(id), args, None)
if (id.1 == fb::IDX || id.1 == fb::IDXREADONLY)
&& !e.options().function_is_renamable(id.1.as_bytes().as_bstr())
&& (args.len() == 2 || args.len() == 3) =>
{
emit_idx(e, env, pos, args)
}
(Expr_::Id(id), [(pk, arg1)], None) if id.1 == emitter_special_functions::EVAL => {
error::ensure_normal_paramkind(pk)?;
emit_eval(e, env, pos, arg1)
}
(Expr_::Id(id), [(pk, arg1)], None)
if id.1 == emitter_special_functions::SET_FRAME_METADATA =>
{
error::ensure_normal_paramkind(pk)?;
Ok(InstrSeq::gather(vec![
emit_expr(e, env, arg1)?,
emit_pos(pos),
instr::pop_l(e.named_local("$86metadata".into())),
instr::null(),
]))
}
(Expr_::Id(id), [(pk, arg1)], None)
if id.1 == emitter_special_functions::SET_PRODUCT_ATTRIBUTION_ID
|| id.1 == emitter_special_functions::SET_PRODUCT_ATTRIBUTION_ID_DEFERRED =>
{
error::ensure_normal_paramkind(pk)?;
Ok(InstrSeq::gather(vec![
emit_expr(e, env, arg1)?,
emit_pos(pos),
instr::pop_l(e.named_local("$86productAttributionData".into())),
instr::null(),
]))
}
(Expr_::Id(id), [], None)
if id.1 == pseudo_functions::EXIT || id.1 == pseudo_functions::DIE =>
{
let exit = emit_exit(e, env, None)?;
Ok(emit_pos_then(pos, exit))
}
(Expr_::Id(id), [(pk, arg1)], None)
if id.1 == pseudo_functions::EXIT || id.1 == pseudo_functions::DIE =>
{
error::ensure_normal_paramkind(pk)?;
let exit = emit_exit(e, env, Some(arg1))?;
Ok(emit_pos_then(pos, exit))
}
(Expr_::Id(id), [], _)
if id.1 == emitter_special_functions::SYSTEMLIB_REIFIED_GENERICS
&& e.systemlib()
&& has_reified_types(env) =>
{
// Rewrite __systemlib_reified_generics() to $0ReifiedGenerics,
// but only in systemlib functions that take a reified generic.
let lvar = Expr::new(
(),
pos.clone(),
Expr_::Lvar(Box::new(ast::Lid(
pos.clone(),
local_id::make_unscoped(string_utils::reified::GENERICS_LOCAL_NAME),
))),
);
emit_expr(e, env, &lvar)
}
(_, _, _) => {
let instrs = emit_call(
e,
env,
pos,
func,
targs,
args,
unpacked_arg.as_ref(),
async_eager_label,
readonly_return,
)?;
Ok(emit_pos_then(pos, instrs))
}
}
}
pub fn emit_reified_generic_instrs<'arena>(
e: &Emitter<'arena, '_>,
pos: &Pos,
is_fun: bool,
index: usize,
) -> Result<InstrSeq<'arena>> {
let base = if is_fun {
instr::base_l(
e.named_local(string_utils::reified::GENERICS_LOCAL_NAME.into()),
MOpMode::Warn,
ReadonlyOp::Any,
)
} else {
InstrSeq::gather(vec![
instr::check_this(),
instr::base_h(),
instr::dim_warn_pt(
hhbc::PropName::from_raw_string(e.alloc, string_utils::reified::PROP_NAME),
ReadonlyOp::Any,
),
])
};
Ok(emit_pos_then(
pos,
InstrSeq::gather(vec![
base,
instr::query_m(
0,
QueryMOp::CGet,
MemberKey::EI(index.try_into().unwrap(), ReadonlyOp::Any),
),
]),
))
}
fn emit_reified_type<'a, 'arena>(
e: &Emitter<'arena, '_>,
env: &Env<'a, 'arena>,
pos: &Pos,
name: &str,
) -> Result<InstrSeq<'arena>> {
emit_reified_type_opt(e, env, pos, name)?
.ok_or_else(|| Error::fatal_runtime(&Pos::NONE, "Invalid reified param"))
}
fn emit_reified_type_opt<'a, 'arena>(
e: &Emitter<'arena, '_>,
env: &Env<'a, 'arena>,
pos: &Pos,
name: &str,
) -> Result<Option<InstrSeq<'arena>>> {
let is_in_lambda = env.scope.is_in_lambda();
let cget_instr = |is_fun, i| {
instr::c_get_l(
e.named_local(
string_utils::reified::reified_generic_captured_name(is_fun, i)
.as_str()
.into(),
),
)
};
let check = |is_soft| -> Result<()> {
if is_soft {
Err(Error::fatal_parse(
pos,
format!(
"{} is annotated to be a soft reified generic, it cannot be used until the __Soft annotation is removed",
name
),
))
} else {
Ok(())
}
};
let emit = |(i, is_soft), is_fun| {
check(is_soft)?;
Ok(Some(if is_in_lambda {
cget_instr(is_fun, i)
} else {
emit_reified_generic_instrs(e, pos, is_fun, i)?
}))
};
match is_reified_tparam(env, true, name) {
Some((i, is_soft)) => emit((i, is_soft), true),
None => match is_reified_tparam(env, false, name) {
Some((i, is_soft)) => emit((i, is_soft), false),
None => Ok(None),
},
}
}
fn emit_known_class_id<'arena, 'decl>(
alloc: &'arena bumpalo::Bump,
e: &mut Emitter<'arena, 'decl>,
id: &ast_defs::Id,
) -> InstrSeq<'arena> {
let cid = hhbc::ClassName::from_ast_name_and_mangle(alloc, &id.1);
let cid_string = instr::string(alloc, cid.unsafe_as_str());
e.add_class_ref(cid);
InstrSeq::gather(vec![cid_string, instr::class_get_c()])
}
fn emit_load_class_ref<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
cexpr: ClassExpr<'arena>,
) -> Result<InstrSeq<'arena>> {
let alloc = env.arena;
let instrs = match cexpr {
ClassExpr::Special(SpecialClsRef::SelfCls) => instr::self_cls(),
ClassExpr::Special(SpecialClsRef::LateBoundCls) => instr::late_bound_cls(),
ClassExpr::Special(SpecialClsRef::ParentCls) => instr::parent_cls(),
ClassExpr::Id(id) => emit_known_class_id(alloc, e, &id),
ClassExpr::Expr(expr) => InstrSeq::gather(vec![
emit_pos(pos),
emit_expr(e, env, &expr)?,
instr::class_get_c(),
]),
ClassExpr::Reified(instrs) => {
InstrSeq::gather(vec![emit_pos(pos), instrs, instr::class_get_c()])
}
_ => panic!("Enum value does not match one of listed variants"),
};
Ok(emit_pos_then(pos, instrs))
}
enum NewObjOpInfo<'a, 'arena> {
/// true => top of stack contains type structure
/// false => top of stack contains class
NewObj(bool),
NewObjD(&'a hhbc::ClassName<'arena>, Option<&'a Vec<ast::Targ>>),
NewObjS(hhbc::SpecialClsRef),
}
fn emit_new<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
(cid, targs, args, uarg, _): &(
ast::ClassId,
Vec<ast::Targ>,
Vec<ast::Expr>,
Option<ast::Expr>,
(),
),
is_reflection_class_builtin: bool,
) -> Result<InstrSeq<'arena>> {
let alloc = env.arena;
let resolve_self = match &cid.2.as_ciexpr() {
Some(ci_expr) => match ci_expr.as_id() {
Some(ast_defs::Id(_, n)) if string_utils::is_self(n) => env
.scope
.get_class_tparams()
.iter()
.all(|tp| tp.reified.is_erased()),
Some(ast_defs::Id(_, n)) if string_utils::is_parent(n) => {
env.scope
.get_class()
.map_or(true, |cls| match cls.get_extends() {
[h, ..] => {
h.1.as_happly()
.map_or(true, |(_, l)| !has_non_tparam_generics(env, l))
}
_ => true,
})
}
_ => true,
},
_ => true,
};
use HasGenericsOp as H;
let cexpr = ClassExpr::class_id_to_class_expr(e, false, resolve_self, &env.scope, cid);
let (cexpr, has_generics) = match &cexpr {
ClassExpr::Id(ast_defs::Id(_, name)) => match emit_reified_type_opt(e, env, pos, name)? {
Some(instrs) => {
if targs.is_empty() {
(ClassExpr::Reified(instrs), H::MaybeGenerics)
} else {
return Err(Error::fatal_parse(
pos,
"Cannot have higher kinded reified generics",
));
}
}
None if !has_non_tparam_generics_targs(env, targs) => (cexpr, H::NoGenerics),
None => (cexpr, H::HasGenerics),
},
_ => (cexpr, H::NoGenerics),
};
if is_reflection_class_builtin {
scope::with_unnamed_locals(e, |e| {
let instr_args = emit_exprs(e, env, args)?;
let instr_uargs = match uarg {
None => instr::empty(),
Some(uarg) => emit_expr(e, env, uarg)?,
};
Ok((
instr::empty(),
InstrSeq::gather(vec![instr_args, instr_uargs]),
instr::empty(),
))
})
} else {
let newobj_instrs = match cexpr {
ClassExpr::Id(ast_defs::Id(_, cname)) => {
let id = hhbc::ClassName::<'arena>::from_ast_name_and_mangle(alloc, &cname);
e.add_class_ref(id);
let targs = match has_generics {
H::NoGenerics => None,
H::HasGenerics => Some(targs),
H::MaybeGenerics => {
return Err(Error::unrecoverable(
"Internal error: This case should have been transformed",
));
}
};
emit_new_obj_reified_instrs(e, env, pos, NewObjOpInfo::NewObjD(&id, targs))?
}
ClassExpr::Special(cls_ref) => {
emit_new_obj_reified_instrs(e, env, pos, NewObjOpInfo::NewObjS(cls_ref))?
}
ClassExpr::Reified(instrs) if has_generics == H::MaybeGenerics => {
InstrSeq::gather(vec![
instrs,
emit_new_obj_reified_instrs(e, env, pos, NewObjOpInfo::NewObj(true))?,
])
}
_ => InstrSeq::gather(vec![
emit_load_class_ref(e, env, pos, cexpr)?,
emit_new_obj_reified_instrs(e, env, pos, NewObjOpInfo::NewObj(false))?,
]),
};
scope::with_unnamed_locals(e, |e| {
let alloc = e.alloc;
let instr_args = emit_exprs(e, env, args)?;
let instr_uargs = match uarg {
None => instr::empty(),
Some(uarg) => emit_expr(e, env, uarg)?,
};
Ok((
instr::empty(),
InstrSeq::gather(vec![
newobj_instrs,
instr::dup(),
instr::null_uninit(),
instr_args,
instr_uargs,
emit_pos(pos),
instr::f_call_ctor(get_fcall_args_no_inout(
alloc,
args,
uarg.as_ref(),
None,
env.call_context.clone(),
true,
true, // we do not need to enforce readonly return for constructors
false, // we do not need to enforce readonly this for constructors
)),
instr::pop_c(),
instr::lock_obj(),
]),
instr::empty(),
))
})
}
}
fn emit_new_obj_reified_instrs<'a, 'b, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
op: NewObjOpInfo<'b, 'arena>,
) -> Result<InstrSeq<'arena>> {
use string_utils::reified::INIT_METH_NAME;
let call_reified_init = |obj, ts| -> InstrSeq<'_> {
InstrSeq::gather(vec![
obj,
instr::null_uninit(),
ts,
instr::f_call_obj_method_d(
FCallArgs::new(
FCallArgsFlags::default(),
1,
1,
Slice::empty(),
Slice::empty(),
None,
None,
),
hhbc::MethodName::from_raw_string(env.arena, INIT_METH_NAME),
),
instr::pop_c(),
])
};
scope::with_unnamed_locals(e, |e| {
let class_local = e.local_gen_mut().get_unnamed();
let ts_local = e.local_gen_mut().get_unnamed();
let obj_local = e.local_gen_mut().get_unnamed();
let no_reified_generics_passed_in_label = e.label_gen_mut().next_regular();
let try_parent_has_reified_generics_label = e.label_gen_mut().next_regular();
let end_label = e.label_gen_mut().next_regular();
let try_parent_has_reified_generics = InstrSeq::gather(vec![
instr::label(try_parent_has_reified_generics_label),
instr::c_get_l(class_local),
instr::has_reified_parent(),
instr::jmp_z(end_label),
call_reified_init(
instr::c_get_l(obj_local),
InstrSeq::gather(vec![
instr::new_col(CollectionType::Vector),
instr::cast_vec(),
]),
),
instr::jmp(end_label),
]);
let is_ts_empty = InstrSeq::gather(vec![
instr::null_uninit(),
instr::null_uninit(),
instr::c_get_l(ts_local),
instr::f_call_func_d(
FCallArgs::new(
FCallArgsFlags::default(),
1,
1,
Slice::empty(),
Slice::empty(),
None,
None,
),
hhbc::FunctionName::from_raw_string(env.arena, "count"),
),
instr::int(0),
instr::eq(),
]);
let no_reified_generics_passed_in = InstrSeq::gather(vec![
instr::label(no_reified_generics_passed_in_label),
instr::c_get_l(class_local),
instr::class_has_reified_generics(),
instr::jmp_z(try_parent_has_reified_generics_label),
instr::c_get_l(class_local),
instr::check_cls_rg_soft(),
instr::jmp(end_label),
]);
let reified_generics_passed_in = InstrSeq::gather(vec![
instr::c_get_l(class_local),
instr::class_has_reified_generics(),
instr::jmp_z(try_parent_has_reified_generics_label),
call_reified_init(instr::c_get_l(obj_local), instr::c_get_l(ts_local)),
instr::jmp(end_label),
]);
let instrs = match op {
NewObjOpInfo::NewObj(false) => InstrSeq::gather(vec![
instr::set_l(class_local),
instr::new_obj(),
instr::pop_l(obj_local),
no_reified_generics_passed_in,
try_parent_has_reified_generics,
]),
NewObjOpInfo::NewObj(true) => InstrSeq::gather(vec![
instr::class_get_ts(),
instr::pop_l(ts_local),
instr::set_l(class_local),
instr::new_obj(),
instr::pop_l(obj_local),
is_ts_empty,
instr::jmp_nz(no_reified_generics_passed_in_label),
reified_generics_passed_in,
no_reified_generics_passed_in,
try_parent_has_reified_generics,
]),
NewObjOpInfo::NewObjD(id, targs) => {
let ts = match targs {
Some(targs) => emit_reified_targs(e, env, pos, targs.iter().map(|t| &t.1))?,
None => instr::empty(),
};
let store_cls_and_obj = InstrSeq::gather(vec![
instr::resolve_class(*id),
instr::pop_l(class_local),
instr::new_obj_d(*id),
instr::pop_l(obj_local),
]);
if ts.is_empty() {
InstrSeq::gather(vec![
store_cls_and_obj,
no_reified_generics_passed_in,
try_parent_has_reified_generics,
])
} else {
InstrSeq::gather(vec![
ts,
instr::pop_l(ts_local),
store_cls_and_obj,
reified_generics_passed_in,
try_parent_has_reified_generics,
])
}
}
NewObjOpInfo::NewObjS(cls_ref) => {
let get_cls_instr = match cls_ref {
SpecialClsRef::SelfCls => instr::self_cls(),
SpecialClsRef::LateBoundCls => instr::late_bound_cls(),
SpecialClsRef::ParentCls => instr::parent_cls(),
_ => {
return Err(Error::unrecoverable(
"Internal error: This case should never occur",
));
}
};
let store_cls_and_obj = InstrSeq::gather(vec![
get_cls_instr,
instr::pop_l(class_local),
instr::new_obj_s(cls_ref),
instr::pop_l(obj_local),
]);
let store_ts_if_prop_set = InstrSeq::gather(vec![
instr::c_get_l(class_local),
instr::class_has_reified_generics(),
instr::jmp_z(no_reified_generics_passed_in_label),
instr::c_get_l(class_local),
instr::get_cls_rg_prop(),
instr::set_l(ts_local),
instr::is_type_c(IsTypeOp::Null),
instr::jmp_nz(no_reified_generics_passed_in_label),
]);
InstrSeq::gather(vec![
store_cls_and_obj,
store_ts_if_prop_set,
is_ts_empty,
instr::jmp_nz(no_reified_generics_passed_in_label),
reified_generics_passed_in,
no_reified_generics_passed_in,
try_parent_has_reified_generics,
])
}
};
let unset_locals = InstrSeq::gather(vec![
instr::unset_l(class_local),
instr::unset_l(ts_local),
instr::unset_l(obj_local),
]);
Ok((
instr::empty(),
InstrSeq::gather(vec![
emit_pos(pos),
instrs,
instr::label(end_label),
instr::c_get_l(obj_local),
]),
unset_locals,
))
})
}
fn emit_obj_get<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
query_op: QueryMOp,
expr: &ast::Expr,
prop: &ast::Expr,
nullflavor: &ast_defs::OgNullFlavor,
null_coalesce_assignment: bool,
readonly_get: bool, // obj_get enclosed in readonly expression
) -> Result<(InstrSeq<'arena>, Option<StackIndex>)> {
let readonly_op = if readonly_get {
ReadonlyOp::Any
} else {
ReadonlyOp::Mutable
};
if let Some(ast::Lid(pos, id)) = expr.2.as_lvar() {
if local_id::get_name(id) == special_idents::THIS
&& nullflavor.eq(&ast_defs::OgNullFlavor::OGNullsafe)
{
return Err(Error::fatal_parse(pos, "?-> is not allowed with $this"));
}
}
if let Some(ast_defs::Id(_, s)) = prop.2.as_id() {
if string_utils::is_xhp(s) {
return Ok((emit_xhp_obj_get(e, env, pos, expr, s, nullflavor)?, None));
}
}
let mode = if null_coalesce_assignment {
MOpMode::Warn
} else {
get_querym_op_mode(&query_op)
};
let prop_stack_size = emit_prop_expr(
e,
env,
nullflavor,
0,
prop,
null_coalesce_assignment,
ReadonlyOp::Any,
)?
.2;
let (
base_expr_instrs_begin,
base_expr_instrs_end,
base_setup_instrs,
base_stack_size,
cls_stack_size,
) = emit_base(
e,
env,
expr,
mode,
true,
BareThisOp::Notice,
null_coalesce_assignment,
prop_stack_size,
0,
readonly_op,
)?;
let (mk, prop_instrs, _) = emit_prop_expr(
e,
env,
nullflavor,
cls_stack_size,
prop,
null_coalesce_assignment,
readonly_op,
)?;
let total_stack_size = (prop_stack_size + base_stack_size + cls_stack_size) as usize;
let num_params = if null_coalesce_assignment {
0
} else {
total_stack_size
};
let final_instr = instr::query_m(num_params as u32, query_op, mk);
// Don't pop elems/props from the stack during the lookup for null
// coalesce assignment in case we do a write later.
let querym_n_unpopped = if null_coalesce_assignment {
Some(total_stack_size as u32)
} else {
None
};
let instr = InstrSeq::gather(vec![
base_expr_instrs_begin,
prop_instrs,
base_expr_instrs_end,
emit_pos(pos),
base_setup_instrs,
final_instr,
]);
Ok((instr, querym_n_unpopped))
}
// Get the member key for a property, and return any instructions and
// the size of the stack in the case that the property cannot be
// placed inline in the instruction.
fn emit_prop_expr<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
nullflavor: &ast_defs::OgNullFlavor,
stack_index: StackIndex,
prop: &ast::Expr,
null_coalesce_assignment: bool,
readonly_op: ReadonlyOp,
) -> Result<(MemberKey<'arena>, InstrSeq<'arena>, StackIndex)> {
let alloc = env.arena;
let mk = match &prop.2 {
ast::Expr_::Id(id) => {
let ast_defs::Id(pos, name) = &**id;
if name.starts_with('$') {
MemberKey::PL(get_local(e, env, pos, name)?, readonly_op)
} else {
// Special case for known property name
let pid = hhbc::PropName::<'arena>::from_ast_name(
alloc,
string_utils::strip_global_ns(name),
);
match nullflavor {
ast_defs::OgNullFlavor::OGNullthrows => MemberKey::PT(pid, readonly_op),
ast_defs::OgNullFlavor::OGNullsafe => MemberKey::QT(pid, readonly_op),
}
}
}
// Special case for known property name
ast::Expr_::String(name) => {
let pid: hhbc::PropName<'arena> = hhbc::PropName::<'arena>::from_ast_name(
alloc,
string_utils::strip_global_ns(
// FIXME: This is not safe--string literals are binary strings.
// There's no guarantee that they're valid UTF-8.
unsafe { std::str::from_utf8_unchecked(name.as_slice()) },
),
);
match nullflavor {
ast_defs::OgNullFlavor::OGNullthrows => MemberKey::PT(pid, readonly_op),
ast_defs::OgNullFlavor::OGNullsafe => MemberKey::QT(pid, readonly_op),
}
}
ast::Expr_::Lvar(lid) if !(is_local_this(env, &lid.1)) => MemberKey::PL(
get_local(e, env, &lid.0, local_id::get_name(&lid.1))?,
readonly_op,
),
_ => {
// General case
MemberKey::PC(stack_index, readonly_op)
}
};
// For nullsafe access, insist that property is known
Ok(match mk {
MemberKey::PL(_, _) | MemberKey::PC(_, _)
if nullflavor.eq(&ast_defs::OgNullFlavor::OGNullsafe) =>
{
return Err(Error::fatal_parse(
&prop.1,
"?-> can only be used with scalar property names",
));
}
MemberKey::PC(_, _) => (mk, emit_expr(e, env, prop)?, 1),
MemberKey::PL(local, readonly_op) if null_coalesce_assignment => (
MemberKey::PC(stack_index, readonly_op),
instr::c_get_l(local),
1,
),
_ => (mk, instr::empty(), 0),
})
}
fn emit_xhp_obj_get<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
expr: &ast::Expr,
s: &str,
nullflavor: &ast_defs::OgNullFlavor,
) -> Result<InstrSeq<'arena>> {
use ast::Expr;
use ast::Expr_;
let f = Expr(
(),
pos.clone(),
Expr_::mk_obj_get(
expr.clone(),
Expr(
(),
pos.clone(),
Expr_::mk_id(ast_defs::Id(pos.clone(), "getAttribute".into())),
),
nullflavor.clone(),
ast::PropOrMethod::IsMethod,
),
);
let args = vec![(
ParamKind::Pnormal,
Expr(
(),
pos.clone(),
Expr_::mk_string(string_utils::clean(s).into()),
),
)];
emit_call(e, env, pos, &f, &[], &args[..], None, None, false)
}
fn emit_array_get<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
outer_pos: &Pos,
mode: Option<MOpMode>,
query_op: QueryMOp,
base: &ast::Expr,
elem: Option<&ast::Expr>,
no_final: bool,
null_coalesce_assignment: bool,
) -> Result<(InstrSeq<'arena>, Option<StackIndex>)> {
let result = emit_array_get_(
e,
env,
outer_pos,
mode,
query_op,
base,
elem,
no_final,
null_coalesce_assignment,
None,
)?;
match result {
(ArrayGetInstr::Regular(i), querym_n_unpopped) => Ok((i, querym_n_unpopped)),
(ArrayGetInstr::Inout { .. }, _) => Err(Error::unrecoverable("unexpected inout")),
}
}
fn emit_array_get_<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
outer_pos: &Pos,
mode: Option<MOpMode>,
query_op: QueryMOp,
base_expr: &ast::Expr,
elem: Option<&ast::Expr>,
no_final: bool,
null_coalesce_assignment: bool,
inout_param_info: Option<(usize, &inout_locals::AliasInfoMap<'_>)>,
) -> Result<(ArrayGetInstr<'arena>, Option<StackIndex>)> {
use ast::Expr;
match (base_expr, elem) {
(Expr(_, pos, _), None) if !env.flags.contains(env::Flags::ALLOWS_ARRAY_APPEND) => {
Err(Error::fatal_runtime(pos, "Can't use [] for reading"))
}
_ => {
let local_temp_kind = get_local_temp_kind(env, false, inout_param_info, elem);
let mode = if null_coalesce_assignment {
MOpMode::Warn
} else {
mode.unwrap_or_else(|| get_querym_op_mode(&query_op))
};
let (elem_instrs, elem_stack_size) =
emit_elem(e, env, elem, local_temp_kind, null_coalesce_assignment)?;
let base_result = emit_base_(
e,
env,
base_expr,
mode,
false,
match query_op {
QueryMOp::Isset => BareThisOp::NoNotice,
_ => BareThisOp::Notice,
},
null_coalesce_assignment,
elem_stack_size,
0,
inout_param_info,
ReadonlyOp::Any, // array get on reading has no restrictions
)?;
let cls_stack_size = match &base_result {
ArrayGetBase::Regular(base) => base.cls_stack_size,
ArrayGetBase::Inout { load, .. } => load.cls_stack_size,
};
let (memberkey, warninstr) =
get_elem_member_key(e, env, cls_stack_size, elem, null_coalesce_assignment)?;
let mut querym_n_unpopped = None;
let mut make_final =
|total_stack_size: StackIndex, memberkey: MemberKey<'arena>| -> InstrSeq<'_> {
if no_final {
instr::empty()
} else if null_coalesce_assignment {
querym_n_unpopped = Some(total_stack_size);
instr::query_m(0, query_op, memberkey)
} else {
instr::query_m(total_stack_size, query_op, memberkey)
}
};
let instr = match (base_result, local_temp_kind) {
(ArrayGetBase::Regular(base), None) =>
// neither base nor expression needs to store anything
{
ArrayGetInstr::Regular(InstrSeq::gather(vec![
warninstr,
base.base_instrs,
elem_instrs,
base.cls_instrs,
emit_pos(outer_pos),
base.setup_instrs,
make_final(
base.base_stack_size + base.cls_stack_size + elem_stack_size,
memberkey,
),
]))
}
(ArrayGetBase::Regular(base), Some(local_kind)) => {
// base does not need temp locals but index expression does
let local = e.local_gen_mut().get_unnamed();
let load = vec![
// load base and indexer, value of indexer will be saved in local
(
InstrSeq::gather(vec![base.base_instrs.clone(), elem_instrs]),
Some((local, local_kind)),
),
// finish loading the value
(
InstrSeq::gather(vec![
warninstr,
base.base_instrs,
emit_pos(outer_pos),
base.setup_instrs,
make_final(
base.base_stack_size + base.cls_stack_size + elem_stack_size,
memberkey,
),
]),
None,
),
];
let store = InstrSeq::gather(vec![
emit_store_for_simple_base(
e,
env,
outer_pos,
elem_stack_size,
base_expr,
local,
false,
ReadonlyOp::Any,
)?,
instr::pop_c(),
]);
ArrayGetInstr::Inout { load, store }
}
(
ArrayGetBase::Inout {
load:
ArrayGetBaseData {
mut base_instrs,
cls_instrs,
setup_instrs,
base_stack_size,
cls_stack_size,
},
store,
},
None,
) => {
// base needs temp locals, indexer - does not,
// simply concat two instruction sequences
base_instrs.push((
InstrSeq::gather(vec![
warninstr,
elem_instrs,
cls_instrs,
emit_pos(outer_pos),
setup_instrs,
make_final(
base_stack_size + cls_stack_size + elem_stack_size,
memberkey.clone(),
),
]),
None,
));
let store =
InstrSeq::gather(vec![store, instr::set_m(0, memberkey), instr::pop_c()]);
ArrayGetInstr::Inout {
load: base_instrs,
store,
}
}
(
ArrayGetBase::Inout {
load:
ArrayGetBaseData {
mut base_instrs,
cls_instrs,
setup_instrs,
base_stack_size,
cls_stack_size,
},
store,
},
Some(local_kind),
) => {
// both base and index need temp locals,
// create local for index value
let local = e.local_gen_mut().get_unnamed();
base_instrs.push((elem_instrs, Some((local, local_kind))));
base_instrs.push((
InstrSeq::gather(vec![
warninstr,
cls_instrs,
emit_pos(outer_pos),
setup_instrs,
make_final(
base_stack_size + cls_stack_size + elem_stack_size,
memberkey,
),
]),
None,
));
let store = InstrSeq::gather(vec![
store,
instr::set_m(0, MemberKey::EL(local, ReadonlyOp::Any)),
instr::pop_c(),
]);
ArrayGetInstr::Inout {
load: base_instrs,
store,
}
}
};
Ok((instr, querym_n_unpopped))
}
}
}
fn is_special_class_constant_accessed_with_class_id(cname: &ast::ClassId_, id: &str) -> bool {
let is_self_parent_or_static = match cname {
ast::ClassId_::CIexpr(ast::Expr(_, _, ast::Expr_::Id(id))) => {
string_utils::is_self(&id.1)
|| string_utils::is_parent(&id.1)
|| string_utils::is_static(&id.1)
}
_ => false,
};
string_utils::is_class(id) && !is_self_parent_or_static
}
fn emit_elem<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
elem: Option<&ast::Expr>,
local_temp_kind: Option<StoredValueKind>,
null_coalesce_assignment: bool,
) -> Result<(InstrSeq<'arena>, StackIndex)> {
Ok(match elem {
None => (instr::empty(), 0),
Some(expr) if expr.2.is_int() || expr.2.is_string() => (instr::empty(), 0),
Some(expr) => match &expr.2 {
ast::Expr_::Lvar(x) if !is_local_this(env, &x.1) => {
if local_temp_kind.is_some() {
(
instr::c_get_quiet_l(get_local(e, env, &x.0, local_id::get_name(&x.1))?),
0,
)
} else if null_coalesce_assignment {
(
instr::c_get_l(get_local(e, env, &x.0, local_id::get_name(&x.1))?),
1,
)
} else {
(instr::empty(), 0)
}
}
ast::Expr_::ClassConst(x)
if is_special_class_constant_accessed_with_class_id(&(x.0).2, &(x.1).1) =>
{
(instr::empty(), 0)
}
_ => (emit_expr(e, env, expr)?, 1),
},
})
}
fn get_elem_member_key<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
stack_index: StackIndex,
elem: Option<&ast::Expr>,
null_coalesce_assignment: bool,
) -> Result<(MemberKey<'arena>, InstrSeq<'arena>)> {
use ast::ClassId_ as CI_;
use ast::Expr;
use ast::Expr_;
let alloc = env.arena;
match elem {
// ELement missing (so it's array append)
None => Ok((MemberKey::W, instr::empty())),
Some(elem_expr) => match &elem_expr.2 {
// Special case for local
Expr_::Lvar(x) if !is_local_this(env, &x.1) => Ok((
{
if null_coalesce_assignment {
MemberKey::EC(stack_index, ReadonlyOp::Any)
} else {
MemberKey::EL(
get_local(e, env, &x.0, local_id::get_name(&x.1))?,
ReadonlyOp::Any,
)
}
},
instr::empty(),
)),
// Special case for literal integer
Expr_::Int(s) => match constant_folder::expr_to_typed_value(e, elem_expr) {
Ok(TypedValue::Int(i)) => Ok((MemberKey::EI(i, ReadonlyOp::Any), instr::empty())),
_ => Err(Error::unrecoverable(format!(
"{} is not a valid integer index",
s
))),
},
// Special case for literal string
Expr_::String(s) => {
// FIXME: This is not safe--string literals are binary strings.
// There's no guarantee that they're valid UTF-8.
let s = unsafe { std::str::from_utf8_unchecked(s.as_slice()) };
let s = bumpalo::collections::String::from_str_in(s, alloc).into_bump_str();
Ok((MemberKey::ET(Str::from(s), ReadonlyOp::Any), instr::empty()))
}
// Special case for class name
Expr_::ClassConst(x)
if is_special_class_constant_accessed_with_class_id(&(x.0).2, &(x.1).1) =>
{
let cname = match (&(x.0).2, env.scope.get_class()) {
(CI_::CIself, Some(cd)) => string_utils::strip_global_ns(cd.get_name_str()),
(CI_::CIexpr(Expr(_, _, Expr_::Id(id))), _) => {
string_utils::strip_global_ns(&id.1)
}
(CI_::CI(id), _) => string_utils::strip_global_ns(&id.1),
_ => {
return Err(Error::unrecoverable(
"Unreachable due to is_special_class_constant_accessed_with_class_id",
));
}
};
let fq_id = hhbc::ClassName::<'arena>::from_ast_name_and_mangle(alloc, cname)
.unsafe_as_str();
Ok((
MemberKey::ET(Str::from(fq_id), ReadonlyOp::Any),
instr::raise_class_string_conversion_warning(),
))
}
_ => {
// General case
Ok((MemberKey::EC(stack_index, ReadonlyOp::Any), instr::empty()))
}
},
}
}
fn emit_store_for_simple_base<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
elem_stack_size: StackIndex,
base: &ast::Expr,
local: Local,
is_base: bool,
readonly_op: ReadonlyOp,
) -> Result<InstrSeq<'arena>> {
let (base_expr_instrs_begin, base_expr_instrs_end, base_setup_instrs, _, _) = emit_base(
e,
env,
base,
MOpMode::Define,
false,
BareThisOp::Notice,
false,
elem_stack_size,
0,
readonly_op,
)?;
let memberkey = MemberKey::EL(local, ReadonlyOp::Any);
Ok(InstrSeq::gather(vec![
base_expr_instrs_begin,
base_expr_instrs_end,
emit_pos(pos),
base_setup_instrs,
if is_base {
instr::dim(MOpMode::Define, memberkey)
} else {
instr::set_m(0, memberkey)
},
]))
}
fn get_querym_op_mode(query_op: &QueryMOp) -> MOpMode {
match *query_op {
QueryMOp::InOut => MOpMode::InOut,
QueryMOp::CGet => MOpMode::Warn,
_ => MOpMode::None,
}
}
fn emit_class_get<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
query_op: QueryMOp,
cid: &ast::ClassId,
prop: &ast::ClassGetExpr,
readonly_op: ReadonlyOp,
) -> Result<InstrSeq<'arena>> {
let cexpr = ClassExpr::class_id_to_class_expr(e, false, false, &env.scope, cid);
let (cexpr_seq1, cexpr_seq2) = emit_class_expr(e, env, cexpr, prop)?;
Ok(InstrSeq::gather(vec![
cexpr_seq1,
cexpr_seq2,
match query_op {
QueryMOp::CGet => instr::c_get_s(readonly_op),
QueryMOp::Isset => instr::isset_s(),
QueryMOp::CGetQuiet => {
return Err(Error::unrecoverable("emit_class_get: CGetQuiet"));
}
QueryMOp::InOut => return Err(Error::unrecoverable("emit_class_get: InOut")),
_ => panic!("Enum value does not match one of listed variants"),
},
]))
}
fn emit_conditional_expr<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
etest: &ast::Expr,
etrue: Option<&ast::Expr>,
efalse: &ast::Expr,
) -> Result<InstrSeq<'arena>> {
Ok(match etrue.as_ref() {
Some(etrue) => {
let false_label = e.label_gen_mut().next_regular();
let end_label = e.label_gen_mut().next_regular();
let r = emit_jmpz(e, env, etest, false_label)?;
// only emit false branch if false_label is used
let false_branch = if r.is_label_used {
InstrSeq::gather(vec![instr::label(false_label), emit_expr(e, env, efalse)?])
} else {
instr::empty()
};
// only emit true branch if there is fallthrough from condition
let true_branch = if r.is_fallthrough {
InstrSeq::gather(vec![
emit_expr(e, env, etrue)?,
emit_pos(pos),
instr::jmp(end_label),
])
} else {
instr::empty()
};
InstrSeq::gather(vec![
r.instrs,
true_branch,
false_branch,
// end_label is used to jump out of true branch so they should be emitted together
if r.is_fallthrough {
instr::label(end_label)
} else {
instr::empty()
},
])
}
None => {
let end_label = e.label_gen_mut().next_regular();
let efalse_instr = emit_expr(e, env, efalse)?;
let etest_instr = emit_expr(e, env, etest)?;
InstrSeq::gather(vec![
etest_instr,
instr::dup(),
instr::jmp_nz(end_label),
instr::pop_c(),
efalse_instr,
instr::label(end_label),
])
}
})
}
fn emit_local<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
notice: BareThisOp,
lid: &aast_defs::Lid,
) -> Result<InstrSeq<'arena>> {
let alloc = env.arena;
let ast::Lid(pos, id) = lid;
let id_name = local_id::get_name(id);
if superglobals::is_superglobal(id_name) {
Ok(InstrSeq::gather(vec![
instr::string(alloc, string_utils::locals::strip_dollar(id_name)),
emit_pos(pos),
instr::c_get_g(),
]))
} else {
Ok(
if is_local_this(env, id) && !env.flags.contains(EnvFlags::NEEDS_LOCAL_THIS) {
emit_pos_then(pos, instr::bare_this(notice))
} else {
let local = get_local(e, env, pos, id_name)?;
instr::c_get_l(local)
},
)
}
}
fn emit_class_const<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
cid: &ast::ClassId,
id: &ast_defs::Pstring,
) -> Result<InstrSeq<'arena>> {
let alloc = env.arena;
let mut cexpr = ClassExpr::class_id_to_class_expr(e, false, true, &env.scope, cid);
if let ClassExpr::Id(ast_defs::Id(_, name)) = &cexpr {
if let Some(reified_var_cexpr) = get_reified_var_cexpr(e, env, pos, name)? {
cexpr = reified_var_cexpr;
}
}
match cexpr {
ClassExpr::Id(ast_defs::Id(pos, name)) => {
let cid = hhbc::ClassName::from_ast_name_and_mangle(alloc, &name);
Ok(if string_utils::is_class(&id.1) {
emit_pos_then(&pos, instr::lazy_class(cid))
} else {
e.add_class_ref(cid.clone());
// TODO(hrust) enabel `let const_id = hhbc::ConstName::from_ast_name(&id.1);`,
// `from_ast_name` should be able to accpet Cow<str>
let const_id =
hhbc::ConstName::new(Str::new_str(alloc, string_utils::strip_global_ns(&id.1)));
emit_pos_then(&pos, instr::cls_cns_d(const_id, cid))
})
}
_ => {
let load_const = if string_utils::is_class(&id.1) {
instr::lazy_class_from_class()
} else {
// TODO(hrust) enable `let const_id = hhbc::ConstName::from_ast_name(&id.1);`,
// `from_ast_name` should be able to accpet Cow<str>
let const_id =
hhbc::ConstName::new(Str::new_str(alloc, string_utils::strip_global_ns(&id.1)));
instr::cls_cns(const_id)
};
Ok(InstrSeq::gather(vec![
emit_load_class_ref(e, env, pos, cexpr)?,
load_const,
]))
}
}
}
fn emit_unop<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
(uop, expr): &(ast_defs::Uop, ast::Expr),
) -> Result<InstrSeq<'arena>> {
use ast_defs::Uop;
match uop {
Uop::Utild | Uop::Unot => Ok(InstrSeq::gather(vec![
emit_expr(e, env, expr)?,
emit_pos_then(pos, from_unop(uop)?),
])),
Uop::Uplus | Uop::Uminus => Ok(InstrSeq::gather(vec![
emit_pos(pos),
instr::int(0),
emit_expr(e, env, expr)?,
emit_pos_then(pos, from_unop(uop)?),
])),
Uop::Uincr | Uop::Udecr | Uop::Upincr | Uop::Updecr => emit_lval_op(
e,
env,
pos,
LValOp::IncDec(unop_to_incdec_op(uop)?),
expr,
None,
false,
),
Uop::Usilence => e.local_scope(|e| {
let temp_local = e.local_gen_mut().get_unnamed();
Ok(InstrSeq::gather(vec![
emit_pos(pos),
instr::silence_start(temp_local),
{
let try_instrs = emit_expr(e, env, expr)?;
let catch_instrs =
InstrSeq::gather(vec![emit_pos(pos), instr::silence_end(temp_local)]);
scope::create_try_catch(
e.label_gen_mut(),
None,
false, /* skip_throw */
try_instrs,
catch_instrs,
)
},
emit_pos(pos),
instr::silence_end(temp_local),
]))
}),
}
}
fn unop_to_incdec_op(op: &ast_defs::Uop) -> Result<IncDecOp> {
use ast_defs::Uop;
match op {
Uop::Uincr => Ok(IncDecOp::PreInc),
Uop::Udecr => Ok(IncDecOp::PreDec),
Uop::Upincr => Ok(IncDecOp::PostInc),
Uop::Updecr => Ok(IncDecOp::PostDec),
_ => Err(Error::unrecoverable("invalid incdec op")),
}
}
fn from_unop<'arena>(op: &ast_defs::Uop) -> Result<InstrSeq<'arena>> {
use ast_defs::Uop;
Ok(match op {
Uop::Utild => instr::bit_not(),
Uop::Unot => instr::not(),
Uop::Uplus => instr::add(),
Uop::Uminus => instr::sub(),
_ => {
return Err(Error::unrecoverable(
"this unary operation cannot be translated",
));
}
})
}
fn binop_to_setopop(op: &ast_defs::Bop) -> Option<SetOpOp> {
use ast_defs::Bop;
match op {
Bop::Plus => Some(SetOpOp::PlusEqual),
Bop::Minus => Some(SetOpOp::MinusEqual),
Bop::Star => Some(SetOpOp::MulEqual),
Bop::Slash => Some(SetOpOp::DivEqual),
Bop::Starstar => Some(SetOpOp::PowEqual),
Bop::Amp => Some(SetOpOp::AndEqual),
Bop::Bar => Some(SetOpOp::OrEqual),
Bop::Xor => Some(SetOpOp::XorEqual),
Bop::Ltlt => Some(SetOpOp::SlEqual),
Bop::Gtgt => Some(SetOpOp::SrEqual),
Bop::Percent => Some(SetOpOp::ModEqual),
Bop::Dot => Some(SetOpOp::ConcatEqual),
_ => None,
}
}
fn optimize_null_checks<'arena, 'decl>(e: &Emitter<'arena, 'decl>) -> bool {
e.options().compiler_flags.optimize_null_checks
}
fn from_binop<'arena>(op: &ast_defs::Bop) -> Result<InstrSeq<'arena>> {
use ast_defs::Bop as B;
Ok(match op {
B::Plus => instr::add(),
B::Minus => instr::sub(),
B::Star => instr::mul(),
B::Slash => instr::div(),
B::Eqeq => instr::eq(),
B::Eqeqeq => instr::same(),
B::Starstar => instr::pow(),
B::Diff => instr::neq(),
B::Diff2 => instr::n_same(),
B::Lt => instr::lt(),
B::Lte => instr::lte(),
B::Gt => instr::gt(),
B::Gte => instr::gte(),
B::Dot => instr::concat(),
B::Amp => instr::bit_and(),
B::Bar => instr::bit_or(),
B::Ltlt => instr::shl(),
B::Gtgt => instr::shr(),
B::Cmp => instr::cmp(),
B::Percent => instr::mod_(),
B::Xor => instr::bit_xor(),
B::Eq(_) => {
return Err(Error::unrecoverable("assignment is emitted differently"));
}
B::QuestionQuestion => {
return Err(Error::unrecoverable(
"null coalescence is emitted differently",
));
}
B::Barbar | B::Ampamp => {
return Err(Error::unrecoverable(
"short-circuiting operator cannot be generated as a simple binop",
));
}
})
}
fn emit_first_expr<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
expr: &ast::Expr,
) -> Result<(InstrSeq<'arena>, bool)> {
Ok(match &expr.2 {
ast::Expr_::Lvar(l)
if !((is_local_this(env, &l.1) && !env.flags.contains(EnvFlags::NEEDS_LOCAL_THIS))
|| superglobals::is_any_global(local_id::get_name(&l.1))) =>
{
(
instr::c_get_l_2(get_local(e, env, &l.0, local_id::get_name(&l.1))?),
true,
)
}
_ => (emit_expr(e, env, expr)?, false),
})
}
pub fn emit_two_exprs<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
outer_pos: &Pos,
e1: &ast::Expr,
e2: &ast::Expr,
) -> Result<InstrSeq<'arena>> {
let (instrs1, is_under_top) = emit_first_expr(e, env, e1)?;
let instrs2 = emit_expr(e, env, e2)?;
let instrs2_is_var = e2.2.is_lvar();
Ok(InstrSeq::gather(if is_under_top {
if instrs2_is_var {
vec![emit_pos(outer_pos), instrs2, instrs1]
} else {
vec![instrs2, emit_pos(outer_pos), instrs1]
}
} else if instrs2_is_var {
vec![instrs1, emit_pos(outer_pos), instrs2]
} else {
vec![instrs1, instrs2, emit_pos(outer_pos)]
}))
}
fn emit_readonly_expr<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
expr: &aast::Expr<(), ()>,
) -> Result<InstrSeq<'arena>> {
match &expr.2 {
aast::Expr_::ObjGet(x) => {
Ok(emit_obj_get(e, env, pos, QueryMOp::CGet, &x.0, &x.1, &x.2, false, true)?.0)
}
aast::Expr_::Call(c) => emit_call_expr(e, env, pos, None, true, c),
aast::Expr_::ClassGet(x) => {
emit_class_get(e, env, QueryMOp::CGet, &x.0, &x.1, ReadonlyOp::Any)
}
_ => emit_expr(e, env, expr),
}
}
fn emit_quiet_expr<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
expr: &ast::Expr,
null_coalesce_assignment: bool,
) -> Result<(InstrSeq<'arena>, Option<StackIndex>)> {
match &expr.2 {
ast::Expr_::Lvar(lid) if !is_local_this(env, &lid.1) => Ok((
instr::c_get_quiet_l(get_local(e, env, pos, local_id::get_name(&lid.1))?),
None,
)),
ast::Expr_::ArrayGet(x) => emit_array_get(
e,
env,
pos,
None,
QueryMOp::CGetQuiet,
&x.0,
x.1.as_ref(),
false,
null_coalesce_assignment,
),
ast::Expr_::ObjGet(x) if x.as_ref().3 == ast::PropOrMethod::IsProp => emit_obj_get(
e,
env,
pos,
QueryMOp::CGetQuiet,
&x.0,
&x.1,
&x.2,
null_coalesce_assignment,
false,
),
_ => Ok((emit_expr(e, env, expr)?, None)),
}
}
fn emit_null_coalesce_assignment<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
e1: &ast::Expr,
e2: &ast::Expr,
) -> Result<InstrSeq<'arena>> {
let end_label = e.label_gen_mut().next_regular();
let do_set_label = e.label_gen_mut().next_regular();
let l_nonnull = e.local_gen_mut().get_unnamed();
let (quiet_instr, querym_n_unpopped) = emit_quiet_expr(e, env, pos, e1, true)?;
let emit_popc_n = |n_unpopped| match n_unpopped {
Some(n) => InstrSeq::gather(
iter::repeat_with(instr::pop_c)
.take(n as usize)
.collect_vec(),
),
None => instr::empty(),
};
Ok(InstrSeq::gather(vec![
quiet_instr,
instr::dup(),
instr::is_type_c(IsTypeOp::Null),
instr::jmp_nz(do_set_label),
instr::pop_l(l_nonnull),
emit_popc_n(querym_n_unpopped),
instr::push_l(l_nonnull),
instr::jmp(end_label),
instr::label(do_set_label),
instr::pop_c(),
emit_lval_op(e, env, pos, LValOp::Set, e1, Some(e2), true)?,
instr::label(end_label),
]))
}
fn emit_short_circuit_op<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
expr: &ast::Expr,
) -> Result<InstrSeq<'arena>> {
let its_true = e.label_gen_mut().next_regular();
let its_done = e.label_gen_mut().next_regular();
let jmp_instrs = emit_jmpnz(e, env, expr, its_true)?;
Ok(if jmp_instrs.is_fallthrough {
InstrSeq::gather(vec![
jmp_instrs.instrs,
emit_pos(pos),
instr::false_(),
instr::jmp(its_done),
if jmp_instrs.is_label_used {
InstrSeq::gather(vec![instr::label(its_true), emit_pos(pos), instr::true_()])
} else {
instr::empty()
},
instr::label(its_done),
])
} else {
InstrSeq::gather(vec![
jmp_instrs.instrs,
if jmp_instrs.is_label_used {
InstrSeq::gather(vec![instr::label(its_true), emit_pos(pos), instr::true_()])
} else {
instr::empty()
},
])
})
}
fn emit_binop<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
expr: &ast::Expr,
) -> Result<InstrSeq<'arena>> {
let ast::Binop {
bop: op,
lhs: e1,
rhs: e2,
} = expr.2.as_binop().unwrap();
use ast_defs::Bop as B;
match op {
B::Ampamp | B::Barbar => emit_short_circuit_op(e, env, pos, expr),
B::Eq(None) => emit_lval_op(e, env, pos, LValOp::Set, e1, Some(e2), false),
B::Eq(Some(eop)) if eop.is_question_question() => {
emit_null_coalesce_assignment(e, env, pos, e1, e2)
}
B::Eq(Some(eop)) => match binop_to_setopop(eop) {
None => Err(Error::unrecoverable("illegal eq op")),
Some(op) => emit_lval_op(e, env, pos, LValOp::SetOp(op), e1, Some(e2), false),
},
B::QuestionQuestion => {
let end_label = e.label_gen_mut().next_regular();
let rhs = emit_expr(e, env, e2)?;
Ok(InstrSeq::gather(vec![
emit_quiet_expr(e, env, pos, e1, false)?.0,
instr::dup(),
instr::is_type_c(IsTypeOp::Null),
instr::not(),
instr::jmp_nz(end_label),
instr::pop_c(),
rhs,
instr::label(end_label),
]))
}
_ => {
let default = |e: &mut Emitter<'arena, 'decl>| {
Ok(InstrSeq::gather(vec![
emit_two_exprs(e, env, pos, e1, e2)?,
from_binop(op)?,
]))
};
if optimize_null_checks(e) {
match op {
B::Eqeqeq if e2.2.is_null() => emit_is_null(e, env, e1),
B::Eqeqeq if e1.2.is_null() => emit_is_null(e, env, e2),
B::Diff2 if e2.2.is_null() => Ok(InstrSeq::gather(vec![
emit_is_null(e, env, e1)?,
instr::not(),
])),
B::Diff2 if e1.2.is_null() => Ok(InstrSeq::gather(vec![
emit_is_null(e, env, e2)?,
instr::not(),
])),
_ => default(e),
}
} else {
default(e)
}
}
}
}
fn emit_pipe<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
(_, e1, e2): &(aast_defs::Lid, ast::Expr, ast::Expr),
) -> Result<InstrSeq<'arena>> {
let lhs_instrs = emit_expr(e, env, e1)?;
scope::with_unnamed_local(e, |e, local| {
// TODO(hrust) avoid cloning env
let mut pipe_env = env.clone();
pipe_env.with_pipe_var(local);
let rhs_instrs = emit_expr(e, &pipe_env, e2)?;
Ok((
InstrSeq::gather(vec![lhs_instrs, instr::pop_l(local)]),
rhs_instrs,
instr::unset_l(local),
))
})
}
fn emit_as<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
(expr, h, is_nullable): &(ast::Expr, aast_defs::Hint, bool),
) -> Result<InstrSeq<'arena>> {
e.local_scope(|e| {
let arg_local = e.local_gen_mut().get_unnamed();
let type_struct_local = e.local_gen_mut().get_unnamed();
let (ts_instrs, is_static) = emit_reified_arg(e, env, pos, true, h)?;
let then_label = e.label_gen_mut().next_regular();
let done_label = e.label_gen_mut().next_regular();
let main_block = |ts_instrs, resolve| {
InstrSeq::gather(vec![
ts_instrs,
instr::set_l(type_struct_local),
match resolve {
TypeStructResolveOp::Resolve => instr::is_type_struct_c_resolve(),
TypeStructResolveOp::DontResolve => instr::is_type_struct_c_dontresolve(),
_ => panic!("Enum value does not match one of listed variants"),
},
instr::jmp_nz(then_label),
if *is_nullable {
InstrSeq::gather(vec![instr::null(), instr::jmp(done_label)])
} else {
InstrSeq::gather(vec![
instr::push_l(arg_local),
instr::push_l(type_struct_local),
instr::throw_as_type_struct_exception(),
])
},
])
};
let i2 = if is_static {
main_block(
get_type_structure_for_hint(
e,
&[],
&IndexSet::new(),
TypeRefinementInHint::Disallowed,
h,
)?,
TypeStructResolveOp::Resolve,
)
} else {
main_block(ts_instrs, TypeStructResolveOp::DontResolve)
};
let i1 = emit_expr(e, env, expr)?;
Ok(InstrSeq::gather(vec![
i1,
instr::set_l(arg_local),
i2,
instr::label(then_label),
instr::push_l(arg_local),
instr::unset_l(type_struct_local),
instr::label(done_label),
]))
})
}
fn emit_cast<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
hint: &aast_defs::Hint_,
expr: &ast::Expr,
) -> Result<InstrSeq<'arena>> {
use aast_defs::Hint_ as H_;
let op = match hint {
H_::Happly(ast_defs::Id(_, id), hints) if hints.is_empty() => {
let id = string_utils::strip_ns(id);
match string_utils::strip_hh_ns(id).as_ref() {
typehints::INT => instr::cast_int(),
typehints::BOOL => instr::cast_bool(),
typehints::STRING => instr::cast_string(),
typehints::FLOAT => instr::cast_double(),
_ => {
return Err(Error::fatal_parse(
pos,
format!("Invalid cast type: {}", id),
));
}
}
}
_ => return Err(Error::fatal_parse(pos, "Invalid cast type")),
};
Ok(InstrSeq::gather(vec![
emit_expr(e, env, expr)?,
emit_pos(pos),
op,
]))
}
pub fn emit_unset_expr<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
expr: &ast::Expr,
) -> Result<InstrSeq<'arena>> {
emit_lval_op_nonlist(
e,
env,
&expr.1,
LValOp::Unset,
expr,
instr::empty(),
0,
false,
false,
)
}
pub fn emit_set_range_expr<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
pos: &Pos,
name: &str,
kind: SetRange,
args: &[(ParamKind, ast::Expr)],
) -> Result<InstrSeq<'arena>> {
let raise_fatal = |msg: &str| Err(Error::fatal_parse(pos, format!("{} {}", name, msg)));
// TODO(hgoldstein) Weirdly enough, we *ignore* when the first argument is `inout`
// unconditionally. We probably want to either _always_ require it or never require it.
let ((_, base), (pk_offset, offset), (pk_src, src), args) = if args.len() >= 3 {
(&args[0], &args[1], &args[2], &args[3..])
} else {
return raise_fatal("expects at least 3 arguments");
};
error::ensure_normal_paramkind(pk_offset)?;
error::ensure_normal_paramkind(pk_src)?;
let count_instrs = match (args, kind.vec) {
([c], true) => emit_expr(e, env, error::expect_normal_paramkind(c)?)?,
([], _) => instr::int(-1),
(_, false) => return raise_fatal("expects no more than 3 arguments"),
(_, true) => return raise_fatal("expects no more than 4 arguments"),
};
let (base_expr, cls_expr, base_setup, base_stack, cls_stack) = emit_base(
e,
env,
base,
MOpMode::Define,
false, /* is_object */
BareThisOp::Notice,
false, /*null_coalesce_assignment*/
3, /* base_offset */
3, /* rhs_stack_size */
ReadonlyOp::Any, /* readonly_op */
)?;
Ok(InstrSeq::gather(vec![
base_expr,
cls_expr,
emit_expr(e, env, offset)?,
emit_expr(e, env, src)?,
count_instrs,
base_setup,
instr::instr(Instruct::Opcode(Opcode::SetRangeM(
base_stack + cls_stack,
kind.size.try_into().expect("SetRange size overflow"),
kind.op,
))),
]))
}
pub fn is_reified_tparam<'a, 'arena>(
env: &Env<'a, 'arena>,
is_fun: bool,
name: &str,
) -> Option<(usize, bool)> {
let is = |tparams: &[ast::Tparam]| {
use ast::ReifyKind;
tparams.iter().enumerate().find_map(|(i, tp)| {
if (tp.reified == ReifyKind::Reified || tp.reified == ReifyKind::SoftReified)
&& tp.name.1 == name
{
Some((i, is_soft(&tp.user_attributes)))
} else {
None
}
})
};
if is_fun {
is(env.scope.get_fun_tparams())
} else {
is(env.scope.get_class_tparams())
}
}
/// Emit code for a base expression `expr` that forms part of
/// an element access `expr[elem]` or field access `expr->fld`.
/// The instructions are divided into three sections:
/// 1. base and element/property expression instructions:
/// push non-trivial base and key values on the stack
/// 2. class instructions: emitted when the base is a static property access.
/// A sequence of instructions that pushes the property and the class on the
/// stack to be consumed by a BaseSC. (Foo::$bar)
/// 3. base selector instructions: a sequence of Base/Dim instructions that
/// actually constructs the base address from "member keys" that are inlined
/// in the instructions, or pulled from the key values that
/// were pushed on the stack in section 1.
/// 4. (constructed by the caller) a final accessor e.g. QueryM or setter
/// e.g. SetOpM instruction that has the final key inlined in the
/// instruction, or pulled from the key values that were pushed on the
/// stack in section 1.
///
/// The function returns a 5-tuple:
/// (base_instrs, cls_instrs, base_setup_instrs, base_stack_size, cls_stack_size)
/// where base_instrs is section 1 above, cls_instrs is section 2, base_setup_instrs
/// is section 3, stack_size is the number of values pushed on the stack by
/// section 1, and cls_stack_size is the number of values pushed on the stack by
/// section 2.
///
/// For example, the r-value expression $arr[3][$ix+2]
/// will compile to
/// # Section 1, pushing the value of $ix+2 on the stack
/// Int 2
/// CGetL2 $ix
/// Add
/// # Section 2, constructing the base address of $arr[3]
/// BaseL $arr Warn
/// Dim Warn EI:3
/// # Section 3, indexing the array using the value at stack position 0 (EC:0)
/// QueryM 1 CGet EC:0
///
fn emit_base<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
expr: &ast::Expr,
mode: MOpMode,
is_object: bool,
notice: BareThisOp,
null_coalesce_assignment: bool,
base_offset: StackIndex,
rhs_stack_size: StackIndex,
readonly_enforcement: ReadonlyOp, // this value depends on where we are emitting the base
) -> Result<(
InstrSeq<'arena>,
InstrSeq<'arena>,
InstrSeq<'arena>,
StackIndex,
StackIndex,
)> {
let result = emit_base_(
e,
env,
expr,
mode,
is_object,
notice,
null_coalesce_assignment,
base_offset,
rhs_stack_size,
None,
readonly_enforcement,
)?;
match result {
ArrayGetBase::Regular(i) => Ok((
i.base_instrs,
i.cls_instrs,
i.setup_instrs,
i.base_stack_size,
i.cls_stack_size,
)),
ArrayGetBase::Inout { .. } => Err(Error::unrecoverable("unexpected input")),
}
}
fn is_trivial(env: &Env<'_, '_>, is_base: bool, expr: &ast::Expr) -> bool {
use ast::Expr_;
match &expr.2 {
Expr_::Int(_) | Expr_::String(_) => true,
Expr_::Lvar(x) => {
!is_local_this(env, &x.1) || env.flags.contains(EnvFlags::NEEDS_LOCAL_THIS)
}
Expr_::ArrayGet(_) if !is_base => false,
Expr_::ArrayGet(x) => {
is_trivial(env, is_base, &x.0)
&& (x.1).as_ref().map_or(true, |e| is_trivial(env, is_base, e))
}
_ => false,
}
}
fn get_local_temp_kind<'a, 'arena>(
env: &Env<'a, 'arena>,
is_base: bool,
inout_param_info: Option<(usize, &inout_locals::AliasInfoMap<'_>)>,
expr: Option<&ast::Expr>,
) -> Option<StoredValueKind> {
match (expr, inout_param_info) {
(_, None) => None,
(Some(ast::Expr(_, _, ast::Expr_::Lvar(id))), Some((i, aliases)))
if inout_locals::should_save_local_value(id.name(), i, aliases) =>
{
Some(StoredValueKind::Local)
}
(Some(e), _) => {
if is_trivial(env, is_base, e) {
None
} else {
Some(StoredValueKind::Expr)
}
}
(None, _) => None,
}
}
fn emit_base_<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
expr: &ast::Expr,
mode: MOpMode,
is_object: bool,
notice: BareThisOp,
null_coalesce_assignment: bool,
base_offset: StackIndex,
rhs_stack_size: StackIndex,
inout_param_info: Option<(usize, &inout_locals::AliasInfoMap<'_>)>,
readonly_op: ReadonlyOp,
) -> Result<ArrayGetBase<'arena>> {
let alloc = env.arena;
let pos = &expr.1;
let expr_ = &expr.2;
let base_mode = if mode == MOpMode::InOut {
MOpMode::Warn
} else {
mode
};
let local_temp_kind = get_local_temp_kind(env, true, inout_param_info, Some(expr));
let emit_default = |e: &mut Emitter<'arena, 'decl>,
base_instrs,
cls_instrs,
setup_instrs,
base_stack_size,
cls_stack_size| {
match local_temp_kind {
Some(local_temp) => {
let local = e.local_gen_mut().get_unnamed();
ArrayGetBase::Inout {
load: ArrayGetBaseData {
base_instrs: vec![(base_instrs, Some((local, local_temp)))],
cls_instrs,
setup_instrs,
base_stack_size,
cls_stack_size,
},
store: instr::base_l(local, MOpMode::Define, ReadonlyOp::Any),
}
}
_ => ArrayGetBase::Regular(ArrayGetBaseData {
base_instrs,
cls_instrs,
setup_instrs,
base_stack_size,
cls_stack_size,
}),
}
};
// Called when emitting a base with MOpMode::Define on a Readonly expression
let emit_readonly_lval_base = |
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
inner_expr: &ast::Expr, // expression inside of readonly expression
| -> Option<Result<ArrayGetBase<'_>>> {
// Readonly local variable requires a CheckROCOW
if let aast::Expr(_, _, Expr_::Lvar(x)) = inner_expr {
if !is_local_this(env, &x.1) || env.flags.contains(EnvFlags::NEEDS_LOCAL_THIS) {
match get_local(e, env, &x.0, &(x.1).1) {
Ok(v) => {
let base_instr = if local_temp_kind.is_some() {
instr::c_get_quiet_l(v)
} else {
instr::empty()
};
Some(Ok(emit_default(
e,
base_instr,
instr::empty(),
instr::base_l( v, MOpMode::Define, ReadonlyOp::CheckROCOW),
0,
0,
)))
}
Err(e) => Some(Err(e))
}
} else {
None // Found a local variable case that does not work
}
} else {
// The only other reasonable case is if the inner expression
// is a ClassGet, in which case we can use the default emit_base_ logic to handle
None // Otherwise, ignore readonly
}
};
let emit_expr_default =
|e: &mut Emitter<'arena, 'decl>, env, expr: &ast::Expr| -> Result<ArrayGetBase<'_>> {
let base_expr_instrs = emit_expr(e, env, expr)?;
Ok(emit_default(
e,
base_expr_instrs,
instr::empty(),
emit_pos_then(pos, instr::base_c(base_offset, base_mode)),
1,
0,
))
};
use ast::Expr_;
match expr_ {
// Readonly expression in assignment
Expr_::ReadonlyExpr(r) if base_mode == MOpMode::Define => {
if let Some(result) = emit_readonly_lval_base(e, env, r) {
result
} else {
// If we're not able to emit special readonly expression instructions, emit code as if readonly
// expression does not exist
emit_base_(
e,
env,
r,
mode,
is_object,
notice,
null_coalesce_assignment,
base_offset,
rhs_stack_size,
inout_param_info,
readonly_op,
)
}
}
Expr_::Lvar(x) if superglobals::is_superglobal(&(x.1).1) => {
let base_instrs = emit_pos_then(
&x.0,
instr::string(alloc, string_utils::locals::strip_dollar(&(x.1).1)),
);
Ok(emit_default(
e,
base_instrs,
instr::empty(),
instr::base_gc(base_offset, base_mode),
1,
0,
))
}
Expr_::Lvar(x) if is_object && (x.1).1 == special_idents::THIS => {
let base_instrs = emit_pos_then(&x.0, instr::check_this());
Ok(emit_default(
e,
base_instrs,
instr::empty(),
instr::base_h(),
0,
0,
))
}
Expr_::Lvar(x)
if !is_local_this(env, &x.1) || env.flags.contains(EnvFlags::NEEDS_LOCAL_THIS) =>
{
let v = get_local(e, env, &x.0, &(x.1).1)?;
let base_instr = if local_temp_kind.is_some() {
instr::c_get_quiet_l(v)
} else {
instr::empty()
};
Ok(emit_default(
e,
base_instr,
instr::empty(),
instr::base_l(v, base_mode, ReadonlyOp::Any),
0,
0,
))
}
Expr_::Lvar(lid) => {
let local = emit_local(e, env, notice, lid)?;
Ok(emit_default(
e,
local,
instr::empty(),
instr::base_c(base_offset, base_mode),
1,
0,
))
}
Expr_::ArrayGet(x) => match (&(x.0).1, x.1.as_ref()) {
// $a[] can not be used as the base of an array get unless as an lval
(_, None) if !env.flags.contains(env::Flags::ALLOWS_ARRAY_APPEND) => {
Err(Error::fatal_runtime(pos, "Can't use [] for reading"))
}
// base is in turn array_get - do a specific handling for inout params
// if necessary
(_, opt_elem_expr) => {
let base_expr = &x.0;
let local_temp_kind =
get_local_temp_kind(env, false, inout_param_info, opt_elem_expr);
let (elem_instrs, elem_stack_size) = emit_elem(
e,
env,
opt_elem_expr,
local_temp_kind,
null_coalesce_assignment,
)?;
let base_result = emit_base_(
e,
env,
base_expr,
mode,
false,
notice,
null_coalesce_assignment,
base_offset + elem_stack_size,
rhs_stack_size,
inout_param_info,
readonly_op, // continue passing readonly enforcement up
)?;
let cls_stack_size = match &base_result {
ArrayGetBase::Regular(base) => base.cls_stack_size,
ArrayGetBase::Inout { load, .. } => load.cls_stack_size,
};
let (mk, warninstr) = get_elem_member_key(
e,
env,
base_offset + cls_stack_size,
opt_elem_expr,
null_coalesce_assignment,
)?;
let make_setup_instrs = |base_setup_instrs: InstrSeq<'arena>| {
InstrSeq::gather(vec![warninstr, base_setup_instrs, instr::dim(mode, mk)])
};
Ok(match (base_result, local_temp_kind) {
// both base and index don't use temps - fallback to default handler
(ArrayGetBase::Regular(base), None) => emit_default(
e,
InstrSeq::gather(vec![base.base_instrs, elem_instrs]),
base.cls_instrs,
make_setup_instrs(base.setup_instrs),
base.base_stack_size + elem_stack_size,
base.cls_stack_size,
),
// base does not need temps but index does
(ArrayGetBase::Regular(base), Some(local_temp)) => {
let local = e.local_gen_mut().get_unnamed();
let base_instrs = InstrSeq::gather(vec![base.base_instrs, elem_instrs]);
ArrayGetBase::Inout {
load: ArrayGetBaseData {
// store result of instr_begin to temp
base_instrs: vec![(base_instrs, Some((local, local_temp)))],
cls_instrs: base.cls_instrs,
setup_instrs: make_setup_instrs(base.setup_instrs),
base_stack_size: base.base_stack_size + elem_stack_size,
cls_stack_size: base.cls_stack_size,
},
store: emit_store_for_simple_base(
e,
env,
pos,
elem_stack_size,
base_expr,
local,
true,
readonly_op,
)?,
}
}
// base needs temps, index - does not
(
ArrayGetBase::Inout {
load:
ArrayGetBaseData {
mut base_instrs,
cls_instrs,
setup_instrs,
base_stack_size,
cls_stack_size,
},
store,
},
None,
) => {
base_instrs.push((elem_instrs, None));
ArrayGetBase::Inout {
load: ArrayGetBaseData {
base_instrs,
cls_instrs,
setup_instrs: make_setup_instrs(setup_instrs),
base_stack_size: base_stack_size + elem_stack_size,
cls_stack_size,
},
store: InstrSeq::gather(vec![store, instr::dim(MOpMode::Define, mk)]),
}
}
// both base and index needs locals
(
ArrayGetBase::Inout {
load:
ArrayGetBaseData {
mut base_instrs,
cls_instrs,
setup_instrs,
base_stack_size,
cls_stack_size,
},
store,
},
Some(local_kind),
) => {
let local = e.local_gen_mut().get_unnamed();
base_instrs.push((elem_instrs, Some((local, local_kind))));
ArrayGetBase::Inout {
load: ArrayGetBaseData {
base_instrs,
cls_instrs,
setup_instrs: make_setup_instrs(setup_instrs),
base_stack_size: base_stack_size + elem_stack_size,
cls_stack_size,
},
store: InstrSeq::gather(vec![
store,
instr::dim(MOpMode::Define, MemberKey::EL(local, ReadonlyOp::Any)),
]),
}
}
})
}
},
Expr_::ObjGet(x) if x.as_ref().3 == ast::PropOrMethod::IsProp => {
let (base_expr, prop_expr, null_flavor, _) = &**x;
Ok(match prop_expr.2.as_id() {
Some(ast_defs::Id(_, s)) if string_utils::is_xhp(s) => {
let base_instrs = emit_xhp_obj_get(e, env, pos, base_expr, s, null_flavor)?;
emit_default(
e,
base_instrs,
instr::empty(),
instr::base_c(base_offset, base_mode),
1,
0,
)
}
_ => {
let prop_stack_size = emit_prop_expr(
e,
env,
null_flavor,
0,
prop_expr,
null_coalesce_assignment,
ReadonlyOp::Any, // just getting stack size here
)?
.2;
let (
base_expr_instrs_begin,
base_expr_instrs_end,
base_setup_instrs,
base_stack_size,
cls_stack_size,
) = emit_base(
e,
env,
base_expr,
mode,
true,
BareThisOp::Notice,
null_coalesce_assignment,
base_offset + prop_stack_size,
rhs_stack_size,
ReadonlyOp::Mutable, // the rest of the base must be completely mutable
)?;
let (mk, prop_instrs, _) = emit_prop_expr(
e,
env,
null_flavor,
base_offset + cls_stack_size,
prop_expr,
null_coalesce_assignment,
readonly_op, // use the current enforcement
)?;
let total_stack_size = prop_stack_size + base_stack_size;
let final_instr = instr::dim(mode, mk);
emit_default(
e,
InstrSeq::gather(vec![base_expr_instrs_begin, prop_instrs]),
base_expr_instrs_end,
InstrSeq::gather(vec![base_setup_instrs, final_instr]),
total_stack_size,
cls_stack_size,
)
}
})
}
Expr_::ClassGet(x) => {
let (cid, prop, _) = &**x;
let cexpr = ClassExpr::class_id_to_class_expr(e, false, false, &env.scope, cid);
let (cexpr_begin, cexpr_end) = emit_class_expr(e, env, cexpr, prop)?;
Ok(emit_default(
e,
cexpr_begin,
cexpr_end,
instr::base_sc(base_offset + 1, rhs_stack_size, base_mode, readonly_op),
1,
1,
))
}
_ => emit_expr_default(e, env, expr),
}
}
pub fn emit_ignored_exprs<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
exprs: &[ast::Expr],
) -> Result<InstrSeq<'arena>> {
exprs
.iter()
.map(|e| emit_ignored_expr(emitter, env, pos, e))
.collect::<Result<Vec<_>>>()
.map(InstrSeq::gather)
}
pub fn emit_ignored_expr<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
expr: &ast::Expr,
) -> Result<InstrSeq<'arena>> {
Ok(InstrSeq::gather(vec![
emit_expr(emitter, env, expr)?,
emit_pos_then(pos, instr::pop_c()),
]))
}
fn emit_lval_op<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
op: LValOp,
expr1: &ast::Expr,
expr2: Option<&ast::Expr>,
null_coalesce_assignment: bool,
) -> Result<InstrSeq<'arena>> {
match (op, &expr1.2, expr2) {
(LValOp::Set, ast::Expr_::List(l), Some(expr2)) => {
let instr_rhs = emit_expr(e, env, expr2)?;
let has_elements = l.iter().any(|e| !e.2.is_omitted());
if !has_elements {
Ok(instr_rhs)
} else {
scope::with_unnamed_local(e, |e, local| {
let loc = if can_use_as_rhs_in_list_assignment(&expr2.2)? {
Some(&local)
} else {
None
};
let (instr_lhs, instr_assign) = emit_lval_op_list(
e,
env,
pos,
loc,
&[],
expr1,
false,
is_readonly_expr(expr2),
)?;
Ok((
InstrSeq::gather(vec![instr_lhs, instr_rhs, instr::pop_l(local)]),
instr_assign,
instr::push_l(local),
))
})
}
}
_ => e.local_scope(|e| {
let (rhs_instrs, rhs_stack_size, rhs_readonly) = match expr2 {
None => (instr::empty(), 0, false),
Some(aast::Expr(_, _, aast::Expr_::Yield(af))) => {
let temp = e.local_gen_mut().get_unnamed();
(
InstrSeq::gather(vec![
emit_yield(e, env, pos, af)?,
instr::set_l(temp),
instr::pop_c(),
instr::push_l(temp),
]),
1,
false,
)
}
Some(expr) => (emit_expr(e, env, expr)?, 1, is_readonly_expr(expr)),
};
emit_lval_op_nonlist(
e,
env,
pos,
op,
expr1,
rhs_instrs,
rhs_stack_size,
rhs_readonly,
null_coalesce_assignment,
)
}),
}
}
fn can_use_as_rhs_in_list_assignment(expr: &ast::Expr_) -> Result<bool> {
use aast::Expr_;
Ok(match expr {
Expr_::Call(box aast::CallExpr {
func: ast::Expr(_, _, Expr_::Id(id)),
..
}) if id.1 == special_functions::ECHO => false,
Expr_::ObjGet(o) if o.as_ref().3 == ast::PropOrMethod::IsProp => true,
Expr_::ClassGet(c) if c.as_ref().2 == ast::PropOrMethod::IsProp => true,
Expr_::Lvar(_)
| Expr_::ArrayGet(_)
| Expr_::Call(_)
| Expr_::FunctionPointer(_)
| Expr_::New(_)
| Expr_::Yield(_)
| Expr_::Cast(_)
| Expr_::Eif(_)
| Expr_::Tuple(_)
| Expr_::Varray(_)
| Expr_::Darray(_)
| Expr_::Collection(_)
| Expr_::KeyValCollection(_)
| Expr_::ValCollection(_)
| Expr_::Clone(_)
| Expr_::Unop(_)
| Expr_::As(_)
| Expr_::Upcast(_)
| Expr_::Await(_)
| Expr_::ReadonlyExpr(_)
| Expr_::ClassConst(_) => true,
Expr_::Pipe(p) => can_use_as_rhs_in_list_assignment(&(p.2).2)?,
Expr_::Binop(b) => {
if let ast_defs::Bop::Eq(None) = &b.bop {
if (b.lhs).2.is_list() {
return can_use_as_rhs_in_list_assignment(&(b.rhs).2);
}
}
b.bop.is_plus() || b.bop.is_question_question() || b.bop.is_any_eq()
}
_ => false,
})
}
// Given a local $local and a list of integer array indices i_1, ..., i_n,
// generate code to extract the value of $local[i_n]...[i_1]:
// BaseL $local Warn
// Dim Warn EI:i_n ...
// Dim Warn EI:i_2
// QueryM 0 CGet EI:i_1
fn emit_array_get_fixed<'arena>(
last_usage: bool,
local: Local,
indices: &[isize],
) -> InstrSeq<'arena> {
let (base, stack_count) = if last_usage {
(
InstrSeq::gather(vec![instr::push_l(local), instr::base_c(0, MOpMode::Warn)]),
1,
)
} else {
(instr::base_l(local, MOpMode::Warn, ReadonlyOp::Any), 0)
};
let indices = InstrSeq::gather(
indices
.iter()
.enumerate()
.rev()
.map(|(i, ix)| {
let mk = MemberKey::EI(*ix as i64, ReadonlyOp::Any);
if i == 0 {
instr::query_m(stack_count, QueryMOp::CGet, mk)
} else {
instr::dim(MOpMode::Warn, mk)
}
})
.collect(),
);
InstrSeq::gather(vec![base, indices])
}
/// Generate code for each lvalue assignment in a list destructuring expression.
/// Lvalues are assigned right-to-left, regardless of the nesting structure. So
/// list($a, list($b, $c)) = $d
/// and list(list($a, $b), $c) = $d
/// will both assign to $c, $b and $a in that order.
/// Returns a pair of instructions:
/// 1. initialization part of the left hand side
/// 2. assignment
/// this is necessary to handle cases like:
/// list($a[$f()]) = b();
/// here f() should be invoked before b()
pub fn emit_lval_op_list<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
outer_pos: &Pos,
local: Option<&Local>,
indices: &[isize],
expr: &ast::Expr,
last_usage: bool,
rhs_readonly: bool,
) -> Result<(InstrSeq<'arena>, InstrSeq<'arena>)> {
use ast::Expr_;
let is_ltr = e.options().hhbc.ltr_assign;
match &expr.2 {
Expr_::List(exprs) => {
let last_non_omitted = if last_usage {
// last usage of the local will happen when processing last non-omitted
// element in the list - find it
if is_ltr {
exprs.iter().rposition(|v| !v.2.is_omitted())
} else {
// in right-to-left case result list will be reversed
// so we need to find first non-omitted expression
exprs.iter().rev().rposition(|v| !v.2.is_omitted())
}
} else {
None
};
let (lhs_instrs, set_instrs): (Vec<InstrSeq<'arena>>, Vec<InstrSeq<'arena>>) = exprs
.iter()
.enumerate()
.map(|(i, expr)| {
let mut new_indices = vec![i as isize];
new_indices.extend_from_slice(indices);
emit_lval_op_list(
e,
env,
outer_pos,
local,
&new_indices[..],
expr,
last_non_omitted.map_or(false, |j| j == i),
rhs_readonly,
)
})
.collect::<Result<Vec<_>>>()?
.into_iter()
.unzip();
Ok((
InstrSeq::gather(lhs_instrs),
InstrSeq::gather(if !is_ltr {
set_instrs.into_iter().rev().collect()
} else {
set_instrs
}),
))
}
Expr_::Omitted => Ok((instr::empty(), instr::empty())),
_ => {
// Generate code to access the element from the array
let access_instrs = match (local, indices) {
(Some(loc), [_, ..]) => emit_array_get_fixed(last_usage, loc.to_owned(), indices),
(Some(loc), []) => {
if last_usage {
instr::push_l(loc.to_owned())
} else {
instr::c_get_l(loc.to_owned())
}
}
(None, _) => instr::null(),
};
// Generate code to assign to the lvalue *)
// Return pair: side effects to initialize lhs + assignment
let (lhs_instrs, rhs_instrs, set_op) = emit_lval_op_nonlist_steps(
e,
env,
outer_pos,
LValOp::Set,
expr,
access_instrs,
1,
rhs_readonly,
false,
)?;
Ok(if is_ltr {
(
instr::empty(),
InstrSeq::gather(vec![lhs_instrs, rhs_instrs, set_op, instr::pop_c()]),
)
} else {
(
lhs_instrs,
InstrSeq::gather(vec![instr::empty(), rhs_instrs, set_op, instr::pop_c()]),
)
})
}
}
}
pub fn emit_lval_op_nonlist<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
outer_pos: &Pos,
op: LValOp,
expr: &ast::Expr,
rhs_instrs: InstrSeq<'arena>,
rhs_stack_size: u32,
rhs_readonly: bool,
null_coalesce_assignment: bool,
) -> Result<InstrSeq<'arena>> {
emit_lval_op_nonlist_steps(
e,
env,
outer_pos,
op,
expr,
rhs_instrs,
rhs_stack_size,
rhs_readonly,
null_coalesce_assignment,
)
.map(|(lhs, rhs, setop)| InstrSeq::gather(vec![lhs, rhs, setop]))
}
pub fn emit_final_global_op<'arena>(pos: &Pos, op: LValOp) -> InstrSeq<'arena> {
use LValOp as L;
match op {
L::Set => emit_pos_then(pos, instr::set_g()),
L::SetOp(op) => instr::set_op_g(op),
L::IncDec(op) => instr::inc_dec_g(op),
L::Unset => emit_pos_then(pos, instr::unset_g()),
}
}
pub fn emit_final_local_op<'arena>(pos: &Pos, op: LValOp, lid: Local) -> InstrSeq<'arena> {
use LValOp as L;
emit_pos_then(
pos,
match op {
L::Set => instr::set_l(lid),
L::SetOp(op) => instr::set_op_l(lid, op),
L::IncDec(op) => instr::inc_dec_l(lid, op),
L::Unset => instr::unset_l(lid),
},
)
}
fn emit_final_member_op<'arena>(
stack_size: StackIndex,
op: LValOp,
mk: MemberKey<'arena>,
) -> InstrSeq<'arena> {
use LValOp as L;
match op {
L::Set => instr::set_m(stack_size, mk),
L::SetOp(op) => instr::set_op_m(stack_size, op, mk),
L::IncDec(op) => instr::inc_dec_m(stack_size, op, mk),
L::Unset => instr::unset_m(stack_size, mk),
}
}
fn emit_final_static_op<'arena>(
alloc: &'arena bumpalo::Bump,
cid: &ast::ClassId,
prop: &ast::ClassGetExpr,
op: LValOp,
) -> Result<InstrSeq<'arena>> {
use LValOp as L;
Ok(match op {
L::Set => instr::set_s(ReadonlyOp::Any),
L::SetOp(op) => instr::set_op_s(op),
L::IncDec(op) => instr::inc_dec_s(op),
L::Unset => {
let pos = match prop {
ast::ClassGetExpr::CGstring((pos, _))
| ast::ClassGetExpr::CGexpr(ast::Expr(_, pos, _)) => pos,
};
let cid = text_of_class_id(cid);
let id = text_of_prop(prop);
emit_fatal::emit_fatal_runtime(
alloc,
pos,
format!(
"Attempt to unset static property {}::{}",
string_utils::strip_ns(&cid),
id,
),
)
}
})
}
pub fn emit_lval_op_nonlist_steps<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
outer_pos: &Pos,
op: LValOp,
expr: &ast::Expr,
rhs_instrs: InstrSeq<'arena>,
rhs_stack_size: StackIndex,
rhs_readonly: bool,
null_coalesce_assignment: bool,
) -> Result<(InstrSeq<'arena>, InstrSeq<'arena>, InstrSeq<'arena>)> {
let f = |alloc: &'arena bumpalo::Bump, env: &mut Env<'a, 'arena>| {
use ast::Expr_;
let pos = &expr.1;
Ok(match &expr.2 {
Expr_::Lvar(v) if superglobals::is_any_global(local_id::get_name(&v.1)) => (
emit_pos_then(
&v.0,
instr::string(alloc, string_utils::lstrip(local_id::get_name(&v.1), "$")),
),
rhs_instrs,
emit_final_global_op(outer_pos, op),
),
Expr_::Lvar(v) if is_local_this(env, &v.1) && op.is_incdec() => (
emit_local(e, env, BareThisOp::Notice, v)?,
rhs_instrs,
instr::empty(),
),
Expr_::Lvar(v) if !is_local_this(env, &v.1) || op == LValOp::Unset => {
(instr::empty(), rhs_instrs, {
let lid = get_local(e, env, &v.0, &(v.1).1)?;
emit_final_local_op(outer_pos, op, lid)
})
}
Expr_::ArrayGet(x) => match (&(x.0).1, x.1.as_ref()) {
(_, None) if !env.flags.contains(env::Flags::ALLOWS_ARRAY_APPEND) => {
return Err(Error::fatal_runtime(pos, "Can't use [] for reading"));
}
(_, opt_elem_expr) => {
let mode = match op {
LValOp::Unset => MOpMode::Unset,
_ => MOpMode::Define,
};
let (elem_instrs, elem_stack_size) =
emit_elem(e, env, opt_elem_expr, None, null_coalesce_assignment)?;
let base_offset = elem_stack_size + rhs_stack_size;
let readonly_op = if rhs_readonly {
ReadonlyOp::CheckROCOW // writing a readonly value requires a readonly copy on write array
} else {
ReadonlyOp::CheckMutROCOW // writing a mut value requires left side to be mutable or a ROCOW
};
let (
base_expr_instrs_begin,
base_expr_instrs_end,
base_setup_instrs,
base_stack_size,
cls_stack_size,
) = emit_base(
e,
env,
&x.0,
mode,
false,
BareThisOp::Notice,
null_coalesce_assignment,
base_offset,
rhs_stack_size,
readonly_op,
)?;
let (mk, warninstr) = get_elem_member_key(
e,
env,
rhs_stack_size + cls_stack_size,
opt_elem_expr,
null_coalesce_assignment,
)?;
let total_stack_size = elem_stack_size + base_stack_size + cls_stack_size;
let final_instr =
emit_pos_then(pos, emit_final_member_op(total_stack_size, op, mk));
(
// Don't emit instructions for elems as these were not popped from
// the stack by the final member op during the lookup of a null
// coalesce assignment.
if null_coalesce_assignment {
instr::empty()
} else {
InstrSeq::gather(vec![
base_expr_instrs_begin,
elem_instrs,
base_expr_instrs_end,
])
},
rhs_instrs,
InstrSeq::gather(vec![
emit_pos(pos),
warninstr,
base_setup_instrs,
final_instr,
]),
)
}
},
Expr_::ObjGet(x) if x.as_ref().3 == ast::PropOrMethod::IsProp => {
let (e1, e2, nullflavor, _) = &**x;
if nullflavor.eq(&ast_defs::OgNullFlavor::OGNullsafe) {
return Err(Error::fatal_parse(
pos,
"?-> is not allowed in write context",
));
}
let mode = match op {
LValOp::Unset => MOpMode::Unset,
_ => MOpMode::Define,
};
let readonly_op = if rhs_readonly {
ReadonlyOp::Readonly
} else {
ReadonlyOp::Any
};
let prop_stack_size = emit_prop_expr(
e,
env,
nullflavor,
0,
e2,
null_coalesce_assignment,
readonly_op,
)?
.2;
let base_offset = prop_stack_size + rhs_stack_size;
let (
base_expr_instrs_begin,
base_expr_instrs_end,
base_setup_instrs,
base_stack_size,
cls_stack_size,
) = emit_base(
e,
env,
e1,
mode,
true,
BareThisOp::Notice,
null_coalesce_assignment,
base_offset,
rhs_stack_size,
ReadonlyOp::Mutable, // writing to a property requires everything in the base to be mutable
)?;
let (mk, prop_instrs, _) = emit_prop_expr(
e,
env,
nullflavor,
rhs_stack_size + cls_stack_size,
e2,
null_coalesce_assignment,
readonly_op,
)?;
let total_stack_size = prop_stack_size + base_stack_size + cls_stack_size;
let final_instr =
emit_pos_then(pos, emit_final_member_op(total_stack_size, op, mk));
(
// Don't emit instructions for props as these were not popped from
// the stack by the final member op during the lookup of a null
// coalesce assignment.
if null_coalesce_assignment {
instr::empty()
} else {
InstrSeq::gather(vec![
base_expr_instrs_begin,
prop_instrs,
base_expr_instrs_end,
])
},
rhs_instrs,
InstrSeq::gather(vec![base_setup_instrs, final_instr]),
)
}
Expr_::ClassGet(x) if x.as_ref().2 == ast::PropOrMethod::IsProp => {
let (cid, prop, _) = &**x;
let cexpr = ClassExpr::class_id_to_class_expr(e, false, false, &env.scope, cid);
let final_instr_ = emit_final_static_op(alloc, cid, prop, op)?;
let final_instr = emit_pos_then(pos, final_instr_);
let (cexpr_seq1, cexpr_seq2) = emit_class_expr(e, env, cexpr, prop)?;
(
InstrSeq::gather(vec![cexpr_seq1, cexpr_seq2]),
rhs_instrs,
final_instr,
)
}
Expr_::Unop(uop) => (
instr::empty(),
rhs_instrs,
InstrSeq::gather(vec![
emit_lval_op_nonlist(
e,
env,
pos,
op,
&uop.1,
instr::empty(),
rhs_stack_size,
false,
false, // all unary operations (++, --, etc) are on primitives, so no HHVM readonly checks
)?,
from_unop(&uop.0)?,
]),
),
_ => {
return Err(Error::fatal_parse(
pos,
"Can't use return value in write context",
));
}
})
};
// TODO(shiqicao): remove clone!
let alloc = env.arena;
let mut env = env.clone();
match op {
LValOp::Set | LValOp::SetOp(_) | LValOp::IncDec(_) => {
env.with_allows_array_append(alloc, f)
}
_ => f(alloc, &mut env),
}
}
fn emit_class_expr<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
cexpr: ClassExpr<'arena>,
prop: &ast::ClassGetExpr,
) -> Result<(InstrSeq<'arena>, InstrSeq<'arena>)> {
let load_prop = |e: &mut Emitter<'arena, 'decl>| match prop {
ast::ClassGetExpr::CGstring((pos, id)) => Ok(emit_pos_then(
pos,
instr::string(e.alloc, string_utils::locals::strip_dollar(id)),
)),
ast::ClassGetExpr::CGexpr(expr) => emit_expr(e, env, expr),
};
Ok(match &cexpr {
ClassExpr::Expr(expr)
if expr.2.is_call()
|| expr.2.is_binop()
|| expr.2.is_class_get()
|| expr
.2
.as_lvar()
.map_or(false, |ast::Lid(_, id)| local_id::get_name(id) == "$this") =>
{
let cexpr_local = emit_expr(e, env, expr)?;
(
instr::empty(),
InstrSeq::gather(vec![
cexpr_local,
scope::stash_top_in_unnamed_local(e, load_prop)?,
instr::class_get_c(),
]),
)
}
_ => {
let pos = match prop {
ast::ClassGetExpr::CGstring((pos, _))
| ast::ClassGetExpr::CGexpr(ast::Expr(_, pos, _)) => pos,
};
(load_prop(e)?, emit_load_class_ref(e, env, pos, cexpr)?)
}
})
}
fn fixup_type_arg<'a, 'b, 'arena>(
env: &Env<'b, 'arena>,
isas: bool,
hint: &'a ast::Hint,
) -> Result<Cow<'a, ast::Hint>> {
struct Checker<'s> {
erased_tparams: &'s [&'s str],
isas: bool,
}
impl<'ast, 's> Visitor<'ast> for Checker<'s> {
type Params = AstParams<(), Option<Error>>;
fn object(&mut self) -> &mut dyn Visitor<'ast, Params = Self::Params> {
self
}
fn visit_hint_fun(&mut self, c: &mut (), hf: &ast::HintFun) -> Result<(), Option<Error>> {
hf.param_tys.accept(c, self.object())?;
hf.return_ty.accept(c, self.object())
}
fn visit_hint(&mut self, c: &mut (), h: &ast::Hint) -> Result<(), Option<Error>> {
use ast::Hint_ as H_;
use ast::Id;
match h.1.as_ref() {
H_::Happly(Id(_, id), _)
if self.erased_tparams.contains(&id.as_str()) && self.isas =>
{
return Err(Some(Error::fatal_parse(
&h.0,
"Erased generics are not allowed in is/as expressions",
)));
}
H_::Haccess(_, _) => return Ok(()),
_ => {}
}
h.recurse(c, self.object())
}
fn visit_hint_(&mut self, c: &mut (), h: &ast::Hint_) -> Result<(), Option<Error>> {
use ast::Hint_ as H_;
use ast::Id;
match h {
H_::Happly(Id(_, id), _) if self.erased_tparams.contains(&id.as_str()) => Err(None),
_ => h.recurse(c, self.object()),
}
}
}
struct Updater<'s> {
erased_tparams: &'s [&'s str],
}
impl<'ast, 's> VisitorMut<'ast> for Updater<'s> {
type Params = AstParams<(), ()>;
fn object(&mut self) -> &mut dyn VisitorMut<'ast, Params = Self::Params> {
self
}
fn visit_hint_fun(&mut self, c: &mut (), hf: &mut ast::HintFun) -> Result<(), ()> {
<Vec<ast::Hint> as NodeMut<Self::Params>>::accept(&mut hf.param_tys, c, self.object())?;
<ast::Hint as NodeMut<Self::Params>>::accept(&mut hf.return_ty, c, self.object())
}
fn visit_hint_(&mut self, c: &mut (), h: &mut ast::Hint_) -> Result<(), ()> {
use ast::Hint_ as H_;
use ast::Id;
match h {
H_::Happly(Id(_, id), _) if self.erased_tparams.contains(&id.as_str()) => {
Ok(*h = H_::Hwildcard)
}
_ => h.recurse(c, self.object()),
}
}
}
let erased_tparams = get_erased_tparams(env);
let erased_tparams = erased_tparams.as_slice();
let mut checker = Checker {
erased_tparams,
isas,
};
match visit(&mut checker, &mut (), hint) {
Ok(()) => Ok(Cow::Borrowed(hint)),
Err(Some(error)) => Err(error),
Err(None) => {
let mut updater = Updater { erased_tparams };
let mut hint = hint.clone();
visit_mut(&mut updater, &mut (), &mut hint).unwrap();
Ok(Cow::Owned(hint))
}
}
}
pub fn emit_reified_arg<'b, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'b, 'arena>,
pos: &Pos,
isas: bool,
hint: &ast::Hint,
) -> Result<(InstrSeq<'arena>, bool)> {
struct Collector<'ast, 'a> {
current_tags: &'a HashSet<&'a str>,
acc: IndexSet<&'ast str>,
}
impl<'ast, 'a> Collector<'ast, 'a> {
fn add_name(&mut self, name: &'ast str) {
if self.current_tags.contains(name) && !self.acc.contains(name) {
self.acc.insert(name);
}
}
}
impl<'ast, 'a> Visitor<'ast> for Collector<'ast, 'a> {
type Params = AstParams<(), ()>;
fn object(&mut self) -> &mut dyn Visitor<'ast, Params = Self::Params> {
self
}
fn visit_hint_(&mut self, c: &mut (), h_: &'ast ast::Hint_) -> Result<(), ()> {
use ast::Hint_ as H_;
use ast::Id;
match h_ {
H_::Haccess(_, sids) => Ok(sids.iter().for_each(|Id(_, name)| self.add_name(name))),
H_::Habstr(name, h) | H_::Happly(Id(_, name), h) => {
self.add_name(name);
h.accept(c, self.object())
}
_ => h_.recurse(c, self.object()),
}
}
}
let hint = fixup_type_arg(env, isas, hint)?;
fn f<'a>(mut acc: HashSet<&'a str>, tparam: &'a ast::Tparam) -> HashSet<&'a str> {
if tparam.reified != ast::ReifyKind::Erased {
acc.insert(&tparam.name.1);
}
acc
}
let current_tags = env
.scope
.get_fun_tparams()
.iter()
.fold(HashSet::<&str>::default(), f);
let class_tparams = env.scope.get_class_tparams();
let current_tags = class_tparams.iter().fold(current_tags, f);
let mut collector = Collector {
current_tags: ¤t_tags,
acc: IndexSet::new(),
};
visit(&mut collector, &mut (), &hint as &ast::Hint).unwrap();
match hint.1.as_ref() {
ast::Hint_::Happly(ast::Id(_, name), hs)
if hs.is_empty() && current_tags.contains(name.as_str()) =>
{
Ok((emit_reified_type(e, env, pos, name)?, false))
}
_ => {
let type_refinement_in_hint = if isas {
TypeRefinementInHint::Disallowed
} else {
TypeRefinementInHint::Allowed
};
let ts = get_type_structure_for_hint(
e,
&[],
&collector.acc,
type_refinement_in_hint,
&hint,
)?;
let ts_list = if collector.acc.is_empty() {
ts
} else {
let values = collector
.acc
.iter()
.map(|v| emit_reified_type(e, env, pos, v))
.collect::<Result<Vec<_>>>()?;
InstrSeq::gather(vec![InstrSeq::gather(values), ts])
};
Ok((
InstrSeq::gather(vec![
ts_list,
instr::combine_and_resolve_type_struct(collector.acc.len() as u32 + 1),
]),
collector.acc.is_empty(),
))
}
}
}
pub fn get_local<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
s: &str,
) -> Result<Local> {
if s == special_idents::DOLLAR_DOLLAR {
match &env.pipe_var {
None => Err(Error::fatal_runtime(
pos,
"Pipe variables must occur only in the RHS of pipe expressions",
)),
Some(var) => Ok(*var),
}
} else if special_idents::is_tmp_var(s) {
Ok(*e.local_gen().get_unnamed_for_tempname(s))
} else {
Ok(e.named_local(s.into()))
}
}
pub fn emit_is_null<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
expr: &ast::Expr,
) -> Result<InstrSeq<'arena>> {
if let Some(ast::Lid(pos, id)) = expr.2.as_lvar() {
if !is_local_this(env, id) {
return Ok(instr::is_type_l(
get_local(e, env, pos, local_id::get_name(id))?,
IsTypeOp::Null,
));
}
}
Ok(InstrSeq::gather(vec![
emit_expr(e, env, expr)?,
instr::is_type_c(IsTypeOp::Null),
]))
}
pub fn emit_jmpnz<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
expr: &ast::Expr,
label: Label,
) -> Result<EmitJmpResult<'arena>> {
let ast::Expr(_, pos, expr_) = expr;
let opt = optimize_null_checks(e);
Ok(match constant_folder::expr_to_typed_value(e, expr) {
Ok(tv) => {
if constant_folder::cast_to_bool(tv) {
EmitJmpResult {
instrs: emit_pos_then(pos, instr::jmp(label)),
is_fallthrough: false,
is_label_used: true,
}
} else {
EmitJmpResult {
instrs: emit_pos_then(pos, instr::empty()),
is_fallthrough: true,
is_label_used: false,
}
}
}
Err(_) => {
use ast::Expr_;
use ast_defs::Uop;
match expr_ {
Expr_::Unop(uo) if uo.0 == Uop::Unot => emit_jmpz(e, env, &uo.1, label)?,
Expr_::Binop(bo) if bo.bop.is_barbar() => {
let r1 = emit_jmpnz(e, env, &bo.lhs, label)?;
if r1.is_fallthrough {
let r2 = emit_jmpnz(e, env, &bo.rhs, label)?;
EmitJmpResult {
instrs: emit_pos_then(
pos,
InstrSeq::gather(vec![r1.instrs, r2.instrs]),
),
is_fallthrough: r2.is_fallthrough,
is_label_used: r1.is_label_used || r2.is_label_used,
}
} else {
r1
}
}
Expr_::Binop(bo) if bo.bop.is_ampamp() => {
let skip_label = e.label_gen_mut().next_regular();
let r1 = emit_jmpz(e, env, &bo.lhs, skip_label)?;
if !r1.is_fallthrough {
EmitJmpResult {
instrs: emit_pos_then(
pos,
InstrSeq::gather(if r1.is_label_used {
vec![r1.instrs, instr::label(skip_label)]
} else {
vec![r1.instrs]
}),
),
is_fallthrough: r1.is_label_used,
is_label_used: false,
}
} else {
let r2 = emit_jmpnz(e, env, &bo.rhs, label)?;
EmitJmpResult {
instrs: emit_pos_then(
pos,
InstrSeq::gather(if r1.is_label_used {
vec![r1.instrs, r2.instrs, instr::label(skip_label)]
} else {
vec![r1.instrs, r2.instrs]
}),
),
is_fallthrough: r2.is_fallthrough || r1.is_label_used,
is_label_used: r2.is_label_used,
}
}
}
Expr_::Binop(bo)
if bo.bop.is_eqeqeq()
&& ((bo.lhs).2.is_null() || (bo.rhs).2.is_null())
&& opt =>
{
let is_null = emit_is_null(
e,
env,
if (bo.lhs).2.is_null() {
&bo.rhs
} else {
&bo.lhs
},
)?;
EmitJmpResult {
instrs: emit_pos_then(
pos,
InstrSeq::gather(vec![is_null, instr::jmp_nz(label)]),
),
is_fallthrough: true,
is_label_used: true,
}
}
Expr_::Binop(bo)
if bo.bop.is_diff2()
&& ((bo.lhs).2.is_null() || (bo.rhs).2.is_null())
&& opt =>
{
let is_null = emit_is_null(
e,
env,
if (bo.lhs).2.is_null() {
&bo.rhs
} else {
&bo.lhs
},
)?;
EmitJmpResult {
instrs: emit_pos_then(
pos,
InstrSeq::gather(vec![is_null, instr::jmp_z(label)]),
),
is_fallthrough: true,
is_label_used: true,
}
}
_ => {
let instr = emit_expr(e, env, expr)?;
EmitJmpResult {
instrs: emit_pos_then(
pos,
InstrSeq::gather(vec![instr, instr::jmp_nz(label)]),
),
is_fallthrough: true,
is_label_used: true,
}
}
}
}
})
}
pub fn emit_jmpz<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
expr: &ast::Expr,
label: Label,
) -> Result<EmitJmpResult<'arena>> {
let ast::Expr(_, pos, expr_) = expr;
let opt = optimize_null_checks(e);
Ok(match constant_folder::expr_to_typed_value(e, expr) {
Ok(v) => {
if constant_folder::cast_to_bool(v) {
EmitJmpResult {
instrs: emit_pos_then(pos, instr::empty()),
is_fallthrough: true,
is_label_used: false,
}
} else {
EmitJmpResult {
instrs: emit_pos_then(pos, instr::jmp(label)),
is_fallthrough: false,
is_label_used: true,
}
}
}
Err(_) => {
use ast::Expr_;
use ast_defs::Uop;
match expr_ {
Expr_::Unop(uo) if uo.0 == Uop::Unot => emit_jmpnz(e, env, &uo.1, label)?,
Expr_::Binop(bo) if bo.bop.is_barbar() => {
let skip_label = e.label_gen_mut().next_regular();
let r1 = emit_jmpnz(e, env, &bo.lhs, skip_label)?;
if !r1.is_fallthrough {
EmitJmpResult {
instrs: emit_pos_then(
pos,
InstrSeq::gather(if r1.is_label_used {
vec![r1.instrs, instr::label(skip_label)]
} else {
vec![r1.instrs]
}),
),
is_fallthrough: r1.is_label_used,
is_label_used: false,
}
} else {
let r2 = emit_jmpz(e, env, &bo.rhs, label)?;
EmitJmpResult {
instrs: emit_pos_then(
pos,
InstrSeq::gather(if r1.is_label_used {
vec![r1.instrs, r2.instrs, instr::label(skip_label)]
} else {
vec![r1.instrs, r2.instrs]
}),
),
is_fallthrough: r2.is_fallthrough || r1.is_label_used,
is_label_used: r2.is_label_used,
}
}
}
Expr_::Binop(bo) if bo.bop.is_ampamp() => {
let r1 = emit_jmpz(e, env, &bo.lhs, label)?;
if r1.is_fallthrough {
let r2 = emit_jmpz(e, env, &bo.rhs, label)?;
EmitJmpResult {
instrs: emit_pos_then(
pos,
InstrSeq::gather(vec![r1.instrs, r2.instrs]),
),
is_fallthrough: r2.is_fallthrough,
is_label_used: r1.is_label_used || r2.is_label_used,
}
} else {
EmitJmpResult {
instrs: emit_pos_then(pos, r1.instrs),
is_fallthrough: false,
is_label_used: r1.is_label_used,
}
}
}
Expr_::Binop(bo)
if bo.bop.is_eqeqeq()
&& ((bo.lhs).2.is_null() || (bo.rhs).2.is_null())
&& opt =>
{
let is_null = emit_is_null(
e,
env,
if (bo.lhs).2.is_null() {
&bo.rhs
} else {
&bo.lhs
},
)?;
EmitJmpResult {
instrs: emit_pos_then(
pos,
InstrSeq::gather(vec![is_null, instr::jmp_z(label)]),
),
is_fallthrough: true,
is_label_used: true,
}
}
Expr_::Binop(bo)
if bo.bop.is_diff2()
&& ((bo.lhs).2.is_null() || (bo.rhs).2.is_null())
&& opt =>
{
let is_null = emit_is_null(
e,
env,
if (bo.lhs).2.is_null() {
&bo.rhs
} else {
&bo.lhs
},
)?;
EmitJmpResult {
instrs: emit_pos_then(
pos,
InstrSeq::gather(vec![is_null, instr::jmp_nz(label)]),
),
is_fallthrough: true,
is_label_used: true,
}
}
_ => {
let instr = emit_expr(e, env, expr)?;
EmitJmpResult {
instrs: emit_pos_then(
pos,
InstrSeq::gather(vec![instr, instr::jmp_z(label)]),
),
is_fallthrough: true,
is_label_used: true,
}
}
}
}
})
} |
Rust | hhvm/hphp/hack/src/hackc/emitter/emit_fatal.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use emit_pos::emit_pos;
use hhbc::FatalOp;
use instruction_sequence::instr;
use instruction_sequence::InstrSeq;
use oxidized::pos::Pos;
pub fn emit_fatal<'arena>(
alloc: &'arena bumpalo::Bump,
op: FatalOp,
pos: &Pos,
msg: impl AsRef<str>,
) -> InstrSeq<'arena> {
InstrSeq::gather(vec![
emit_pos(pos),
instr::string(alloc, msg.as_ref()),
instr::fatal(op),
])
}
pub fn emit_fatal_runtime<'arena>(
alloc: &'arena bumpalo::Bump,
pos: &Pos,
msg: impl AsRef<str>,
) -> InstrSeq<'arena> {
emit_fatal(alloc, FatalOp::Runtime, pos, msg)
}
pub fn emit_fatal_runtimeomitframe<'arena>(
alloc: &'arena bumpalo::Bump,
pos: &Pos,
msg: impl AsRef<str>,
) -> InstrSeq<'arena> {
emit_fatal(alloc, FatalOp::RuntimeOmitFrame, pos, msg)
}
pub fn emit_fatal_for_break_continue<'arena>(
alloc: &'arena bumpalo::Bump,
pos: &Pos,
) -> InstrSeq<'arena> {
emit_fatal_runtime(alloc, pos, "Cannot break/continue")
} |
Rust | hhvm/hphp/hack/src/hackc/emitter/emit_file_attributes.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use env::emitter::Emitter;
use error::Result;
use hhbc::Attribute;
use itertools::Itertools;
use oxidized::ast;
use crate::emit_attribute::from_asts;
fn emit_file_attributes<'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
fa: &ast::FileAttribute,
) -> Result<Vec<Attribute<'arena>>> {
from_asts(e, &fa.user_attributes[..])
}
pub fn emit_file_attributes_from_program<'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
prog: &[ast::Def],
) -> Result<Vec<Attribute<'arena>>> {
prog.iter()
.filter_map(|node| {
if let ast::Def::FileAttributes(fa) = node {
Some(emit_file_attributes(e, fa))
} else {
None
}
})
.fold_ok(vec![], |mut acc, attrs| {
acc.extend(attrs);
acc
})
} |
Rust | hhvm/hphp/hack/src/hackc/emitter/emit_function.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::sync::Arc;
use ast_scope::Scope;
use ast_scope::ScopeItem;
use env::emitter::Emitter;
use error::Result;
use ffi::Slice;
use ffi::Str;
use hhbc::Attribute;
use hhbc::ClassName;
use hhbc::Coeffects;
use hhbc::Function;
use hhbc::FunctionName;
use hhbc::Span;
use instruction_sequence::instr;
use naming_special_names_rust::user_attributes as ua;
use oxidized::ast;
use oxidized::ast_defs;
use crate::emit_attribute;
use crate::emit_body;
use crate::emit_memoize_function;
use crate::emit_memoize_helpers;
use crate::emit_param;
pub fn emit_function<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
fd: &'a ast::FunDef,
) -> Result<Vec<Function<'arena>>> {
use ast_defs::FunKind;
use hhbc::FunctionFlags;
let alloc = e.alloc;
let f = &fd.fun;
let original_id = FunctionName::from_ast_name(alloc, &fd.name.1);
let mut flags = FunctionFlags::empty();
flags.set(
FunctionFlags::ASYNC,
matches!(f.fun_kind, FunKind::FAsync | FunKind::FAsyncGenerator),
);
let mut user_attrs: Vec<Attribute<'arena>> = emit_attribute::from_asts(e, &f.user_attributes)?;
user_attrs.extend(emit_attribute::add_reified_attribute(alloc, &fd.tparams));
let memoized = user_attrs
.iter()
.any(|a| ua::is_memoized(a.name.unsafe_as_str()));
flags.set(FunctionFlags::MEMOIZE_IMPL, memoized);
let renamed_id = {
if memoized {
FunctionName::add_suffix(alloc, &original_id, emit_memoize_helpers::MEMOIZE_SUFFIX)
} else {
original_id
}
};
let is_meth_caller = fd.name.1.starts_with("\\MethCaller$");
let call_context = if is_meth_caller {
match &f.user_attributes[..] {
[
ast::UserAttribute {
name: ast_defs::Id(_, ref s),
params,
},
] if s == "__MethCaller" => match ¶ms[..] {
[ast::Expr(_, _, ast::Expr_::String(ref ctx))] if !ctx.is_empty() => Some(
ClassName::from_ast_name_and_mangle(
alloc,
// FIXME: This is not safe--string literals are binary strings.
// There's no guarantee that they're valid UTF-8.
unsafe { std::str::from_utf8_unchecked(ctx.as_slice()) },
)
.unsafe_as_str()
.into(),
),
_ => None,
},
_ => None,
}
} else {
None
};
let is_debug_main = match f.user_attributes.as_slice() {
[ast::UserAttribute { name, params }]
if name.1 == "__DebuggerMain" && params.is_empty() =>
{
true
}
_ => false,
};
let mut scope = Scope::default();
if !is_debug_main {
scope.push_item(ScopeItem::Function(ast_scope::Fun::new_ref(fd)));
}
let mut coeffects = Coeffects::from_ast(alloc, f.ctxs.as_ref(), &f.params, &fd.tparams, vec![]);
if is_meth_caller {
coeffects = coeffects.with_caller(alloc)
}
if e.systemlib()
&& (fd.name.1 == "\\HH\\Coeffects\\backdoor"
|| fd.name.1 == "\\HH\\Coeffects\\backdoor_async")
{
coeffects = coeffects.with_backdoor(alloc)
}
if e.systemlib()
&& (fd.name.1 == "\\HH\\Coeffects\\fb\\backdoor_to_globals_leak_safe__DO_NOT_USE")
{
coeffects = coeffects.with_backdoor_globals_leak_safe(alloc)
}
let ast_body = &f.body.fb_ast;
let deprecation_info = hhbc::deprecation_info(user_attrs.iter());
let (body, is_gen, is_pair_gen) = {
let deprecation_info = if memoized { None } else { deprecation_info };
let native = user_attrs
.iter()
.any(|a| ua::is_native(a.name.unsafe_as_str()));
use emit_body::Args as EmitBodyArgs;
use emit_body::Flags as EmitBodyFlags;
let mut body_flags = EmitBodyFlags::empty();
body_flags.set(EmitBodyFlags::ASYNC, flags.contains(FunctionFlags::ASYNC));
body_flags.set(EmitBodyFlags::NATIVE, native);
body_flags.set(EmitBodyFlags::MEMOIZE, memoized);
body_flags.set(
EmitBodyFlags::SKIP_AWAITABLE,
f.fun_kind == ast_defs::FunKind::FAsync,
);
body_flags.set(
EmitBodyFlags::HAS_COEFFECTS_LOCAL,
coeffects.has_coeffects_local(),
);
emit_body::emit_body(
alloc,
e,
Arc::clone(&fd.namespace),
ast_body,
instr::null(),
scope,
EmitBodyArgs {
flags: body_flags,
deprecation_info: &deprecation_info,
default_dropthrough: None,
doc_comment: f.doc_comment.clone(),
pos: &f.span,
ret: f.ret.1.as_ref(),
ast_params: &f.params,
call_context,
immediate_tparams: &fd.tparams,
class_tparam_names: &[],
},
)?
};
flags.set(FunctionFlags::GENERATOR, is_gen);
flags.set(FunctionFlags::PAIR_GENERATOR, is_pair_gen);
let memoize_wrapper = if memoized {
Some(emit_memoize_function::emit_wrapper_function(
e,
original_id,
&renamed_id,
deprecation_info,
fd,
)?)
} else {
None
};
let has_variadic = emit_param::has_variadic(&body.params);
let attrs =
emit_memoize_function::get_attrs_for_fun(e, fd, &user_attrs, memoized, has_variadic);
let normal_function = Function {
attributes: Slice::fill_iter(alloc, user_attrs.into_iter()),
name: FunctionName::new(Str::new_str(alloc, renamed_id.unsafe_as_str())),
span: Span::from_pos(&f.span),
coeffects,
body,
flags,
attrs,
};
Ok(if let Some(memoize_wrapper) = memoize_wrapper {
vec![normal_function, memoize_wrapper]
} else {
vec![normal_function]
})
}
pub fn emit_functions_from_program<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
ast: &'a [ast::Def],
) -> Result<Vec<Function<'arena>>> {
Ok(ast
.iter()
.filter_map(|d| d.as_fun().map(|f| emit_function(e, f)))
.collect::<Result<Vec<Vec<_>>>>()?
.into_iter()
.flatten()
.collect::<Vec<_>>())
} |
Rust | hhvm/hphp/hack/src/hackc/emitter/emit_memoize_function.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::sync::Arc;
use ast_scope::Scope;
use ast_scope::ScopeItem;
use bstr::ByteSlice;
use emit_pos::emit_pos_then;
use env::emitter::Emitter;
use env::Env;
use error::Result;
use ffi::Slice;
use ffi::Str;
use hhbc::Attribute;
use hhbc::Body;
use hhbc::Coeffects;
use hhbc::FCallArgs;
use hhbc::FCallArgsFlags;
use hhbc::Function;
use hhbc::FunctionFlags;
use hhbc::Label;
use hhbc::Local;
use hhbc::LocalRange;
use hhbc::Param;
use hhbc::Span;
use hhbc::TypeInfo;
use hhbc::TypedValue;
use hhbc_string_utils::reified;
use hhvm_types_ffi::ffi::Attr;
use instruction_sequence::instr;
use instruction_sequence::InstrSeq;
use oxidized::ast;
use oxidized::pos::Pos;
use crate::emit_attribute;
use crate::emit_body;
use crate::emit_memoize_helpers;
use crate::emit_param;
pub(crate) fn get_attrs_for_fun<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
fd: &'a ast::FunDef,
user_attrs: &'a [Attribute<'arena>],
is_memoize_impl: bool,
has_variadic: bool,
) -> Attr {
let f = &fd.fun;
let is_systemlib = emitter.systemlib();
let is_dyn_call =
is_systemlib || (hhbc::has_dynamically_callable(user_attrs) && !is_memoize_impl);
let is_prov_skip_frame = hhbc::has_provenance_skip_frame(user_attrs);
let is_meth_caller = hhbc::has_meth_caller(user_attrs);
let is_persistent = is_systemlib
&& !emitter
.options()
.function_is_renamable(fd.name.1.as_bytes().as_bstr());
let is_interceptable = emitter
.options()
.function_is_interceptable(fd.name.1.as_bytes().as_bstr());
let mut attrs = Attr::AttrNone;
attrs.set(Attr::AttrInterceptable, is_interceptable);
attrs.set(Attr::AttrPersistent, is_persistent);
attrs.set(Attr::AttrBuiltin, is_meth_caller | is_systemlib);
attrs.set(Attr::AttrDynamicallyCallable, is_dyn_call);
attrs.set(Attr::AttrIsFoldable, hhbc::has_foldable(user_attrs));
attrs.set(Attr::AttrIsMethCaller, is_meth_caller);
attrs.set(Attr::AttrNoInjection, hhbc::is_no_injection(user_attrs));
attrs.set(Attr::AttrProvenanceSkipFrame, is_prov_skip_frame);
attrs.set(Attr::AttrReadonlyReturn, f.readonly_ret.is_some());
attrs.set(Attr::AttrInternal, fd.internal);
attrs.set(Attr::AttrVariadicParam, has_variadic);
attrs
}
pub(crate) fn emit_wrapper_function<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
original_id: hhbc::FunctionName<'arena>,
renamed_id: &hhbc::FunctionName<'arena>,
deprecation_info: Option<&[TypedValue<'arena>]>,
fd: &'a ast::FunDef,
) -> Result<Function<'arena>> {
let alloc = emitter.alloc;
let f = &fd.fun;
emit_memoize_helpers::check_memoize_possible(&(fd.name).0, &f.params, false)?;
let scope = Scope::with_item(ScopeItem::Function(ast_scope::Fun::new_ref(fd)));
let mut tparams = scope
.get_tparams()
.iter()
.map(|tp| tp.name.1.as_str())
.collect::<Vec<_>>();
let params = emit_param::from_asts(emitter, &mut tparams, true, &scope, &f.params)?;
let mut attributes = emit_attribute::from_asts(emitter, &f.user_attributes)?;
attributes.extend(emit_attribute::add_reified_attribute(alloc, &fd.tparams));
let return_type_info = emit_body::emit_return_type_info(
alloc,
&tparams,
f.fun_kind.is_fasync(), /* skip_awaitable */
f.ret.1.as_ref(),
)?;
let is_reified = fd
.tparams
.iter()
.any(|tp| tp.reified.is_reified() || tp.reified.is_soft_reified());
let should_emit_implicit_context = hhbc::is_keyed_by_ic_memoize(attributes.iter());
let is_make_ic_inaccessible_memoize = hhbc::is_make_ic_inaccessible_memoize(attributes.iter());
let is_soft_make_ic_inaccessible_memoize =
hhbc::is_soft_make_ic_inaccessible_memoize(attributes.iter());
let should_make_ic_inaccessible =
if is_make_ic_inaccessible_memoize || is_soft_make_ic_inaccessible_memoize {
Some(is_soft_make_ic_inaccessible_memoize)
} else {
None
};
let mut env = Env::default(alloc, Arc::clone(&fd.namespace)).with_scope(scope);
let (body_instrs, decl_vars) = make_memoize_function_code(
emitter,
&mut env,
&f.span,
deprecation_info,
¶ms,
&f.params,
*renamed_id,
f.fun_kind.is_fasync(),
is_reified,
should_emit_implicit_context,
should_make_ic_inaccessible,
)?;
let coeffects = Coeffects::from_ast(alloc, f.ctxs.as_ref(), &f.params, &fd.tparams, vec![]);
let body = make_wrapper_body(
emitter,
env,
return_type_info,
params,
decl_vars,
body_instrs,
)?;
let mut flags = FunctionFlags::empty();
flags.set(FunctionFlags::ASYNC, f.fun_kind.is_fasync());
let has_variadic = emit_param::has_variadic(&body.params);
let attrs = get_attrs_for_fun(emitter, fd, &attributes, false, has_variadic);
Ok(Function {
attributes: Slice::fill_iter(alloc, attributes.into_iter()),
name: original_id,
body,
span: Span::from_pos(&f.span),
coeffects,
flags,
attrs,
})
}
fn make_memoize_function_code<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
pos: &Pos,
deprecation_info: Option<&[TypedValue<'arena>]>,
hhas_params: &[(Param<'arena>, Option<(Label, ast::Expr)>)],
ast_params: &[ast::FunParam],
renamed_id: hhbc::FunctionName<'arena>,
is_async: bool,
is_reified: bool,
should_emit_implicit_context: bool,
should_make_ic_inaccessible: Option<bool>,
) -> Result<(InstrSeq<'arena>, Vec<Str<'arena>>)> {
let (fun, decl_vars) = if hhas_params.is_empty() && !is_reified && !should_emit_implicit_context
{
make_memoize_function_no_params_code(
e,
env,
deprecation_info,
renamed_id,
is_async,
should_make_ic_inaccessible,
)
} else {
make_memoize_function_with_params_code(
e,
env,
pos,
deprecation_info,
hhas_params,
ast_params,
renamed_id,
is_async,
is_reified,
should_emit_implicit_context,
should_make_ic_inaccessible,
)
}?;
Ok((emit_pos_then(pos, fun), decl_vars))
}
fn make_memoize_function_with_params_code<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
pos: &Pos,
deprecation_info: Option<&[TypedValue<'arena>]>,
hhas_params: &[(Param<'arena>, Option<(Label, ast::Expr)>)],
ast_params: &[ast::FunParam],
renamed_id: hhbc::FunctionName<'arena>,
is_async: bool,
is_reified: bool,
should_emit_implicit_context: bool,
should_make_ic_inaccessible: Option<bool>,
) -> Result<(InstrSeq<'arena>, Vec<Str<'arena>>)> {
let alloc = e.alloc;
let param_count = hhas_params.len();
let notfound = e.label_gen_mut().next_regular();
let suspended_get = e.label_gen_mut().next_regular();
let eager_set = e.label_gen_mut().next_regular();
// The local that contains the reified generics is the first non parameter local,
// so the first unnamed local is parameter count + 1 when there are reified generics.
let add_reified = usize::from(is_reified);
let add_implicit_context = usize::from(should_emit_implicit_context);
let generics_local = Local::new(param_count); // only used if is_reified == true.
let decl_vars = match is_reified {
true => vec![reified::GENERICS_LOCAL_NAME.into()],
false => Vec::new(),
};
e.init_named_locals(
hhas_params
.iter()
.map(|(param, _)| param.name)
.chain(decl_vars.iter().copied()),
);
let first_unnamed_idx = param_count + add_reified;
let deprecation_body =
emit_body::emit_deprecation_info(alloc, &env.scope, deprecation_info, e.systemlib())?;
let (begin_label, default_value_setters) =
// Default value setters belong in the wrapper method not in the original method
emit_param::emit_param_default_value_setter(e, env, pos, hhas_params)?;
let fcall_args = {
let mut fcall_flags = FCallArgsFlags::default();
fcall_flags.set(FCallArgsFlags::HasGenerics, is_reified);
FCallArgs::new(
fcall_flags,
1,
param_count as u32,
Slice::empty(),
Slice::empty(),
if is_async { Some(eager_set) } else { None },
None,
)
};
let (reified_get, reified_memokeym) = if !is_reified {
(instr::empty(), instr::empty())
} else {
(
instr::c_get_l(generics_local),
InstrSeq::gather(emit_memoize_helpers::get_memo_key_list(
Local::new(param_count + first_unnamed_idx),
generics_local,
)),
)
};
let ic_memokey = if !should_emit_implicit_context {
instr::empty()
} else {
// Last unnamed local slot
let local = Local::new(first_unnamed_idx + param_count + add_reified);
emit_memoize_helpers::get_implicit_context_memo_key(alloc, local)
};
let first_unnamed_local = Local::new(first_unnamed_idx);
let key_count = (param_count + add_reified + add_implicit_context) as isize;
let local_range = LocalRange {
start: first_unnamed_local,
len: key_count.try_into().unwrap(),
};
let ic_stash_local = Local::new(first_unnamed_idx + (key_count) as usize);
let instrs = InstrSeq::gather(vec![
begin_label,
emit_body::emit_method_prolog(e, env, pos, hhas_params, ast_params, &[])?,
deprecation_body,
instr::verify_implicit_context_state(),
emit_memoize_helpers::param_code_sets(hhas_params.len(), Local::new(first_unnamed_idx)),
reified_memokeym,
ic_memokey,
if is_async {
InstrSeq::gather(vec![
instr::memo_get_eager(notfound, suspended_get, local_range),
instr::ret_c(),
instr::label(suspended_get),
instr::ret_c_suspended(),
])
} else {
InstrSeq::gather(vec![instr::memo_get(notfound, local_range), instr::ret_c()])
},
instr::label(notfound),
instr::null_uninit(),
instr::null_uninit(),
emit_memoize_helpers::param_code_gets(hhas_params.len()),
reified_get,
emit_memoize_helpers::with_possible_ic(
alloc,
e.label_gen_mut(),
ic_stash_local,
instr::f_call_func_d(fcall_args, renamed_id),
should_make_ic_inaccessible,
),
instr::memo_set(local_range),
if is_async {
InstrSeq::gather(vec![
instr::ret_c_suspended(),
instr::label(eager_set),
instr::memo_set_eager(local_range),
emit_memoize_helpers::ic_restore(ic_stash_local, should_make_ic_inaccessible),
instr::ret_c(),
])
} else {
instr::ret_c()
},
default_value_setters,
]);
Ok((instrs, decl_vars))
}
fn make_memoize_function_no_params_code<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
deprecation_info: Option<&[TypedValue<'arena>]>,
renamed_id: hhbc::FunctionName<'arena>,
is_async: bool,
should_make_ic_inaccessible: Option<bool>,
) -> Result<(InstrSeq<'arena>, Vec<Str<'arena>>)> {
let alloc = e.alloc;
let notfound = e.label_gen_mut().next_regular();
let suspended_get = e.label_gen_mut().next_regular();
let eager_set = e.label_gen_mut().next_regular();
let deprecation_body =
emit_body::emit_deprecation_info(alloc, &env.scope, deprecation_info, e.systemlib())?;
let fcall_args = FCallArgs::new(
FCallArgsFlags::default(),
1,
0,
Slice::empty(),
Slice::empty(),
if is_async { Some(eager_set) } else { None },
None,
);
let ic_stash_local = Local::new(0);
let instrs = InstrSeq::gather(vec![
deprecation_body,
instr::verify_implicit_context_state(),
if is_async {
InstrSeq::gather(vec![
instr::memo_get_eager(notfound, suspended_get, LocalRange::EMPTY),
instr::ret_c(),
instr::label(suspended_get),
instr::ret_c_suspended(),
])
} else {
InstrSeq::gather(vec![
instr::memo_get(notfound, LocalRange::EMPTY),
instr::ret_c(),
])
},
instr::label(notfound),
instr::null_uninit(),
instr::null_uninit(),
emit_memoize_helpers::with_possible_ic(
alloc,
e.label_gen_mut(),
ic_stash_local,
instr::f_call_func_d(fcall_args, renamed_id),
should_make_ic_inaccessible,
),
instr::memo_set(LocalRange::EMPTY),
if is_async {
InstrSeq::gather(vec![
instr::ret_c_suspended(),
instr::label(eager_set),
instr::memo_set_eager(LocalRange::EMPTY),
emit_memoize_helpers::ic_restore(ic_stash_local, should_make_ic_inaccessible),
instr::ret_c(),
])
} else {
instr::ret_c()
},
]);
Ok((instrs, Vec::new()))
}
fn make_wrapper_body<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
env: Env<'a, 'arena>,
return_type_info: TypeInfo<'arena>,
params: Vec<(Param<'arena>, Option<(Label, ast::Expr)>)>,
decl_vars: Vec<Str<'arena>>,
body_instrs: InstrSeq<'arena>,
) -> Result<Body<'arena>> {
emit_body::make_body(
emitter.alloc,
emitter,
body_instrs,
decl_vars,
true, /* is_memoize_wrapper */
false, /* is_memoize_wrapper_lsb */
vec![], /* upper_bounds */
vec![], /* shadowed_tparams */
params,
Some(return_type_info),
None, /* doc comment */
Some(&env),
)
} |
Rust | hhvm/hphp/hack/src/hackc/emitter/emit_memoize_helpers.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use env::LabelGen;
use error::Error;
use error::Result;
use ffi::Slice;
use hhbc::FCallArgs;
use hhbc::FCallArgsFlags;
use hhbc::Local;
use instruction_sequence::instr;
use instruction_sequence::InstrSeq;
use oxidized::aast::FunParam;
use oxidized::pos::Pos;
use scope::create_try_catch;
pub const MEMOIZE_SUFFIX: &str = "$memoize_impl";
pub fn get_memo_key_list<'arena>(temp_local: Local, param_local: Local) -> Vec<InstrSeq<'arena>> {
vec![
instr::get_memo_key_l(param_local),
instr::set_l(temp_local),
instr::pop_c(),
]
}
pub fn param_code_sets<'arena>(num_params: usize, first_unnamed: Local) -> InstrSeq<'arena> {
InstrSeq::gather(
(0..num_params)
.flat_map(|i| {
let param_local = Local::new(i);
let temp_local = Local::new(first_unnamed.idx as usize + i);
get_memo_key_list(temp_local, param_local)
})
.collect(),
)
}
pub fn param_code_gets<'arena>(num_params: usize) -> InstrSeq<'arena> {
InstrSeq::gather(
(0..num_params)
.map(|i| instr::c_get_l(Local::new(i)))
.collect(),
)
}
pub fn check_memoize_possible<Ex, En>(
pos: &Pos,
params: &[FunParam<Ex, En>],
is_method: bool,
) -> Result<()> {
if !is_method && params.iter().any(|param| param.is_variadic) {
return Err(Error::fatal_runtime(
pos,
String::from("<<__Memoize>> cannot be used on functions with variable arguments"),
));
}
Ok(())
}
pub fn get_implicit_context_memo_key<'arena>(
alloc: &'arena bumpalo::Bump,
local: Local,
) -> InstrSeq<'arena> {
InstrSeq::gather(vec![
instr::null_uninit(),
instr::null_uninit(),
instr::f_call_func_d(
FCallArgs::new(
FCallArgsFlags::default(),
1,
0,
Slice::empty(),
Slice::empty(),
None,
None,
),
hhbc::FunctionName::from_raw_string(
alloc,
"HH\\ImplicitContext\\_Private\\get_implicit_context_memo_key",
),
),
instr::set_l(local),
instr::pop_c(),
])
}
fn ic_set<'arena>(alloc: &'arena bumpalo::Bump, local: Local, soft: bool) -> InstrSeq<'arena> {
if soft {
InstrSeq::gather(vec![
instr::cns_e(hhbc::ConstName::from_raw_string(
alloc,
"HH\\MEMOIZE_IC_TYPE_SOFT_INACCESSIBLE",
)),
instr::null(),
instr::create_special_implicit_context(),
instr::set_implicit_context_by_value(),
instr::set_l(local),
instr::pop_c(),
])
} else {
InstrSeq::gather(vec![
instr::null_uninit(),
instr::null_uninit(),
instr::f_call_func_d(
FCallArgs::new(
FCallArgsFlags::default(),
1,
0,
Slice::empty(),
Slice::empty(),
None,
None,
),
hhbc::FunctionName::from_raw_string(
alloc,
"HH\\ImplicitContext\\_Private\\create_ic_inaccessible_context",
),
),
instr::set_implicit_context_by_value(),
instr::set_l(local),
instr::pop_c(),
])
}
}
pub fn ic_restore<'arena>(
local: Local,
should_make_ic_inaccessible: Option<bool>,
) -> InstrSeq<'arena> {
if should_make_ic_inaccessible.is_some() {
InstrSeq::gather(vec![
instr::c_get_l(local),
instr::set_implicit_context_by_value(),
instr::pop_c(),
])
} else {
instr::empty()
}
}
pub fn with_possible_ic<'arena>(
alloc: &'arena bumpalo::Bump,
label_gen: &mut LabelGen,
local: Local,
instrs: InstrSeq<'arena>,
should_make_ic_inaccessible: Option<bool>,
) -> InstrSeq<'arena> {
if let Some(soft) = should_make_ic_inaccessible {
InstrSeq::gather(vec![
ic_set(alloc, local, soft),
create_try_catch(
label_gen,
None,
false,
instrs,
ic_restore(local, should_make_ic_inaccessible),
),
ic_restore(local, should_make_ic_inaccessible),
])
} else {
instrs
}
} |
Rust | hhvm/hphp/hack/src/hackc/emitter/emit_memoize_method.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use ast_scope::Scope;
use ast_scope::ScopeItem;
use bitflags::bitflags;
use emit_method::get_attrs_for_method;
use emit_pos::emit_pos_then;
use env::emitter::Emitter;
use env::Env;
use error::Error;
use error::Result;
use ffi::Slice;
use ffi::Str;
use hhbc::Body;
use hhbc::Coeffects;
use hhbc::FCallArgs;
use hhbc::FCallArgsFlags;
use hhbc::Label;
use hhbc::Local;
use hhbc::LocalRange;
use hhbc::Method;
use hhbc::MethodFlags;
use hhbc::Param;
use hhbc::Span;
use hhbc::SpecialClsRef;
use hhbc::TypeInfo;
use hhbc::TypedValue;
use hhbc::Visibility;
use hhbc_string_utils::reified;
use instruction_sequence::instr;
use instruction_sequence::InstrSeq;
use naming_special_names_rust::members;
use naming_special_names_rust::user_attributes;
use oxidized::ast;
use oxidized::pos::Pos;
use crate::emit_attribute;
use crate::emit_body;
use crate::emit_memoize_helpers;
use crate::emit_method;
use crate::emit_param;
/// Precomputed information required for generation of memoized methods
pub struct MemoizeInfo<'arena> {
/// True if the enclosing class is a trait
is_trait: bool,
/// Enclosing class name
class_name: hhbc::ClassName<'arena>,
}
fn is_memoize(method: &ast::Method_) -> bool {
method
.user_attributes
.iter()
.any(|a| user_attributes::is_memoized(&a.name.1))
}
fn is_memoize_lsb(method: &ast::Method_) -> bool {
method
.user_attributes
.iter()
.any(|a| user_attributes::MEMOIZE_LSB == a.name.1)
}
pub fn make_info<'arena>(
class: &ast::Class_,
class_name: hhbc::ClassName<'arena>,
methods: &[ast::Method_],
) -> Result<MemoizeInfo<'arena>> {
for m in methods.iter() {
// check methods
if is_memoize(m) {
emit_memoize_helpers::check_memoize_possible(&m.name.0, &m.params[..], true)?;
let pos = &m.name.0;
if class.kind.is_cinterface() {
return Err(Error::fatal_runtime(
pos,
"<<__Memoize>> cannot be used in interfaces",
));
} else if m.abstract_ {
return Err(Error::fatal_parse(
pos,
format!(
"Abstract method {}::{} cannot be memoized",
class_name.unsafe_as_str(),
&m.name.1,
),
));
};
};
}
let is_trait = class.kind.is_ctrait();
Ok(MemoizeInfo {
is_trait,
class_name,
})
}
pub fn emit_wrapper_methods<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
info: &MemoizeInfo<'arena>,
class: &'a ast::Class_,
methods: &'a [ast::Method_],
) -> Result<Vec<Method<'arena>>> {
// Wrapper methods may not have iterators
emitter.iterator_mut().reset();
let mut hhas_methods = vec![];
for m in methods.iter() {
if is_memoize(m) {
env.scope
.push_item(ScopeItem::Method(ast_scope::Method::new_ref(m)));
hhas_methods.push(make_memoize_wrapper_method(emitter, env, info, class, m)?);
};
}
Ok(hhas_methods)
}
// This is cut-and-paste from emit_method, with special casing for wrappers
fn make_memoize_wrapper_method<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
info: &MemoizeInfo<'arena>,
class: &'a ast::Class_,
method: &'a ast::Method_,
) -> Result<Method<'arena>> {
let alloc = env.arena;
let ret = if method.name.1 == members::__CONSTRUCT {
None
} else {
method.ret.1.as_ref()
};
let name = hhbc::MethodName::from_ast_name(alloc, &method.name.1);
let mut scope = Scope::default();
scope.push_item(ScopeItem::Class(ast_scope::Class::new_ref(class)));
scope.push_item(ScopeItem::Method(ast_scope::Method::new_ref(method)));
let mut attributes = emit_attribute::from_asts(emitter, &method.user_attributes)?;
attributes.extend(emit_attribute::add_reified_attribute(
alloc,
&method.tparams,
));
let is_async = method.fun_kind.is_fasync();
// __Memoize is not allowed on lambdas, so we never need to inherit the rx
// level from the declaring scope when we're in a Memoize wrapper
let coeffects = Coeffects::from_ast(
alloc,
method.ctxs.as_ref(),
&method.params,
&method.tparams,
&class.tparams,
);
let is_reified = method
.tparams
.iter()
.any(|tp| tp.reified.is_reified() || tp.reified.is_soft_reified());
let mut arg_flags = Flags::empty();
arg_flags.set(Flags::IS_ASYNC, is_async);
arg_flags.set(Flags::IS_REIFIED, is_reified);
arg_flags.set(
Flags::SHOULD_EMIT_IMPLICIT_CONTEXT,
hhbc::is_keyed_by_ic_memoize(attributes.iter()),
);
arg_flags.set(
Flags::SHOULD_MAKE_IC_INACCESSIBLE,
hhbc::is_make_ic_inaccessible_memoize(attributes.iter()),
);
arg_flags.set(
Flags::SHOULD_SOFT_MAKE_IC_INACCESSIBLE,
hhbc::is_soft_make_ic_inaccessible_memoize(attributes.iter()),
);
let mut args = Args {
info,
method,
scope: &scope,
deprecation_info: hhbc::deprecation_info(attributes.iter()),
params: &method.params,
ret,
method_id: &name,
flags: arg_flags,
};
let body = emit_memoize_wrapper_body(emitter, env, &mut args)?;
let mut flags = MethodFlags::empty();
flags.set(MethodFlags::IS_ASYNC, is_async);
let has_variadic = emit_param::has_variadic(&body.params);
let attrs = get_attrs_for_method(
emitter,
method,
&attributes,
&method.visibility,
class,
false,
has_variadic,
);
Ok(Method {
attributes: Slice::fill_iter(alloc, attributes.into_iter()),
visibility: Visibility::from(method.visibility),
name,
body,
span: Span::from_pos(&method.span),
coeffects,
flags,
attrs,
})
}
fn emit_memoize_wrapper_body<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
args: &mut Args<'_, 'a, 'arena>,
) -> Result<Body<'arena>> {
let alloc = env.arena;
let mut tparams: Vec<&str> = args
.scope
.get_tparams()
.iter()
.map(|tp| tp.name.1.as_str())
.collect();
let return_type_info = emit_body::emit_return_type_info(
alloc,
&tparams[..],
args.flags.contains(Flags::IS_ASYNC),
args.ret,
)?;
let hhas_params = emit_param::from_asts(emitter, &mut tparams, true, args.scope, args.params)?;
args.flags.set(Flags::WITH_LSB, is_memoize_lsb(args.method));
args.flags.set(Flags::IS_STATIC, args.method.static_);
emit(emitter, env, hhas_params, return_type_info, args)
}
fn emit<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
hhas_params: Vec<(Param<'arena>, Option<(Label, ast::Expr)>)>,
return_type_info: TypeInfo<'arena>,
args: &Args<'_, 'a, 'arena>,
) -> Result<Body<'arena>> {
let pos = &args.method.span;
let (instrs, decl_vars) = make_memoize_method_code(emitter, env, pos, &hhas_params, args)?;
let instrs = emit_pos_then(pos, instrs);
make_wrapper(
emitter,
env,
instrs,
hhas_params,
decl_vars,
return_type_info,
args,
)
}
fn make_memoize_method_code<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
pos: &Pos,
hhas_params: &[(Param<'arena>, Option<(Label, ast::Expr)>)],
args: &Args<'_, 'a, 'arena>,
) -> Result<(InstrSeq<'arena>, Vec<Str<'arena>>)> {
if args.params.is_empty()
&& !args.flags.contains(Flags::IS_REIFIED)
&& !args.flags.contains(Flags::SHOULD_EMIT_IMPLICIT_CONTEXT)
{
make_memoize_method_no_params_code(emitter, args)
} else {
make_memoize_method_with_params_code(emitter, env, pos, hhas_params, args)
}
}
// method is the already-renamed memoize method that must be wrapped
fn make_memoize_method_with_params_code<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
pos: &Pos,
hhas_params: &[(Param<'arena>, Option<(Label, ast::Expr)>)],
args: &Args<'_, 'a, 'arena>,
) -> Result<(InstrSeq<'arena>, Vec<Str<'arena>>)> {
let alloc = env.arena;
let param_count = hhas_params.len();
let notfound = emitter.label_gen_mut().next_regular();
let suspended_get = emitter.label_gen_mut().next_regular();
let eager_set = emitter.label_gen_mut().next_regular();
// The local that contains the reified generics is the first non parameter local,
// so the first unnamed local is parameter count + 1 when there are reified generics.
let is_reified = args.flags.contains(Flags::IS_REIFIED);
let add_reified = usize::from(is_reified);
let should_emit_implicit_context = args.flags.contains(Flags::SHOULD_EMIT_IMPLICIT_CONTEXT);
let add_implicit_context = usize::from(should_emit_implicit_context);
let first_unnamed_idx = param_count + add_reified;
let generics_local = Local::new(param_count); // only used if is_reified == true.
let decl_vars = match is_reified {
true => vec![reified::GENERICS_LOCAL_NAME.into()],
false => Vec::new(),
};
emitter.init_named_locals(
hhas_params
.iter()
.map(|(param, _)| param.name)
.chain(decl_vars.iter().copied()),
);
let deprecation_body = emit_body::emit_deprecation_info(
alloc,
args.scope,
args.deprecation_info,
emitter.systemlib(),
)?;
let (begin_label, default_value_setters) =
// Default value setters belong in the wrapper method not in the original method
emit_param::emit_param_default_value_setter(emitter, env, pos, hhas_params)?;
let fcall_args = {
let mut fcall_flags = FCallArgsFlags::default();
if is_reified {
fcall_flags |= FCallArgsFlags::HasGenerics;
};
let async_eager_target = if args.flags.contains(Flags::IS_ASYNC) {
Some(eager_set)
} else {
None
};
FCallArgs::new(
fcall_flags,
1,
param_count as u32,
Slice::empty(),
Slice::empty(),
async_eager_target,
None,
)
};
let (reified_get, reified_memokeym) = if !is_reified {
(instr::empty(), instr::empty())
} else {
(
instr::c_get_l(generics_local),
InstrSeq::gather(emit_memoize_helpers::get_memo_key_list(
Local::new(param_count + first_unnamed_idx),
generics_local,
)),
)
};
let ic_memokey = if !should_emit_implicit_context {
instr::empty()
} else {
// Last unnamed local slot
let local = Local::new(first_unnamed_idx + param_count + add_reified);
emit_memoize_helpers::get_implicit_context_memo_key(alloc, local)
};
let first_unnamed_local = Local::new(first_unnamed_idx);
let key_count = (param_count + add_reified + add_implicit_context) as isize;
let local_range = LocalRange {
start: first_unnamed_local,
len: key_count.try_into().unwrap(),
};
let ic_stash_local = Local::new((key_count) as usize + first_unnamed_idx);
let should_make_ic_inaccessible = if args.flags.contains(Flags::SHOULD_MAKE_IC_INACCESSIBLE)
|| args.flags.contains(Flags::SHOULD_SOFT_MAKE_IC_INACCESSIBLE)
{
Some(args.flags.contains(Flags::SHOULD_SOFT_MAKE_IC_INACCESSIBLE))
} else {
None
};
let instrs = InstrSeq::gather(vec![
begin_label,
emit_body::emit_method_prolog(emitter, env, pos, hhas_params, args.params, &[])?,
deprecation_body,
if args.method.static_ {
instr::empty()
} else {
instr::check_this()
},
instr::verify_implicit_context_state(),
emit_memoize_helpers::param_code_sets(hhas_params.len(), Local::new(first_unnamed_idx)),
reified_memokeym,
ic_memokey,
if args.flags.contains(Flags::IS_ASYNC) {
InstrSeq::gather(vec![
instr::memo_get_eager(notfound, suspended_get, local_range),
instr::ret_c(),
instr::label(suspended_get),
instr::ret_c_suspended(),
])
} else {
InstrSeq::gather(vec![instr::memo_get(notfound, local_range), instr::ret_c()])
},
instr::label(notfound),
if args.method.static_ {
instr::null_uninit()
} else {
instr::this()
},
instr::null_uninit(),
emit_memoize_helpers::param_code_gets(hhas_params.len()),
reified_get,
emit_memoize_helpers::with_possible_ic(
alloc,
emitter.label_gen_mut(),
ic_stash_local,
if args.method.static_ {
call_cls_method(alloc, fcall_args, args)
} else {
let renamed_method_id = hhbc::MethodName::add_suffix(
alloc,
args.method_id,
emit_memoize_helpers::MEMOIZE_SUFFIX,
);
instr::f_call_obj_method_d(fcall_args, renamed_method_id)
},
should_make_ic_inaccessible,
),
instr::memo_set(local_range),
if args.flags.contains(Flags::IS_ASYNC) {
InstrSeq::gather(vec![
instr::ret_c_suspended(),
instr::label(eager_set),
instr::memo_set_eager(local_range),
emit_memoize_helpers::ic_restore(ic_stash_local, should_make_ic_inaccessible),
instr::ret_c(),
])
} else {
instr::ret_c()
},
default_value_setters,
]);
Ok((instrs, decl_vars))
}
fn make_memoize_method_no_params_code<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
args: &Args<'_, 'a, 'arena>,
) -> Result<(InstrSeq<'arena>, Vec<Str<'arena>>)> {
let notfound = emitter.label_gen_mut().next_regular();
let suspended_get = emitter.label_gen_mut().next_regular();
let eager_set = emitter.label_gen_mut().next_regular();
let alloc = emitter.alloc;
let deprecation_body = emit_body::emit_deprecation_info(
alloc,
args.scope,
args.deprecation_info,
emitter.systemlib(),
)?;
let fcall_args = FCallArgs::new(
FCallArgsFlags::default(),
1,
0,
Slice::empty(),
Slice::empty(),
if args.flags.contains(Flags::IS_ASYNC) {
Some(eager_set)
} else {
None
},
None,
);
let ic_stash_local = Local::new(0);
let should_make_ic_inaccessible = if args.flags.contains(Flags::SHOULD_MAKE_IC_INACCESSIBLE)
|| args.flags.contains(Flags::SHOULD_SOFT_MAKE_IC_INACCESSIBLE)
{
Some(args.flags.contains(Flags::SHOULD_SOFT_MAKE_IC_INACCESSIBLE))
} else {
None
};
let instrs = InstrSeq::gather(vec![
deprecation_body,
if args.method.static_ {
instr::empty()
} else {
instr::check_this()
},
instr::verify_implicit_context_state(),
if args.flags.contains(Flags::IS_ASYNC) {
InstrSeq::gather(vec![
instr::memo_get_eager(notfound, suspended_get, LocalRange::EMPTY),
instr::ret_c(),
instr::label(suspended_get),
instr::ret_c_suspended(),
])
} else {
InstrSeq::gather(vec![
instr::memo_get(notfound, LocalRange::EMPTY),
instr::ret_c(),
])
},
instr::label(notfound),
if args.method.static_ {
instr::null_uninit()
} else {
instr::this()
},
instr::null_uninit(),
emit_memoize_helpers::with_possible_ic(
alloc,
emitter.label_gen_mut(),
ic_stash_local,
if args.method.static_ {
call_cls_method(alloc, fcall_args, args)
} else {
let renamed_method_id = hhbc::MethodName::add_suffix(
alloc,
args.method_id,
emit_memoize_helpers::MEMOIZE_SUFFIX,
);
instr::f_call_obj_method_d(fcall_args, renamed_method_id)
},
should_make_ic_inaccessible,
),
instr::memo_set(LocalRange::EMPTY),
if args.flags.contains(Flags::IS_ASYNC) {
InstrSeq::gather(vec![
instr::ret_c_suspended(),
instr::label(eager_set),
instr::memo_set_eager(LocalRange::EMPTY),
emit_memoize_helpers::ic_restore(ic_stash_local, should_make_ic_inaccessible),
instr::ret_c(),
])
} else {
instr::ret_c()
},
]);
Ok((instrs, Vec::new()))
}
// Construct the wrapper function
fn make_wrapper<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
instrs: InstrSeq<'arena>,
params: Vec<(Param<'arena>, Option<(Label, ast::Expr)>)>,
decl_vars: Vec<Str<'arena>>,
return_type_info: TypeInfo<'arena>,
args: &Args<'_, 'a, 'arena>,
) -> Result<Body<'arena>> {
emit_body::make_body(
env.arena,
emitter,
instrs,
decl_vars,
true,
args.flags.contains(Flags::WITH_LSB),
vec![], /* upper_bounds */
vec![], /* shadowed_tparams */
params,
Some(return_type_info),
None,
Some(env),
)
}
fn call_cls_method<'a, 'arena>(
alloc: &'arena bumpalo::Bump,
fcall_args: FCallArgs<'arena>,
args: &Args<'_, 'a, 'arena>,
) -> InstrSeq<'arena> {
let method_id =
hhbc::MethodName::add_suffix(alloc, args.method_id, emit_memoize_helpers::MEMOIZE_SUFFIX);
if args.info.is_trait || args.flags.contains(Flags::WITH_LSB) {
instr::f_call_cls_method_sd(fcall_args, SpecialClsRef::SelfCls, method_id)
} else {
instr::f_call_cls_method_d(fcall_args, method_id, args.info.class_name)
}
}
struct Args<'r, 'ast, 'arena> {
pub info: &'r MemoizeInfo<'arena>,
pub method: &'r ast::Method_,
pub scope: &'r Scope<'ast, 'arena>,
pub deprecation_info: Option<&'r [TypedValue<'arena>]>,
pub params: &'r [ast::FunParam],
pub ret: Option<&'r ast::Hint>,
pub method_id: &'r hhbc::MethodName<'arena>,
pub flags: Flags,
}
bitflags! {
pub struct Flags: u8 {
const IS_STATIC = 1 << 1;
const IS_REIFIED = 1 << 2;
const WITH_LSB = 1 << 3;
const IS_ASYNC = 1 << 4;
const SHOULD_EMIT_IMPLICIT_CONTEXT = 1 << 5;
const SHOULD_MAKE_IC_INACCESSIBLE = 1 << 6;
const SHOULD_SOFT_MAKE_IC_INACCESSIBLE = 1 << 7;
}
} |
Rust | hhvm/hphp/hack/src/hackc/emitter/emit_method.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::borrow::Cow;
use std::sync::Arc;
use ast_scope::Lambda;
use ast_scope::Scope;
use ast_scope::ScopeItem;
use env::emitter::Emitter;
use error::Error;
use error::Result;
use ffi::Slice;
use hhbc::Attribute;
use hhbc::Coeffects;
use hhbc::Method;
use hhbc::MethodFlags;
use hhbc::Span;
use hhbc::Visibility;
use hhbc_string_utils as string_utils;
use hhvm_types_ffi::ffi::Attr;
use instruction_sequence::instr;
use naming_special_names_rust::classes;
use naming_special_names_rust::members;
use naming_special_names_rust::user_attributes;
use oxidized::ast;
use oxidized::ast_defs;
use crate::emit_attribute;
use crate::emit_body;
use crate::emit_fatal;
use crate::emit_memoize_helpers;
use crate::emit_native_opcode;
use crate::emit_param;
pub fn from_asts<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
class: &'a ast::Class_,
methods: &'a [ast::Method_],
) -> Result<Vec<Method<'arena>>> {
methods
.iter()
.map(|m| from_ast(emitter, class, m))
.collect()
}
pub fn get_attrs_for_method<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
method: &'a ast::Method_,
user_attrs: &'a [Attribute<'arena>],
visibility: &'a ast::Visibility,
class: &'a ast::Class_,
is_memoize_impl: bool,
has_variadic: bool,
) -> Attr {
let is_abstract = class.kind.is_cinterface() || method.abstract_;
let is_systemlib = emitter.systemlib();
let is_dyn_callable =
is_systemlib || (hhbc::has_dynamically_callable(user_attrs) && !is_memoize_impl);
let is_no_injection = hhbc::is_no_injection(user_attrs);
let is_prov_skip_frame = hhbc::has_provenance_skip_frame(user_attrs);
let is_readonly_return = method.readonly_ret.is_some();
let mut attrs = Attr::AttrNone;
attrs.add(Attr::from(visibility));
attrs.set(Attr::AttrAbstract, is_abstract);
attrs.set(Attr::AttrBuiltin, is_systemlib);
attrs.set(Attr::AttrDynamicallyCallable, is_dyn_callable);
attrs.set(Attr::AttrFinal, method.final_);
attrs.add(Attr::AttrInterceptable);
attrs.set(Attr::AttrIsFoldable, hhbc::has_foldable(user_attrs));
attrs.set(Attr::AttrNoInjection, is_no_injection);
attrs.set(Attr::AttrPersistent, is_systemlib);
attrs.set(Attr::AttrReadonlyReturn, is_readonly_return);
attrs.set(Attr::AttrReadonlyThis, method.readonly_this);
attrs.set(Attr::AttrStatic, method.static_);
attrs.set(Attr::AttrVariadicParam, has_variadic);
attrs.set(Attr::AttrProvenanceSkipFrame, is_prov_skip_frame);
attrs
}
pub fn from_ast<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
class: &'a ast::Class_,
method_: impl Into<Cow<'a, ast::Method_>>,
) -> Result<Method<'arena>> {
let method_: Cow<'a, ast::Method_> = method_.into();
let method = method_.as_ref();
let is_memoize = method
.user_attributes
.iter()
.any(|ua| user_attributes::is_memoized(&ua.name.1));
let class_name = string_utils::mangle(string_utils::strip_global_ns(&class.name.1).into());
let is_closure_body =
method.name.1 == members::__INVOKE && (class.name.1).starts_with("Closure$");
let mut attributes = emit_attribute::from_asts(emitter, &method.user_attributes)?;
if !is_closure_body {
attributes.extend(emit_attribute::add_reified_attribute(
emitter.alloc,
&method.tparams[..],
));
};
let call_context = if is_closure_body {
match &method.user_attributes[..] {
[
ast::UserAttribute {
name: ast_defs::Id(_, ref s),
params: _,
},
] if s.eq_ignore_ascii_case("__DynamicMethCallerForce") => {
Some("__SystemLib\\DynamicContextOverrideUnsafe".to_string())
}
_ => None,
}
} else {
None
};
let is_native = attributes
.iter()
.any(|attr| attr.is(user_attributes::is_native));
let is_native_opcode_impl = hhbc::is_native_opcode_impl(&attributes);
let is_async = method.fun_kind.is_fasync() || method.fun_kind.is_fasync_generator();
if class.kind.is_cinterface() && !method.body.fb_ast.is_empty() {
return Err(Error::fatal_parse(
&method.name.0,
format!(
"Interface method {}::{} cannot contain body",
class_name, &method.name.1
),
));
};
let is_cabstract = match class.kind {
ast_defs::ClassishKind::Cclass(k) => k.is_abstract(),
_ => false,
};
if !method.static_ && class.final_ && is_cabstract {
return Err(Error::fatal_parse(
&method.name.0,
format!(
"Class {} contains non-static method {} and therefore cannot be declared 'abstract final'",
class_name, &method.name.1
),
));
};
let visibility = if is_native_opcode_impl {
ast::Visibility::Public
} else if is_memoize {
ast::Visibility::Private
} else {
method.visibility
};
let deprecation_info = if is_memoize {
None
} else {
hhbc::deprecation_info(attributes.iter())
};
let default_dropthrough = if method.abstract_ {
Some(emit_fatal::emit_fatal_runtimeomitframe(
emitter.alloc,
&method.name.0,
format!(
"Cannot call abstract method {}::{}()",
class_name, &method.name.1
),
))
} else {
None
};
let mut scope = Scope::default();
scope.push_item(ScopeItem::Class(ast_scope::Class::new_ref(class)));
scope.push_item(ScopeItem::Method(match &method_ {
Cow::Borrowed(m) => ast_scope::Method::new_ref(m),
Cow::Owned(m) => ast_scope::Method::new_rc(m),
}));
if is_closure_body {
scope.push_item(ScopeItem::Lambda(Lambda {
is_long: false,
is_async,
coeffects: Coeffects::default(),
pos: method.span.clone(),
}))
};
let namespace = Arc::clone(
emitter
.global_state()
.closure_namespaces
.get(&class_name)
.unwrap_or(&class.namespace),
);
let mut coeffects = if method.ctxs.is_none() && is_closure_body {
let parent_coeffects = emitter
.global_state()
.get_lambda_coeffects_of_scope(&class.name.1, &method.name.1);
parent_coeffects.map_or(Coeffects::default(), |pc| {
pc.inherit_to_child_closure(emitter.alloc)
})
} else {
Coeffects::from_ast(
emitter.alloc,
method.ctxs.as_ref(),
&method.params,
&method.tparams,
&class.tparams,
)
};
if is_closure_body && coeffects.is_86caller() {
coeffects = coeffects.with_caller(emitter.alloc)
}
if is_native_opcode_impl
&& (class.name.1.as_str() == classes::GENERATOR
|| class.name.1.as_str() == classes::ASYNC_GENERATOR)
{
match method.name.1.as_str() {
"send" | "raise" | "throw" | "next" | "rewind" => {
coeffects = coeffects.with_gen_coeffect()
}
_ => {}
}
}
if emitter.systemlib() {
match (class.name.1.as_str(), method.name.1.as_str()) {
("\\__SystemLib\\MethCallerHelper", members::__INVOKE)
| ("\\__SystemLib\\DynMethCallerHelper", members::__INVOKE) => {
coeffects = coeffects.with_caller(emitter.alloc)
}
_ => {}
}
}
let ast_body_block = &method.body.fb_ast;
let (body, is_generator, is_pair_generator) = if is_native_opcode_impl {
(
emit_native_opcode::emit_body(
emitter,
&scope,
&class.user_attributes,
&method.name,
&method.params,
method.ret.1.as_ref(),
)?,
false,
false,
)
} else {
let class_tparam_names = class
.tparams
.iter()
.map(|tp| (tp.name).1.as_str())
.collect::<Vec<_>>();
let mut flags = emit_body::Flags::empty();
flags.set(
emit_body::Flags::SKIP_AWAITABLE,
method.fun_kind.is_fasync(),
);
flags.set(emit_body::Flags::MEMOIZE, is_memoize);
flags.set(emit_body::Flags::CLOSURE_BODY, is_closure_body);
flags.set(emit_body::Flags::NATIVE, is_native);
flags.set(emit_body::Flags::ASYNC, is_async);
flags.set(
emit_body::Flags::HAS_COEFFECTS_LOCAL,
coeffects.has_coeffects_local(),
);
emit_body::emit_body(
emitter.alloc,
emitter,
namespace,
ast_body_block,
instr::null(),
scope,
emit_body::Args {
immediate_tparams: &method.tparams,
class_tparam_names: class_tparam_names.as_slice(),
ast_params: &method.params,
ret: method.ret.1.as_ref(),
pos: &method.span,
deprecation_info: &deprecation_info,
doc_comment: method.doc_comment.clone(),
default_dropthrough,
call_context,
flags,
},
)?
};
let name = {
if is_memoize {
hhbc::MethodName::from_ast_name_and_suffix(
emitter.alloc,
&method.name.1,
emit_memoize_helpers::MEMOIZE_SUFFIX,
)
} else {
hhbc::MethodName::from_ast_name(emitter.alloc, &method.name.1)
}
};
let span = if is_native_opcode_impl {
Span::default()
} else {
Span::from_pos(&method.span)
};
let mut flags = MethodFlags::empty();
flags.set(MethodFlags::IS_ASYNC, is_async);
flags.set(MethodFlags::IS_GENERATOR, is_generator);
flags.set(MethodFlags::IS_PAIR_GENERATOR, is_pair_generator);
flags.set(MethodFlags::IS_CLOSURE_BODY, is_closure_body);
let has_variadic = emit_param::has_variadic(&body.params);
let attrs = get_attrs_for_method(
emitter,
method,
&attributes,
&visibility,
class,
is_memoize,
has_variadic,
);
Ok(Method {
attributes: Slice::fill_iter(emitter.alloc, attributes.into_iter()),
visibility: Visibility::from(visibility),
name,
body,
span,
coeffects,
flags,
attrs,
})
} |
Rust | hhvm/hphp/hack/src/hackc/emitter/emit_module.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use env::emitter::Emitter;
use error::Result;
use ffi::Maybe;
use ffi::Slice;
use ffi::Str;
use hhbc::ClassName;
use hhbc::Module;
use hhbc::Rule;
use hhbc::RuleKind;
use hhbc::Span;
use oxidized::ast;
use crate::emit_attribute;
fn emit_rule<'arena>(alloc: &'arena bumpalo::Bump, rule: &ast::MdNameKind) -> Rule<'arena> {
match rule {
ast::MdNameKind::MDNameGlobal(_) => Rule {
kind: RuleKind::Global,
name: Maybe::Nothing,
},
ast::MdNameKind::MDNamePrefix(id) => Rule {
kind: RuleKind::Prefix,
name: Maybe::Just(Str::new_str(alloc, &id.1)),
},
ast::MdNameKind::MDNameExact(id) => Rule {
kind: RuleKind::Exact,
name: Maybe::Just(Str::new_str(alloc, &id.1)),
},
}
}
pub fn emit_module<'a, 'arena, 'decl>(
alloc: &'arena bumpalo::Bump,
emitter: &mut Emitter<'arena, 'decl>,
ast_module: &'a ast::ModuleDef,
) -> Result<Module<'arena>> {
let attributes = emit_attribute::from_asts(emitter, &ast_module.user_attributes)?;
let name = ClassName::from_ast_name_and_mangle(alloc, &ast_module.name.1);
let span = Span::from_pos(&ast_module.span);
let doc_comment = ast_module.doc_comment.clone();
Ok(Module {
attributes: Slice::fill_iter(alloc, attributes.into_iter()),
name,
span,
doc_comment: Maybe::from(doc_comment.map(|c| Str::new_str(alloc, &c.1))),
exports: Maybe::from(
ast_module
.exports
.as_ref()
.map(|v| Slice::fill_iter(alloc, v.iter().map(|r| emit_rule(alloc, r)))),
),
imports: Maybe::from(
ast_module
.imports
.as_ref()
.map(|v| Slice::fill_iter(alloc, v.iter().map(|r| emit_rule(alloc, r)))),
),
})
}
pub fn emit_modules_from_program<'a, 'arena, 'decl>(
alloc: &'arena bumpalo::Bump,
emitter: &mut Emitter<'arena, 'decl>,
ast: &'a [ast::Def],
) -> Result<Vec<Module<'arena>>> {
ast.iter()
.filter_map(|def| {
if let ast::Def::Module(md) = def {
Some(emit_module(alloc, emitter, md))
} else {
None
}
})
.collect()
}
pub fn emit_module_use_from_program<'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
prog: &[ast::Def],
) -> Maybe<Str<'arena>> {
for node in prog.iter() {
if let ast::Def::SetModule(s) = node {
return Maybe::Just(Str::new_str(e.alloc, &s.1));
}
}
Maybe::Nothing
} |
Rust | hhvm/hphp/hack/src/hackc/emitter/emit_native_opcode.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use ast_scope::Scope;
use env::emitter::Emitter;
use error::Error;
use error::Result;
use ffi::Maybe::Just;
use ffi::Slice;
use hhbc::Body;
use hhbc::Local;
use instruction_sequence::instr;
use instruction_sequence::InstrSeq;
use oxidized::aast;
use oxidized::ast;
use oxidized::pos::Pos;
use crate::emit_body;
use crate::emit_param;
pub fn emit_body<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
scope: &Scope<'a, 'arena>,
class_attrs: &[ast::UserAttribute],
name: &ast::Sid,
params: &[ast::FunParam],
ret: Option<&aast::Hint>,
) -> Result<Body<'arena>> {
let body_instrs = emit_native_opcode_impl(&name.1, params, class_attrs);
let mut tparams = scope
.get_tparams()
.iter()
.map(|tp| tp.name.1.as_str())
.collect::<Vec<_>>();
let params = emit_param::from_asts(emitter, &mut tparams, false, scope, params);
let return_type_info =
emit_body::emit_return_type_info(emitter.alloc, tparams.as_slice(), false, ret);
body_instrs.and_then(|body_instrs| {
params.and_then(|params| {
return_type_info.and_then(|rti| {
let body_instrs =
Slice::from_vec(emitter.alloc, body_instrs.iter().cloned().collect());
let params = Slice::fill_iter(emitter.alloc, params.into_iter().map(|p| p.0));
let stack_depth =
stack_depth::compute_stack_depth(params.as_ref(), body_instrs.as_ref())
.map_err(error::Error::from_error)?;
Ok(Body {
body_instrs,
params,
return_type_info: Just(rti),
decl_vars: Default::default(),
doc_comment: Default::default(),
is_memoize_wrapper: Default::default(),
is_memoize_wrapper_lsb: Default::default(),
num_iters: Default::default(),
shadowed_tparams: Default::default(),
stack_depth,
upper_bounds: Default::default(),
})
})
})
})
}
fn emit_native_opcode_impl<'arena>(
name: &str,
params: &[ast::FunParam],
user_attrs: &[ast::UserAttribute],
) -> Result<InstrSeq<'arena>> {
if let [ua] = user_attrs {
if ua.name.1 == "__NativeData" {
if let [p] = ua.params.as_slice() {
match p.2.as_string() {
Some(s) if s == "HH\\AsyncGenerator" || s == "Generator" => {
return emit_generator_method(name, params);
}
_ => {}
}
};
}
};
Err(Error::fatal_runtime(
&Pos::NONE,
format!("OpCodeImpl attribute is not applicable to {}", name),
))
}
fn emit_generator_method<'arena>(name: &str, params: &[ast::FunParam]) -> Result<InstrSeq<'arena>> {
let instrs = match name {
"send" => {
let local = get_first_param_local(params)?;
InstrSeq::gather(vec![
instr::cont_check_check(),
instr::push_l(local),
instr::cont_enter(),
])
}
"raise" | "throw" => {
let local = get_first_param_local(params)?;
InstrSeq::gather(vec![
instr::cont_check_check(),
instr::push_l(local),
instr::cont_raise(),
])
}
"next" | "rewind" => InstrSeq::gather(vec![
instr::cont_check_ignore(),
instr::null(),
instr::cont_enter(),
]),
"valid" => instr::cont_valid(),
"current" => instr::cont_current(),
"key" => instr::cont_key(),
"getReturn" => instr::cont_get_return(),
_ => {
return Err(Error::fatal_runtime(
&Pos::NONE,
"incorrect native generator function",
));
}
};
Ok(InstrSeq::gather(vec![instrs, instr::ret_c()]))
}
fn get_first_param_local(params: &[ast::FunParam]) -> Result<Local> {
match params {
[_, ..] => Ok(Local::new(0)),
_ => Err(Error::unrecoverable("native generator requires params")),
}
} |
Rust | hhvm/hphp/hack/src/hackc/emitter/emit_param.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::marker::PhantomData;
use ast_scope::Scope;
use emit_type_hint::hint_to_type_info;
use emit_type_hint::Kind;
use env::emitter::Emitter;
use env::Env;
use error::Error;
use error::Result;
use ffi::Maybe;
use ffi::Nothing;
use ffi::Slice;
use ffi::Str;
use hhbc::Label;
use hhbc::Local;
use hhbc::Param;
use hhbc::TypeInfo;
use hhbc_string_utils::locals::strip_dollar;
use instruction_sequence::instr;
use instruction_sequence::InstrSeq;
use oxidized::aast_defs::Hint;
use oxidized::aast_defs::Hint_;
use oxidized::aast_visitor;
use oxidized::aast_visitor::AstParams;
use oxidized::aast_visitor::Node;
use oxidized::ast as a;
use oxidized::ast_defs::Id;
use oxidized::ast_defs::ReadonlyKind;
use oxidized::pos::Pos;
use crate::emit_attribute;
use crate::emit_expression;
pub fn has_variadic(params: &[Param<'_>]) -> bool {
params.iter().any(|v| v.is_variadic)
}
pub fn from_asts<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
tparams: &mut Vec<&str>,
generate_defaults: bool,
scope: &Scope<'a, 'arena>,
ast_params: &[a::FunParam],
) -> Result<Vec<(Param<'arena>, Option<(Label, a::Expr)>)>> {
ast_params
.iter()
.map(|param| from_ast(emitter, tparams, generate_defaults, scope, param))
.collect::<Result<Vec<_>>>()
.map(|params| {
params
.iter()
.filter_map(|p| p.to_owned())
.collect::<Vec<_>>()
})
.map(|params| rename_params(emitter.alloc, params))
}
fn rename_params<'arena>(
alloc: &'arena bumpalo::Bump,
mut params: Vec<(Param<'arena>, Option<(Label, a::Expr)>)>,
) -> Vec<(Param<'arena>, Option<(Label, a::Expr)>)> {
fn rename<'arena>(
alloc: &'arena bumpalo::Bump,
names: &BTreeSet<Str<'arena>>,
param_counts: &mut BTreeMap<Str<'arena>, usize>,
param: &mut Param<'arena>,
) {
match param_counts.get_mut(¶m.name) {
None => {
param_counts.insert(param.name, 0);
}
Some(count) => {
let newname =
Str::new_str(alloc, &format!("{}{}", param.name.unsafe_as_str(), count));
*count += 1;
if names.contains(&newname) {
rename(alloc, names, param_counts, param);
} else {
param.name = newname;
}
}
}
}
let mut param_counts = BTreeMap::new();
let names = params
.iter()
.map(|(p, _)| p.name.clone())
.collect::<BTreeSet<_>>();
params
.iter_mut()
.rev()
.for_each(|(p, _)| rename(alloc, &names, &mut param_counts, p));
params.into_iter().collect()
}
fn from_ast<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
tparams: &mut Vec<&str>,
generate_defaults: bool,
scope: &Scope<'a, 'arena>,
param: &a::FunParam,
) -> Result<Option<(Param<'arena>, Option<(Label, a::Expr)>)>> {
if param.is_variadic && param.name == "..." {
return Ok(None);
};
if param.is_variadic {
tparams.push("array");
};
let type_info = {
let param_type_hint = if param.is_variadic {
Some(Hint(
Pos::NONE,
Box::new(Hint_::mk_happly(
Id(Pos::NONE, "array".to_string()),
param
.type_hint
.get_hint()
.as_ref()
.map_or(vec![], |h| vec![h.clone()]),
)),
))
} else {
param.type_hint.get_hint().clone()
};
if let Some(h) = param_type_hint {
Some(hint_to_type_info(
emitter.alloc,
&Kind::Param,
false,
false, /* meaning only set nullable based on given hint */
&tparams[..],
&h,
)?)
} else {
None
}
};
// Do the type check for default value type and hint type
if let Some(err_msg) = default_type_check(¶m.name, type_info.as_ref(), param.expr.as_ref())
{
return Err(Error::fatal_parse(¶m.pos, err_msg));
}
aast_visitor::visit(
&mut ResolverVisitor {
phantom_a: PhantomData,
phantom_b: PhantomData,
phantom_c: PhantomData,
},
&mut Ctx { emitter, scope },
¶m.expr,
)
.unwrap();
let default_value = if generate_defaults {
param
.expr
.as_ref()
.map(|expr| (emitter.label_gen_mut().next_regular(), expr.clone()))
} else {
None
};
let is_readonly = match param.readonly {
Some(ReadonlyKind::Readonly) => true,
_ => false,
};
let attrs = emit_attribute::from_asts(emitter, ¶m.user_attributes)?;
Ok(Some((
Param {
name: Str::new_str(emitter.alloc, ¶m.name),
is_variadic: param.is_variadic,
is_inout: param.callconv.is_pinout(),
is_readonly,
user_attributes: Slice::new(emitter.alloc.alloc_slice_fill_iter(attrs.into_iter())),
type_info: Maybe::from(type_info),
// - Write hhas_param.default_value as `Nothing` while keeping `default_value` around
// for emitting decl vars and default value setters
// - emit_body::make_body will rewrite hhas_param.default_value using `default_value`
default_value: Nothing,
},
default_value,
)))
}
pub fn emit_param_default_value_setter<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
env: &Env<'a, 'arena>,
pos: &Pos,
params: &[(Param<'arena>, Option<(Label, a::Expr)>)],
) -> Result<(InstrSeq<'arena>, InstrSeq<'arena>)> {
let setters = params
.iter()
.enumerate()
.filter_map(|(i, (_, dv))| {
// LocalIds for params are numbered from 0.
dv.as_ref().map(|(lbl, expr)| {
let param_local = Local::new(i);
let instrs = InstrSeq::gather(vec![
emit_expression::emit_expr(emitter, env, expr)?,
emit_pos::emit_pos(pos),
instr::verify_param_type(param_local),
instr::set_l(param_local),
instr::pop_c(),
]);
Ok(InstrSeq::gather(vec![instr::label(lbl.to_owned()), instrs]))
})
})
.collect::<Result<Vec<_>>>()?;
if setters.is_empty() {
Ok((instr::empty(), instr::empty()))
} else {
let l = emitter.label_gen_mut().next_regular();
Ok((
instr::label(l),
InstrSeq::gather(vec![InstrSeq::gather(setters), instr::enter(l)]),
))
}
}
struct ResolverVisitor<'a, 'arena: 'a, 'decl: 'a> {
phantom_a: PhantomData<&'a ()>,
phantom_b: PhantomData<&'arena ()>,
phantom_c: PhantomData<&'decl ()>,
}
#[allow(dead_code)]
struct Ctx<'a, 'arena, 'decl> {
emitter: &'a mut Emitter<'arena, 'decl>,
scope: &'a Scope<'a, 'arena>,
}
impl<'ast, 'a, 'arena, 'decl> aast_visitor::Visitor<'ast> for ResolverVisitor<'a, 'arena, 'decl> {
type Params = AstParams<Ctx<'a, 'arena, 'decl>, ()>;
fn object(&mut self) -> &mut dyn aast_visitor::Visitor<'ast, Params = Self::Params> {
self
}
fn visit_expr(&mut self, c: &mut Ctx<'a, 'arena, 'decl>, p: &a::Expr) -> Result<(), ()> {
p.recurse(c, self.object())
// TODO(hrust) implement on_CIexpr & remove dead_code on struct Ctx
}
}
// Return None if it passes type check, otherwise return error msg
fn default_type_check<'arena>(
param_name: &str,
param_type_info: Option<&TypeInfo<'arena>>,
param_expr: Option<&a::Expr>,
) -> Option<String> {
let hint_type = get_hint_display_name(
param_type_info
.as_ref()
.and_then(|ti| ti.user_type.as_ref().into()),
);
// If matches, return None, otherwise return default_type
let default_type = hint_type.and_then(|ht| match_default_and_hint(ht, param_expr));
let param_true_name = strip_dollar(param_name);
default_type.and_then(|dt| hint_type.map(|ht| match ht {
"class" => format!(
"Default value for parameter {} with a class type hint can only be NULL",
param_true_name),
_ => format!(
"Default value for parameter {} with type {} needs to have the same type as the type hint {}",
param_true_name,
dt,
ht)
}))
}
fn get_hint_display_name<'arena>(hint: Option<&Str<'arena>>) -> Option<&'static str> {
hint.map(|h| match h.unsafe_as_str() {
"HH\\bool" => "bool",
"HH\\varray" => "HH\\varray",
"HH\\darray" => "HH\\darray",
"HH\\varray_or_darray" => "HH\\varray_or_darray",
"HH\\vec_or_dict" => "HH\\vec_or_dict",
"HH\\AnyArray" => "HH\\AnyArray",
"HH\\int" => "int",
"HH\\num" => "num",
"HH\\arraykey" => "arraykey",
"HH\\float" => "float",
"HH\\string" => "string",
_ => "class",
})
}
// By now only check default type for bool, array, int, float and string.
// Return None when hint_type and default_value matches (in hh mode,
// "class" type matches anything). If not, return default_value type string
// for printing fatal parse error
fn match_default_and_hint(hint_type: &str, param_expr: Option<&a::Expr>) -> Option<&'static str> {
if hint_type == "class" {
return None;
}
match ¶m_expr.as_ref() {
None => None,
Some(e) => match e.2 {
a::Expr_::True | a::Expr_::False => match hint_type {
"bool" => None,
_ => Some("Boolean"),
},
a::Expr_::Int(_) => match hint_type {
"int" | "num" | "arraykey" | "float" => None,
_ => Some("Int64"),
},
a::Expr_::Float(_) => match hint_type {
"float" | "num" => None,
_ => Some("Double"),
},
a::Expr_::String(_) => match hint_type {
"string" | "arraykey" => None,
_ => Some("String"),
},
_ => None,
},
}
} |
Rust | hhvm/hphp/hack/src/hackc/emitter/emit_pos.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use instruction_sequence::instr;
use instruction_sequence::InstrSeq;
use oxidized::pos::Pos;
pub fn emit_pos<'a>(pos: &Pos) -> InstrSeq<'a> {
if !pos.is_none() {
let (line_begin, line_end, col_begin, col_end) = pos.info_pos_extended();
instr::srcloc(
line_begin.try_into().unwrap(),
line_end.try_into().unwrap(),
col_begin.try_into().unwrap(),
col_end.try_into().unwrap(),
)
} else {
instr::empty()
}
}
pub fn emit_pos_then<'a>(pos: &Pos, instrs: InstrSeq<'a>) -> InstrSeq<'a> {
InstrSeq::gather(vec![emit_pos(pos), instrs])
} |
Rust | hhvm/hphp/hack/src/hackc/emitter/emit_property.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use env::emitter::Emitter;
use env::Env;
use error::Error;
use error::Result;
use ffi::Maybe::*;
use hhbc::Constraint;
use hhbc::InitPropOp;
use hhbc::Property;
use hhbc::TypeInfo;
use hhbc::TypedValue;
use hhbc::Visibility;
use hhbc_string_utils as string_utils;
use hhvm_types_ffi::ffi::Attr;
use instruction_sequence::instr;
use instruction_sequence::InstrSeq;
use naming_special_names_rust::pseudo_consts;
use naming_special_names_rust::user_attributes as ua;
use oxidized::aast_defs;
use oxidized::ast;
use oxidized::ast_defs;
use crate::emit_attribute;
use crate::emit_expression;
pub struct FromAstArgs<'ast> {
pub user_attributes: &'ast [ast::UserAttribute],
pub id: &'ast ast::Sid,
pub initial_value: &'ast Option<ast::Expr>,
pub typehint: Option<&'ast aast_defs::Hint>,
pub doc_comment: Option<aast_defs::DocComment>,
pub visibility: aast_defs::Visibility,
pub is_static: bool,
pub is_abstract: bool,
pub is_readonly: bool,
}
/// A Property and its initializer instructions
#[derive(Debug)]
pub struct PropAndInit<'a> {
pub prop: Property<'a>,
pub init: Option<InstrSeq<'a>>,
}
pub fn from_ast<'ast, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
class: &'ast ast::Class_,
tparams: &[&str],
class_is_const: bool,
class_is_closure: bool,
args: FromAstArgs<'_>,
) -> Result<PropAndInit<'arena>> {
let alloc = emitter.alloc;
let ast_defs::Id(pos, cv_name) = args.id;
let pid = hhbc::PropName::from_ast_name(alloc, cv_name);
let attributes = emit_attribute::from_asts(emitter, args.user_attributes)?;
let is_const = (!args.is_static && class_is_const)
|| attributes
.iter()
.any(|a| a.name.unsafe_as_str() == ua::CONST);
let is_lsb = attributes.iter().any(|a| a.name.unsafe_as_str() == ua::LSB);
let is_late_init = attributes
.iter()
.any(|a| a.name.unsafe_as_str() == ua::LATE_INIT);
let is_cabstract = match class.kind {
ast_defs::ClassishKind::Cclass(k) => k.is_abstract(),
_ => false,
};
if !args.is_static && class.final_ && is_cabstract {
return Err(Error::fatal_parse(
pos,
format!(
"Class {} contains non-static property declaration and therefore cannot be declared 'abstract final'",
string_utils::strip_global_ns(&class.name.1),
),
));
};
let type_info = match args.typehint.as_ref() {
None => TypeInfo::make_empty(),
Some(th) => emit_type_hint::hint_to_type_info(
alloc,
&emit_type_hint::Kind::Property,
false,
false,
tparams,
th,
)?,
};
if !(valid_for_prop(&type_info.type_constraint)) {
return Err(Error::fatal_parse(
pos,
format!(
"Invalid property type hint for '{}::${}'",
string_utils::strip_global_ns(&class.name.1),
pid.unsafe_as_str()
),
));
};
let env = Env::make_class_env(alloc, class);
let (initial_value, initializer_instrs, mut hhas_property_flags) = match args.initial_value {
None => {
let initial_value = if is_late_init || class_is_closure {
Some(TypedValue::Uninit)
} else {
None
};
(initial_value, None, Attr::AttrSystemInitialValue)
}
Some(_) if is_late_init => {
return Err(Error::fatal_parse(
pos,
format!(
"<<__LateInit>> property '{}::${}' cannot have an initial value",
string_utils::strip_global_ns(&class.name.1),
pid.unsafe_as_str()
),
));
}
Some(e) => {
let is_collection_map = match e.2.as_collection() {
Some(c) if (c.0).1 == "Map" || (c.0).1 == "ImmMap" => true,
_ => false,
};
let deep_init = !args.is_static && expr_requires_deep_init(e, true);
match constant_folder::expr_to_typed_value(emitter, e) {
Ok(tv) if !(deep_init || is_collection_map) => (Some(tv), None, Attr::AttrNone),
_ => {
let label = emitter.label_gen_mut().next_regular();
let (prolog, epilog) = if args.is_static {
(
instr::empty(),
emit_pos::emit_pos_then(
&class.span,
instr::init_prop(pid, InitPropOp::Static),
),
)
} else if args.visibility.is_private() {
(
instr::empty(),
emit_pos::emit_pos_then(
&class.span,
instr::init_prop(pid, InitPropOp::NonStatic),
),
)
} else {
(
InstrSeq::gather(vec![
emit_pos::emit_pos(&class.span),
instr::check_prop(pid),
instr::jmp_nz(label),
]),
InstrSeq::gather(vec![
emit_pos::emit_pos(&class.span),
instr::init_prop(pid, InitPropOp::NonStatic),
instr::label(label),
]),
)
};
let mut flags = Attr::AttrNone;
flags.set(Attr::AttrDeepInit, deep_init);
(
Some(TypedValue::Uninit),
Some(InstrSeq::gather(vec![
prolog,
emit_expression::emit_expr(emitter, &env, e)?,
epilog,
])),
flags,
)
}
}
}
};
hhas_property_flags.set(Attr::AttrAbstract, args.is_abstract);
hhas_property_flags.set(Attr::AttrStatic, args.is_static);
hhas_property_flags.set(Attr::AttrLSB, is_lsb);
hhas_property_flags.set(Attr::AttrIsConst, is_const);
hhas_property_flags.set(Attr::AttrLateInit, is_late_init);
hhas_property_flags.set(Attr::AttrIsReadonly, args.is_readonly);
hhas_property_flags.add(Attr::from(args.visibility));
let prop = Property {
name: pid,
attributes: alloc.alloc_slice_fill_iter(attributes.into_iter()).into(),
type_info,
initial_value: initial_value.into(),
flags: hhas_property_flags,
visibility: Visibility::from(args.visibility),
doc_comment: args
.doc_comment
.map(|pstr| ffi::Str::from(alloc.alloc_str(&pstr.1)))
.into(),
};
Ok(PropAndInit {
prop,
init: initializer_instrs,
})
}
fn valid_for_prop(tc: &Constraint<'_>) -> bool {
match &tc.name {
Nothing => true,
Just(s) => {
!(s.unsafe_as_str().eq_ignore_ascii_case("hh\\nothing")
|| s.unsafe_as_str().eq_ignore_ascii_case("hh\\noreturn")
|| s.unsafe_as_str().eq_ignore_ascii_case("callable"))
}
}
}
fn expr_requires_deep_init_(expr: &ast::Expr) -> bool {
expr_requires_deep_init(expr, false)
}
fn expr_requires_deep_init(ast::Expr(_, _, expr): &ast::Expr, force_class_init: bool) -> bool {
use ast::Expr_;
use ast_defs::Uop;
match expr {
Expr_::Unop(e) if e.0 == Uop::Uplus || e.0 == Uop::Uminus => expr_requires_deep_init_(&e.1),
Expr_::Binop(e) => expr_requires_deep_init_(&e.lhs) || expr_requires_deep_init_(&e.rhs),
Expr_::Lvar(_)
| Expr_::Null
| Expr_::False
| Expr_::True
| Expr_::Int(_)
| Expr_::Float(_)
| Expr_::String(_) => false,
Expr_::ValCollection(e) if e.0.1 == ast::VcKind::Vec || e.0.1 == ast::VcKind::Keyset => {
(e.2).iter().any(expr_requires_deep_init_)
}
Expr_::KeyValCollection(e) if e.0.1 == ast::KvcKind::Dict => (e.2)
.iter()
.any(|f| expr_requires_deep_init_(&f.0) || expr_requires_deep_init_(&f.1)),
Expr_::Varray(e) => (e.1).iter().any(expr_requires_deep_init_),
Expr_::Darray(e) => (e.1).iter().any(expr_pair_requires_deep_init),
Expr_::Id(e) if e.1 == pseudo_consts::G__FILE__ || e.1 == pseudo_consts::G__DIR__ => false,
Expr_::Shape(sfs) => sfs.iter().any(shape_field_requires_deep_init),
Expr_::ClassConst(e) if (!force_class_init) => match e.0.as_ciexpr() {
Some(ci_expr) => match (ci_expr.2).as_id() {
Some(ast_defs::Id(_, s)) => {
class_const_requires_deep_init(s.as_str(), (e.1).1.as_str())
}
_ => true,
},
None => true,
},
Expr_::Upcast(e) => expr_requires_deep_init_(&e.0),
_ => true,
}
}
fn expr_pair_requires_deep_init((e1, e2): &(ast::Expr, ast::Expr)) -> bool {
expr_requires_deep_init_(e1) || expr_requires_deep_init_(e2)
}
fn shape_field_requires_deep_init((name, expr): &(ast_defs::ShapeFieldName, ast::Expr)) -> bool {
match name {
ast_defs::ShapeFieldName::SFlitInt(_) | ast_defs::ShapeFieldName::SFlitStr(_) => {
expr_requires_deep_init_(expr)
}
ast_defs::ShapeFieldName::SFclassConst(ast_defs::Id(_, s), (_, p)) => {
class_const_requires_deep_init(s, p)
}
}
}
fn class_const_requires_deep_init(s: &str, p: &str) -> bool {
!string_utils::is_class(p)
|| string_utils::is_self(s)
|| string_utils::is_parent(s)
|| string_utils::is_static(s)
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.