1 // Copyright (c) Facebook, Inc. and its affiliates.
3 // This source code is licensed under the MIT license found in the
4 // LICENSE file in the "hack" directory of this source tree.
6 mod special_class_resolver;
9 pub use context::Context;
10 pub use write::{Error, IoWrite, Result, Write};
13 Maybe::{Just, Nothing},
17 use indexmap::IndexSet;
18 use itertools::Itertools;
20 use core_utils_rust::add_ns;
21 use escaper::{escape, escape_by, is_lit_printable};
22 use hhbc_by_ref_emit_type_hint as emit_type_hint;
23 use hhbc_by_ref_hhas_adata::{HhasAdata, DICT_PREFIX, KEYSET_PREFIX, VEC_PREFIX};
24 use hhbc_by_ref_hhas_attribute::{self as hhas_attribute, HhasAttribute};
25 use hhbc_by_ref_hhas_body::{HhasBody, HhasBodyEnv};
26 use hhbc_by_ref_hhas_class::{self as hhas_class, HhasClass};
27 use hhbc_by_ref_hhas_coeffects::{HhasCoeffects, HhasCtxConstant};
28 use hhbc_by_ref_hhas_constant::HhasConstant;
29 use hhbc_by_ref_hhas_function::HhasFunction;
30 use hhbc_by_ref_hhas_method::{HhasMethod, HhasMethodFlags};
31 use hhbc_by_ref_hhas_param::HhasParam;
32 use hhbc_by_ref_hhas_pos::Span;
33 use hhbc_by_ref_hhas_program::HhasProgram;
34 use hhbc_by_ref_hhas_property::HhasProperty;
35 use hhbc_by_ref_hhas_record_def::{Field, HhasRecord};
36 use hhbc_by_ref_hhas_symbol_refs::{HhasSymbolRefs, IncludePath};
37 use hhbc_by_ref_hhas_type::{constraint, Info as HhasTypeInfo};
38 use hhbc_by_ref_hhas_type_const::HhasTypeConstant;
39 use hhbc_by_ref_hhas_typedef::Typedef as HhasTypedef;
40 use hhbc_by_ref_hhbc_ast::*;
41 use hhbc_by_ref_hhbc_id::{class, Id};
42 use hhbc_by_ref_hhbc_string_utils::{
43 float, integer, is_class, is_parent, is_self, is_static, is_xhp, lstrip, mangle, quote_string,
44 quote_string_with_escape, strip_global_ns, strip_ns, triple_quote_string, types,
46 use hhbc_by_ref_instruction_sequence::{Error::Unrecoverable, InstrSeq};
47 use hhbc_by_ref_iterator::Id as IterId;
48 use hhbc_by_ref_label::Label;
49 use hhbc_by_ref_local::Local;
50 use hhbc_by_ref_runtime::TypedValue;
51 use lazy_static::lazy_static;
52 use naming_special_names_rust::classes;
53 use ocaml_helper::escaped;
54 use oxidized::{ast, ast_defs, doc_comment::DocComment, local_id};
58 use std::{borrow::Cow, io::Write as _, path::Path, write};
61 pub codegen_env: Option<&'e HhasBodyEnv>,
64 pub fn print_program<W: Write>(
68 ) -> Result<(), W::Error> {
71 let abs = p.to_absolute();
72 let p = escape(abs.to_str().ok_or(Error::InvalidUTF8)?);
74 concat_str_by(w, " ", ["#", p.as_ref(), "starts here"])?;
79 concat_str(w, [".filepath ", format!("\"{}\"", p).as_str(), ";"])?;
82 handle_not_impl(|| print_program_(ctx, w, prog))?;
85 concat_str_by(w, " ", ["#", p.as_ref(), "ends here"])?;
90 w.write("#starts here")?;
93 handle_not_impl(|| print_program_(ctx, w, prog))?;
96 w.write("#ends here")?;
103 fn get_fatal_op(f: &FatalOp) -> &str {
105 FatalOp::Parse => "Parse",
106 FatalOp::Runtime => "Runtime",
107 FatalOp::RuntimeOmitFrame => "RuntimeOmitFrame",
111 fn print_program_<W: Write>(
115 ) -> Result<(), W::Error> {
116 if let Some((fop, p, msg)) = &prog.fatal {
118 let (line_begin, line_end, col_begin, col_end) = if p.is_none() || !p.is_valid() {
121 p.info_pos_extended()
123 let pos = format!("{}:{},{}:{}", line_begin, col_begin, line_end, col_end);
132 escape(msg).as_ref(),
139 concat(w, &prog.adata, |w, a| print_adata_region(ctx, w, a))?;
140 concat(w, &prog.functions, |w, f| print_fun_def(ctx, w, f))?;
141 concat(w, &prog.classes, |w, cd| print_class_def(ctx, w, cd))?;
142 concat(w, &prog.record_defs, |w, rd| print_record_def(ctx, w, rd))?;
143 concat(w, &prog.constants, |w, c| print_constant(ctx, w, c))?;
144 concat(w, &prog.typedefs, |w, td| print_typedef(ctx, w, td))?;
145 print_file_attributes(ctx, w, prog.file_attributes.as_ref())?;
147 if ctx.dump_symbol_refs() {
148 print_include_region(ctx, w, &prog.symbol_refs.includes)?;
149 print_symbol_ref_regions(ctx, w, &prog.symbol_refs)?;
154 fn print_include_region<W: Write>(
157 includes: &Slice<IncludePath>,
158 ) -> Result<(), W::Error> {
159 fn print_path<W: Write>(w: &mut W, p: &Path) -> Result<(), W::Error> {
160 option(w, p.to_str(), |w, p: &str| write!(w, "\n {}", p))
162 fn print_if_exists<W: Write>(w: &mut W, p: &Path) -> Result<(), W::Error> {
163 if p.exists() { print_path(w, p) } else { Ok(()) }
165 fn print_include<W: Write>(
169 ) -> Result<(), W::Error> {
170 let include_roots = ctx.include_roots;
171 let alloc = bumpalo::Bump::new();
172 match inc.into_doc_root_relative(&alloc, include_roots) {
173 IncludePath::Absolute(p) => print_if_exists(w, Path::new(&p.as_str())),
174 IncludePath::SearchPathRelative(p) => {
175 let path_from_cur_dirname = ctx
177 .and_then(|p| p.path().parent())
178 .unwrap_or_else(|| Path::new(""))
180 if path_from_cur_dirname.exists() {
181 print_path(w, &path_from_cur_dirname)
183 let search_paths = ctx.include_search_paths;
184 for prefix in search_paths.iter() {
185 let path = Path::new(prefix).join(&p.as_str());
187 return print_path(w, &path);
193 IncludePath::IncludeRootRelative(v, p) => {
196 .get(&v.as_str().to_owned())
199 let doc_root = ctx.doc_root;
200 let resolved = Path::new(doc_root).join(ir).join(&p.as_str());
201 print_if_exists(w, &resolved)
206 IncludePath::DocRootRelative(p) => {
207 let doc_root = ctx.doc_root;
208 let resolved = Path::new(doc_root).join(&p.as_str());
209 print_if_exists(w, &resolved)
213 if !includes.is_empty() {
214 w.write("\n.includes {")?;
215 for inc in includes.as_ref().iter() {
216 // TODO(hrust): avoid clone. Rethink onwership of inc in
217 // hhas_symbol_refs_rust::IncludePath::into_doc_root_relative
218 print_include(ctx, w, inc.clone())?;
226 fn print_symbol_ref_regions<'arena, W: Write>(
229 symbol_refs: &HhasSymbolRefs<'arena>,
230 ) -> Result<(), W::Error> {
231 let mut print_region = |name, refs: &Slice<'arena, Str<'arena>>| {
232 if !refs.is_empty() {
234 write!(w, ".{} {{", name)?;
235 ctx.block(w, |c, w| {
236 for s in refs.as_ref().iter() {
247 print_region("constant_refs", &symbol_refs.constants)?;
248 print_region("function_refs", &symbol_refs.functions)?;
249 print_region("class_refs", &symbol_refs.classes)
252 fn print_adata_region<W: Write>(
256 ) -> Result<(), W::Error> {
257 concat_str_by(w, " ", [".adata", adata.id.as_str(), "= "])?;
258 triple_quotes(w, |w| print_adata(ctx, w, &adata.value))?;
263 fn print_typedef<W: Write>(ctx: &mut Context, w: &mut W, td: &HhasTypedef) -> Result<(), W::Error> {
266 print_typedef_attributes(ctx, w, td)?;
267 w.write(td.name.to_raw_string())?;
269 print_typedef_info(w, &td.type_info)?;
271 print_span(w, &td.span)?;
273 triple_quotes(w, |w| print_adata(ctx, w, &td.type_structure))?;
277 fn print_typedef_attributes<W: Write>(
281 ) -> Result<(), W::Error> {
282 let mut specials = vec![];
283 if ctx.is_system_lib() {
284 specials.push("persistent");
286 print_special_and_user_attrs(ctx, w, &specials[..], td.attributes.as_ref())
289 fn handle_not_impl<E: std::fmt::Debug, F: FnOnce() -> Result<(), E>>(f: F) -> Result<(), E> {
292 Err(Error::NotImpl(msg)) => {
293 println!("#### NotImpl: {}", msg);
294 eprintln!("NotImpl: {}", msg);
301 fn print_fun_def<W: Write>(
304 fun_def: &HhasFunction,
305 ) -> Result<(), W::Error> {
306 let body = &fun_def.body;
308 w.write(".function ")?;
309 print_upper_bounds(w, &body.upper_bounds)?;
311 print_fun_attrs(ctx, w, fun_def)?;
312 print_span(w, &fun_def.span)?;
314 option(w, &body.return_type_info, |w, ti| {
315 print_type_info(w, ti)?;
318 w.write(fun_def.name.to_raw_string())?;
319 print_params(ctx, w, fun_def.body.env.as_ref(), fun_def.params())?;
320 if fun_def.is_generator() {
321 w.write(" isGenerator")?;
323 if fun_def.is_async() {
324 w.write(" isAsync")?;
326 if fun_def.is_pair_generator() {
327 w.write(" isPairGenerator")?;
331 ctx.block(w, |c, w| print_body(c, w, body, &fun_def.coeffects))?;
338 fn print_requirement<W: Write>(
341 r: &(class::ClassType<'_>, hhas_class::TraitReqKind),
342 ) -> Result<(), W::Error> {
344 w.write(".require ")?;
346 (name, hhas_class::TraitReqKind::MustExtend) => {
347 write!(w, "extends <{}>;", name.to_raw_string())
349 (name, hhas_class::TraitReqKind::MustImplement) => {
350 write!(w, "implements <{}>;", name.to_raw_string())
355 fn print_type_constant<W: Write>(
358 c: &HhasTypeConstant,
359 ) -> Result<(), W::Error> {
361 concat_str_by(w, " ", [".const", &c.name, "isType"])?;
363 w.write(" isAbstract")?;
365 option(w, &c.initializer, |w, init| {
367 triple_quotes(w, |w| print_adata(ctx, w, init))
372 fn print_ctx_constant<W: Write>(
376 ) -> Result<(), W::Error> {
378 concat_str_by(w, " ", [".ctx", &c.name])?;
380 w.write(" isAbstract")?;
382 if let Some(coeffects) = HhasCoeffects::vec_to_string(&c.coeffects.0, |c| c.to_string()) {
386 if let Some(coeffects) = HhasCoeffects::vec_to_string(&c.coeffects.1, |c| c.to_string()) {
394 fn print_property_doc_comment<W: Write>(w: &mut W, p: &HhasProperty) -> Result<(), W::Error> {
395 if let Just(s) = p.doc_comment.as_ref() {
396 w.write(triple_quote_string(s.as_str()))?;
402 fn print_property_attributes<W: Write>(
405 property: &HhasProperty,
406 ) -> Result<(), W::Error> {
407 let mut special_attributes = vec![];
408 if property.is_late_init() {
409 special_attributes.push("late_init")
411 if property.is_no_bad_redeclare() {
412 special_attributes.push("no_bad_redeclare")
414 if property.initial_satisfies_tc() {
415 special_attributes.push("initial_satisfies_tc")
417 if property.no_implicit_null() {
418 special_attributes.push("no_implicit_null")
420 if property.has_system_initial() {
421 special_attributes.push("sys_initial_val")
423 if property.is_const() {
424 special_attributes.push("is_const")
426 if property.is_readonly() {
427 special_attributes.push("readonly")
429 if property.is_deep_init() {
430 special_attributes.push("deep_init")
432 if property.is_lsb() {
433 special_attributes.push("lsb")
435 if property.is_static() {
436 special_attributes.push("static")
438 special_attributes.push(property.visibility.as_ref());
439 special_attributes.reverse();
442 concat_by(w, " ", &special_attributes, |w, a| w.write(a))?;
443 if !special_attributes.is_empty() && !property.attributes.is_empty() {
446 print_attributes(ctx, w, &property.attributes)?;
450 fn print_property_type_info<W: Write>(w: &mut W, p: &HhasProperty) -> Result<(), W::Error> {
451 print_type_info(w, &p.type_info)?;
455 fn print_property<W: Write>(
458 class_def: &HhasClass,
459 property: &HhasProperty,
460 ) -> Result<(), W::Error> {
462 w.write(" .property ")?;
463 print_property_attributes(ctx, w, property)?;
464 print_property_doc_comment(w, property)?;
465 print_property_type_info(w, property)?;
466 w.write(property.name.to_raw_string())?;
468 let initial_value = property.initial_value.as_ref();
469 if class_def.is_closure() || initial_value == Just(&TypedValue::Uninit) {
472 triple_quotes(w, |w| match initial_value {
473 Nothing => w.write("N;"),
474 Just(value) => print_adata(ctx, w, &value),
480 fn print_constant<W: Write>(
484 ) -> Result<(), W::Error> {
487 w.write(c.name.to_raw_string())?;
489 w.write(" isAbstract")?;
491 match c.value.as_ref() {
492 Just(TypedValue::Uninit) => w.write(" = uninit")?,
495 triple_quotes(w, |w| print_adata(ctx, w, value))?;
502 fn print_enum_ty<W: Write>(ctx: &mut Context, w: &mut W, c: &HhasClass) -> Result<(), W::Error> {
503 if let Some(et) = c.enum_type.as_ref() {
505 w.write(".enum_ty ")?;
506 print_type_info_(w, true, et)?;
512 fn print_doc_comment<W: Write>(
515 doc_comment: &Option<DocComment>,
516 ) -> Result<(), W::Error> {
517 if let Some(cmt) = doc_comment {
519 write!(w, ".doc {};", triple_quote_string(&(cmt.0).1))?;
524 fn print_use_precedence<W: Write>(
527 (id1, id2, ids): &(class::ClassType, class::ClassType, Vec<class::ClassType>),
528 ) -> Result<(), W::Error> {
530 concat_str(w, [id1.to_raw_string(), "::", id2.to_raw_string()])?;
531 w.write(" insteadof ")?;
532 let unique_ids: IndexSet<&str> = ids.iter().map(|i| i.to_raw_string()).collect();
533 concat_str_by(w, " ", unique_ids.iter().collect::<Vec<_>>())?;
537 fn print_use_as_visibility<W: Write>(w: &mut W, u: ast::UseAsVisibility) -> Result<(), W::Error> {
539 ast::UseAsVisibility::UseAsPublic => "public",
540 ast::UseAsVisibility::UseAsPrivate => "private",
541 ast::UseAsVisibility::UseAsProtected => "protected",
542 ast::UseAsVisibility::UseAsFinal => "final",
546 fn print_use_alias<W: Write>(
549 (ido1, id, ido2, kindl): &(
550 Option<class::ClassType>,
552 Option<class::ClassType>,
553 &Vec<ast::UseAsVisibility>,
555 ) -> Result<(), W::Error> {
557 let id = id.to_raw_string();
561 |w, i: &class::ClassType| concat_str(w, [i.to_raw_string(), "::", id]),
565 if !kindl.is_empty() {
567 concat_by(w, " ", kindl, |w, k| print_use_as_visibility(w, *k))
570 w.write_if(!kindl.is_empty() && ido2.is_some(), " ")?;
571 option(w, ido2, |w, i: &class::ClassType| {
572 w.write(i.to_raw_string())
577 fn print_uses<W: Write>(ctx: &mut Context, w: &mut W, c: &HhasClass) -> Result<(), W::Error> {
578 if c.uses.is_empty() {
581 let unique_ids: IndexSet<&str> = c.uses.iter().map(|e| strip_global_ns(e)).collect();
582 let unique_ids: Vec<_> = unique_ids.into_iter().collect();
586 concat_by(w, " ", unique_ids, |w, id| w.write(id))?;
588 if c.use_aliases.is_empty() && c.use_precedences.is_empty() {
592 ctx.block(w, |ctx, w| {
593 for x in &c.use_precedences {
594 print_use_precedence(ctx, w, x)?;
596 for x in &c.use_aliases {
597 print_use_alias(ctx, w, x)?;
607 fn print_class_special_attributes<W: Write>(
611 ) -> Result<(), W::Error> {
612 let user_attrs = &c.attributes;
613 let is_system_lib = ctx.is_system_lib();
615 let mut special_attributes: Vec<&str> = vec![];
616 if c.needs_no_reifiedinit() {
617 special_attributes.push("noreifiedinit")
619 if c.no_dynamic_props() {
620 special_attributes.push("no_dynamic_props")
623 special_attributes.push("is_const")
625 if hhas_attribute::has_foldable(user_attrs) {
626 special_attributes.push("foldable")
628 if hhas_attribute::has_enum_class(user_attrs) {
629 special_attributes.push("enum_class")
632 special_attributes.extend(&["persistent", "builtin", "unique"])
634 if hhas_attribute::has_dynamically_constructible(user_attrs) {
635 special_attributes.push("dyn_constructible");
637 if c.is_closure() && !is_system_lib {
638 special_attributes.push("unique");
641 special_attributes.push("no_override");
644 special_attributes.push("trait");
646 if c.is_interface() {
647 special_attributes.push("interface");
650 special_attributes.push("final");
653 special_attributes.push("sealed");
655 if c.enum_type.is_some() && !hhbc_by_ref_hhas_attribute::has_enum_class(user_attrs) {
656 special_attributes.push("enum");
659 special_attributes.push("abstract");
661 if special_attributes.is_empty() && user_attrs.is_empty() {
665 special_attributes.reverse();
666 wrap_by_(w, "[", "] ", |w| {
667 concat_by(w, " ", &special_attributes, |w, a| w.write(a))?;
669 !special_attributes.is_empty() && !user_attrs.is_empty(),
672 print_attributes(ctx, w, &user_attrs)
676 fn print_implements<W: Write>(
678 implements: &[class::ClassType<'_>],
679 ) -> Result<(), W::Error> {
680 if implements.is_empty() {
683 w.write(" implements (")?;
689 .map(|x| x.to_raw_string())
690 .collect::<Vec<_>>(),
695 fn print_enum_includes<W: Write>(
697 enum_includes: &[class::ClassType<'_>],
698 ) -> Result<(), W::Error> {
699 if enum_includes.is_empty() {
702 w.write(" enum_includes (")?;
708 .map(|x| x.to_raw_string())
709 .collect::<Vec<_>>(),
714 fn print_shadowed_tparams<W: Write>(
716 shadowed_tparams: &[String],
717 ) -> Result<(), W::Error> {
718 braces(w, |w| concat_str_by(w, ", ", shadowed_tparams))
721 fn print_method_def<W: Write>(
724 method_def: &HhasMethod,
725 ) -> Result<(), W::Error> {
726 let body = &method_def.body;
728 w.write(" .method ")?;
729 print_shadowed_tparams(w, &body.shadowed_tparams)?;
730 print_upper_bounds(w, &body.upper_bounds)?;
732 print_method_attrs(ctx, w, method_def)?;
733 print_span(w, &method_def.span)?;
735 option(w, &body.return_type_info, |w, t| {
736 print_type_info(w, t)?;
739 w.write(method_def.name.to_raw_string())?;
740 print_params(ctx, w, body.env.as_ref(), &body.params)?;
741 if method_def.flags.contains(HhasMethodFlags::IS_GENERATOR) {
742 w.write(" isGenerator")?;
744 if method_def.flags.contains(HhasMethodFlags::IS_ASYNC) {
745 w.write(" isAsync")?;
749 .contains(HhasMethodFlags::IS_PAIR_GENERATOR)
751 w.write(" isPairGenerator")?;
753 if method_def.flags.contains(HhasMethodFlags::IS_CLOSURE_BODY) {
754 w.write(" isClosureBody")?;
758 ctx.block(w, |c, w| print_body(c, w, body, &method_def.coeffects))?;
764 fn print_method_attrs<W: Write>(
768 ) -> Result<(), W::Error> {
769 use hhas_attribute::*;
770 let user_attrs = &m.attributes;
771 let mut special_attrs = vec![];
772 if has_provenance_skip_frame(user_attrs) {
773 special_attrs.push("prov_skip_frame")
775 if m.is_interceptable() {
776 special_attrs.push("interceptable");
778 let visibility = m.visibility.to_string();
779 special_attrs.push(&visibility);
780 if m.flags.contains(HhasMethodFlags::IS_STATIC) {
781 special_attrs.push("static");
783 if m.flags.contains(HhasMethodFlags::IS_FINAL) {
784 special_attrs.push("final");
786 if m.flags.contains(HhasMethodFlags::IS_ABSTRACT) {
787 special_attrs.push("abstract");
789 if has_foldable(user_attrs) {
790 special_attrs.push("foldable");
792 if m.is_no_injection() {
793 special_attrs.push("no_injection");
795 if ctx.is_system_lib() && has_native(user_attrs) && !is_native_opcode_impl(user_attrs) {
796 special_attrs.push("unique");
798 if ctx.is_system_lib() {
799 special_attrs.push("builtin");
801 if ctx.is_system_lib() && has_native(user_attrs) && !is_native_opcode_impl(user_attrs) {
802 special_attrs.push("persistent");
804 if ctx.is_system_lib() || (has_dynamically_callable(user_attrs) && !m.is_memoize_impl()) {
805 special_attrs.push("dyn_callable")
807 print_special_and_user_attrs(ctx, w, &special_attrs, user_attrs)
810 fn print_class_def<W: Write>(
813 class_def: &HhasClass,
814 ) -> Result<(), W::Error> {
817 print_upper_bounds(w, &class_def.upper_bounds)?;
819 print_class_special_attributes(ctx, w, class_def)?;
820 w.write(class_def.name.to_raw_string())?;
822 print_span(w, &class_def.span)?;
823 print_extends(w, class_def.base.as_ref().map(|x| x.to_raw_string()))?;
824 print_implements(w, class_def.implements.as_ref())?;
825 print_enum_includes(w, class_def.enum_includes.as_ref())?;
827 ctx.block(w, |c, w| {
828 print_doc_comment(c, w, &class_def.doc_comment)?;
829 print_uses(c, w, class_def)?;
830 print_enum_ty(c, w, class_def)?;
831 for x in &class_def.requirements {
832 print_requirement(c, w, x)?;
834 for x in &class_def.constants {
835 print_constant(c, w, x)?;
837 for x in &class_def.type_constants {
838 print_type_constant(c, w, x)?;
840 for x in &class_def.ctx_constants {
841 print_ctx_constant(c, w, x)?;
843 for x in &class_def.properties {
844 print_property(c, w, class_def, x)?;
846 for m in &class_def.methods {
847 print_method_def(c, w, m)?;
856 fn print_pos_as_prov_tag<W: Write>(
859 loc: &Option<ast_defs::Pos>,
860 ) -> Result<(), W::Error> {
862 Some(l) if ctx.array_provenance => {
863 let (line, ..) = l.info_pos();
864 let filename = l.filename().to_absolute();
865 let filename = match filename.to_str().unwrap() {
866 "" => "(unknown hackc filename)",
874 quote_string_with_escape(filename)
881 fn print_hhbc_id<'a, W: Write>(w: &mut W, id: &impl Id<'a>) -> Result<(), W::Error> {
882 quotes(w, |w| w.write(escape(id.to_raw_string())))
885 fn print_function_id<W: Write>(w: &mut W, id: &FunctionId) -> Result<(), W::Error> {
889 fn print_class_id<W: Write>(w: &mut W, id: &ClassId) -> Result<(), W::Error> {
893 fn print_method_id<W: Write>(w: &mut W, id: &MethodId) -> Result<(), W::Error> {
897 fn print_const_id<W: Write>(w: &mut W, id: &ConstId) -> Result<(), W::Error> {
901 fn print_prop_id<W: Write>(w: &mut W, id: &PropId) -> Result<(), W::Error> {
905 fn print_adata_id<W: Write>(w: &mut W, id: &AdataId) -> Result<(), W::Error> {
906 concat_str(w, ["@", id.as_str()])
909 fn print_adata_mapped_argument<W: Write, F, V>(
913 loc: &Option<ast_defs::Pos>,
916 ) -> Result<(), W::Error>
918 F: Fn(&mut Context, &mut W, &V) -> Result<(), W::Error>,
920 write!(w, "{}:{}:{{", col_type, values.len(),)?;
921 print_pos_as_prov_tag(ctx, w, loc)?;
928 fn print_adata_collection_argument<W: Write>(
932 loc: &Option<ast_defs::Pos>,
933 values: &[TypedValue],
934 ) -> Result<(), W::Error> {
935 print_adata_mapped_argument(ctx, w, col_type, loc, values, &print_adata)
938 fn print_adata_dict_collection_argument<W: Write>(
942 loc: &Option<ast_defs::Pos>,
943 pairs: &[Pair<TypedValue, TypedValue>],
944 ) -> Result<(), W::Error> {
945 print_adata_mapped_argument(ctx, w, col_type, loc, pairs, |ctx, w, Pair(v1, v2)| {
946 print_adata(ctx, w, v1)?;
947 print_adata(ctx, w, v2)
951 fn print_adata<W: Write>(ctx: &mut Context, w: &mut W, tv: &TypedValue) -> Result<(), W::Error> {
953 TypedValue::Uninit => w.write("uninit"),
954 TypedValue::Null => w.write("N;"),
955 TypedValue::String(s) => {
956 write!(w, "s:{}:{};", s.len(), quote_string_with_escape(s.as_str()))
958 TypedValue::LazyClass(s) => {
959 write!(w, "l:{}:{};", s.len(), quote_string_with_escape(s.as_str()))
961 TypedValue::Float(f) => write!(w, "d:{};", float::to_string(*f)),
962 TypedValue::Int(i) => write!(w, "i:{};", i),
963 // TODO: The False case seems to sometimes be b:0 and sometimes i:0. Why?
964 TypedValue::Bool(false) => w.write("b:0;"),
965 TypedValue::Bool(true) => w.write("b:1;"),
966 TypedValue::Vec(values) => {
967 print_adata_collection_argument(ctx, w, VEC_PREFIX, &None, values.as_ref())
969 TypedValue::Dict(pairs) => {
970 print_adata_dict_collection_argument(ctx, w, DICT_PREFIX, &None, pairs.as_ref())
972 TypedValue::Keyset(values) => {
973 print_adata_collection_argument(ctx, w, KEYSET_PREFIX, &None, values.as_ref())
975 TypedValue::HhasAdata(s) => w.write(escaped(s.as_str())),
979 fn print_attribute<W: Write>(
983 ) -> Result<(), W::Error> {
986 "\"{}\"(\"\"\"{}:{}:{{",
991 concat(w, &a.arguments, |w, arg| print_adata(ctx, w, arg))?;
995 fn print_attributes<'a, W: Write>(
998 al: impl AsRef<[HhasAttribute<'a>]>,
999 ) -> Result<(), W::Error> {
1000 // Adjust for underscore coming before alphabet
1001 let al: Vec<&HhasAttribute> = al
1004 .sorted_by_key(|a| (!a.name.as_str().starts_with("__"), a.name.as_str()))
1006 concat_by(w, " ", &al, |w, a| print_attribute(ctx, w, a))
1009 fn print_file_attributes<W: Write>(
1012 al: &[HhasAttribute],
1013 ) -> Result<(), W::Error> {
1018 w.write(".file_attributes [")?;
1019 print_attributes(ctx, w, al)?;
1024 fn is_bareword_char(c: &u8) -> bool {
1026 b'_' | b'.' | b'$' | b'\\' => true,
1027 c => (b'0'..=b'9').contains(&c) || (b'a'..=b'z').contains(&c) || (b'A'..=b'Z').contains(&c),
1031 fn print_body<W: Write>(
1035 coeffects: &HhasCoeffects,
1036 ) -> Result<(), W::Error> {
1037 print_doc_comment(ctx, w, &body.doc_comment)?;
1038 if body.is_memoize_wrapper {
1040 w.write(".ismemoizewrapper;")?;
1042 if body.is_memoize_wrapper_lsb {
1044 w.write(".ismemoizewrapperlsb;")?;
1046 if body.num_iters > 0 {
1048 write!(w, ".numiters {};", body.num_iters)?;
1050 if !body.decl_vars.is_empty() {
1052 w.write(".declvars ")?;
1053 concat_by(w, " ", &body.decl_vars, |w, var| {
1054 if var.as_bytes().iter().all(is_bareword_char) {
1057 quotes(w, |w| w.write(escaper::escape(var)))
1062 if body.num_closures > 0 {
1064 write!(w, ".numclosures {};", body.num_closures)?;
1066 for s in HhasCoeffects::coeffects_to_hhas(&coeffects).iter() {
1070 print_instructions(ctx, w, &body.body_instrs)
1073 fn print_instructions<W: Write>(
1076 instr_seq: &InstrSeq,
1077 ) -> Result<(), W::Error> {
1080 for instr in instr_seq.compact_iter() {
1082 ISpecialFlow(_) => return Err(Error::fail("Cannot break/continue 1 level")),
1086 print_instr(w, instr)?;
1088 ILabel(_) => ctx.unblock(w, |c, w| {
1090 print_instr(w, instr)
1092 ITry(TryCatchBegin) => {
1094 print_instr(w, instr)?;
1097 ITry(TryCatchMiddle) => ctx.unblock(w, |c, w| {
1099 print_instr(w, instr)
1101 ITry(TryCatchEnd) => {
1104 print_instr(w, instr)?;
1108 print_instr(w, instr)?;
1115 fn if_then<F: FnOnce() -> R, R>(cond: bool, f: F) -> Option<R> {
1116 if cond { Some(f()) } else { None }
1119 fn print_fcall_args<W: Write>(
1121 FcallArgs(fls, num_args, num_rets, inouts, async_eager_label, context): &FcallArgs,
1122 ) -> Result<(), W::Error> {
1123 use FcallFlags as F;
1124 let mut flags = vec![];
1125 if_then(fls.contains(F::HAS_UNPACK), || flags.push("Unpack"));
1126 if_then(fls.contains(F::HAS_GENERICS), || flags.push("Generics"));
1127 if_then(fls.contains(F::LOCK_WHILE_UNWINDING), || {
1128 flags.push("LockWhileUnwinding")
1130 angle(w, |w| concat_str_by(w, " ", flags))?;
1132 print_int(w, num_args)?;
1134 print_int(w, num_rets)?;
1137 concat_by(w, "", inouts, |w, i| w.write(if *i { "1" } else { "0" }))
1140 option_or(w, async_eager_label.as_ref(), print_label, "-")?;
1143 Just(s) => quotes(w, |w| w.write(s)),
1144 Nothing => w.write("\"\""),
1148 fn print_special_cls_ref<W: Write>(w: &mut W, cls_ref: &SpecialClsRef) -> Result<(), W::Error> {
1149 w.write(match cls_ref {
1150 SpecialClsRef::Static => "Static",
1151 SpecialClsRef::Self_ => "Self",
1152 SpecialClsRef::Parent => "Parent",
1156 fn print_null_flavor<W: Write>(w: &mut W, f: &ObjNullFlavor) -> Result<(), W::Error> {
1158 ObjNullFlavor::NullThrows => "NullThrows",
1159 ObjNullFlavor::NullSafe => "NullSafe",
1163 fn print_instr<W: Write>(w: &mut W, instr: &Instruct) -> Result<(), W::Error> {
1164 fn print_call<W: Write>(w: &mut W, call: &InstructCall) -> Result<(), W::Error> {
1165 use InstructCall as I;
1167 I::NewObj => w.write("NewObj"),
1168 I::NewObjR => w.write("NewObjR"),
1169 I::NewObjD(cid) => {
1170 w.write("NewObjD ")?;
1171 print_class_id(w, cid)
1173 I::NewObjRD(cid) => {
1174 w.write("NewObjRD ")?;
1175 print_class_id(w, cid)
1178 w.write("NewObjS ")?;
1179 print_special_cls_ref(w, r)
1181 I::FCall(fcall_args) => {
1183 print_fcall_args(w, &fcall_args)?;
1184 w.write(r#" "" """#)
1186 I::FCallClsMethod(fcall_args, is_log_as_dynamic_call) => {
1187 w.write("FCallClsMethod ")?;
1188 print_fcall_args(w, fcall_args)?;
1189 w.write(r#" "" "#)?;
1190 w.write(match is_log_as_dynamic_call {
1191 IsLogAsDynamicCallOp::LogAsDynamicCall => "LogAsDynamicCall",
1192 IsLogAsDynamicCallOp::DontLogAsDynamicCall => "DontLogAsDynamicCall",
1195 I::FCallClsMethodD(fcall_args, cid, mid) => {
1196 w.write("FCallClsMethodD ")?;
1197 print_fcall_args(w, fcall_args)?;
1198 w.write(r#" "" "#)?;
1199 print_class_id(w, cid)?;
1201 print_method_id(w, mid)
1203 I::FCallClsMethodS(fcall_args, r) => {
1204 w.write("FCallClsMethodS ")?;
1205 print_fcall_args(w, fcall_args)?;
1206 w.write(r#" "" "#)?;
1207 print_special_cls_ref(w, r)
1209 I::FCallClsMethodSD(fcall_args, r, mid) => {
1210 w.write("FCallClsMethodSD ")?;
1211 print_fcall_args(w, fcall_args)?;
1212 w.write(r#" "" "#)?;
1213 print_special_cls_ref(w, r)?;
1215 print_method_id(w, mid)
1217 I::FCallCtor(fcall_args) => {
1218 w.write("FCallCtor ")?;
1219 print_fcall_args(w, fcall_args)?;
1222 I::FCallFunc(fcall_args) => {
1223 w.write("FCallFunc ")?;
1224 print_fcall_args(w, fcall_args)
1226 I::FCallFuncD(fcall_args, id) => {
1227 w.write("FCallFuncD ")?;
1228 print_fcall_args(w, fcall_args)?;
1230 print_function_id(w, id)
1232 I::FCallObjMethod(fcall_args, nf) => {
1233 w.write("FCallObjMethod ")?;
1234 print_fcall_args(w, fcall_args)?;
1235 w.write(r#" "" "#)?;
1236 print_null_flavor(w, nf)
1238 I::FCallObjMethodD(fcall_args, nf, id) => {
1239 w.write("FCallObjMethodD ")?;
1240 print_fcall_args(w, fcall_args)?;
1241 w.write(r#" "" "#)?;
1242 print_null_flavor(w, nf)?;
1244 print_method_id(w, id)
1249 fn print_get<W: Write>(w: &mut W, get: &InstructGet) -> Result<(), W::Error> {
1250 use InstructGet as IG;
1256 IG::CGetQuietL(id) => {
1257 w.write("CGetQuietL ")?;
1261 w.write("CGetL2 ")?;
1265 w.write("CUGetL ")?;
1272 IG::CGetG => w.write("CGetG"),
1275 print_readonly_op(w, op)
1277 IG::ClassGetC => w.write("ClassGetC"),
1278 IG::ClassGetTS => w.write("ClassGetTS"),
1283 use InstructBasic as IB;
1285 IIterator(i) => print_iterator(w, i),
1286 IBasic(b) => w.write(match b {
1288 IB::EntryNop => "EntryNop",
1293 ILitConst(lit) => print_lit_const(w, lit),
1294 IOp(op) => print_op(w, op),
1295 IContFlow(cf) => print_control_flow(w, cf),
1296 ICall(c) => print_call(w, c),
1297 IMisc(misc) => print_misc(w, misc),
1298 IGet(get) => print_get(w, get),
1299 IMutator(mutator) => print_mutator(w, mutator),
1304 IIsset(i) => print_isset(w, i),
1305 IBase(i) => print_base(w, i),
1306 IFinal(i) => print_final(w, i),
1307 ITry(itry) => print_try(w, itry),
1308 IComment(s) => concat_str_by(w, " ", ["#", s.as_str()]),
1309 ISrcLoc(p) => write!(
1311 ".srcloc {}:{},{}:{};",
1312 p.line_begin, p.col_begin, p.line_end, p.col_end
1314 IAsync(a) => print_async(w, a),
1315 IGenerator(gen) => print_gen_creation_execution(w, gen),
1316 IIncludeEvalDefine(ed) => print_include_eval_define(w, ed),
1317 _ => Err(Error::fail("invalid instruction")),
1321 fn print_base<W: Write>(w: &mut W, i: &InstructBase) -> Result<(), W::Error> {
1322 use InstructBase as I;
1324 I::BaseGC(si, m) => {
1325 w.write("BaseGC ")?;
1326 print_stack_index(w, si)?;
1328 print_member_opmode(w, m)
1330 I::BaseGL(id, m) => {
1331 w.write("BaseGL ")?;
1332 print_local(w, id)?;
1334 print_member_opmode(w, m)
1336 I::BaseSC(si1, si2, m, op) => {
1337 w.write("BaseSC ")?;
1338 print_stack_index(w, si1)?;
1340 print_stack_index(w, si2)?;
1342 print_member_opmode(w, m)?;
1344 print_readonly_op(w, op)
1346 I::BaseL(id, m) => {
1348 print_local(w, id)?;
1350 print_member_opmode(w, m)
1352 I::BaseC(si, m) => {
1354 print_stack_index(w, si)?;
1356 print_member_opmode(w, m)
1358 I::BaseH => w.write("BaseH"),
1361 print_member_opmode(w, m)?;
1363 print_member_key(w, mk)
1368 fn print_stack_index<W: Write>(w: &mut W, si: &StackIndex) -> Result<(), W::Error> {
1369 w.write(si.to_string())
1372 fn print_member_opmode<W: Write>(w: &mut W, m: &MemberOpMode) -> Result<(), W::Error> {
1373 use MemberOpMode as M;
1375 M::ModeNone => "None",
1377 M::Define => "Define",
1378 M::Unset => "Unset",
1379 M::InOut => "InOut",
1383 fn print_member_key<W: Write>(w: &mut W, mk: &MemberKey) -> Result<(), W::Error> {
1388 print_stack_index(w, si)?;
1390 print_readonly_op(w, op)
1392 M::EL(local, op) => {
1394 print_local(w, local)?;
1396 print_readonly_op(w, op)
1400 quotes(w, |w| w.write(escape(s.as_str())))?;
1402 print_readonly_op(w, op)
1405 concat_str(w, ["EI:", i.to_string().as_ref()])?;
1407 print_readonly_op(w, op)
1411 print_stack_index(w, si)?;
1413 print_readonly_op(w, op)
1415 M::PL(local, op) => {
1417 print_local(w, local)?;
1419 print_readonly_op(w, op)
1423 print_prop_id(w, id)?;
1425 print_readonly_op(w, op)
1429 print_prop_id(w, id)?;
1431 print_readonly_op(w, op)
1433 M::W => w.write("W"),
1437 fn print_iterator<W: Write>(w: &mut W, i: &InstructIterator) -> Result<(), W::Error> {
1438 use InstructIterator as I;
1440 I::IterInit(iter_args, label) => {
1441 w.write("IterInit ")?;
1442 print_iter_args(w, iter_args)?;
1444 print_label(w, label)
1446 I::IterNext(iter_args, label) => {
1447 w.write("IterNext ")?;
1448 print_iter_args(w, iter_args)?;
1450 print_label(w, label)
1452 I::IterFree(id) => {
1453 w.write("IterFree ")?;
1454 print_iterator_id(w, id)
1459 fn print_iter_args<W: Write>(w: &mut W, iter_args: &IterArgs) -> Result<(), W::Error> {
1460 print_iterator_id(w, &iter_args.iter_id)?;
1462 match &iter_args.key_id {
1463 Nothing => w.write("NK")?,
1466 print_local(w, &k)?;
1471 print_local(w, &iter_args.val_id)
1474 fn print_iterator_id<W: Write>(w: &mut W, i: &IterId) -> Result<(), W::Error> {
1478 fn print_async<W: Write>(w: &mut W, a: &AsyncFunctions) -> Result<(), W::Error> {
1479 use AsyncFunctions as A;
1481 A::WHResult => w.write("WHResult"),
1482 A::Await => w.write("Await"),
1483 A::AwaitAll(Just(Pair(Local::Unnamed(id), count))) => {
1484 write!(w, "AwaitAll L:{}+{}", id, count)
1486 A::AwaitAll(Nothing) => w.write("AwaitAll L:0+0"),
1487 _ => Err(Error::fail("AwaitAll needs an unnamed local")),
1491 fn print_query_op<W: Write>(w: &mut W, q: QueryOp) -> Result<(), W::Error> {
1493 QueryOp::CGet => "CGet",
1494 QueryOp::CGetQuiet => "CGetQuiet",
1495 QueryOp::Isset => "Isset",
1496 QueryOp::InOut => "InOut",
1500 fn print_final<W: Write>(w: &mut W, f: &InstructFinal) -> Result<(), W::Error> {
1501 use InstructFinal as F;
1503 F::QueryM(n, op, mk) => {
1504 w.write("QueryM ")?;
1507 print_query_op(w, *op)?;
1509 print_member_key(w, mk)
1511 F::UnsetM(n, mk) => {
1512 w.write("UnsetM ")?;
1515 print_member_key(w, mk)
1521 print_member_key(w, mk)
1523 F::SetOpM(i, op, mk) => {
1524 w.write("SetOpM ")?;
1527 print_eq_op(w, &op)?;
1529 print_member_key(w, mk)
1531 F::IncDecM(i, op, mk) => {
1532 w.write("IncDecM ")?;
1535 print_incdec_op(w, &op)?;
1537 print_member_key(w, mk)
1539 F::SetRangeM(i, s, op) => {
1540 w.write("SetRangeM ")?;
1543 print_int(w, &(*s as usize))?;
1546 SetrangeOp::Forward => "Forward",
1547 SetrangeOp::Reverse => "Reverse",
1553 fn print_isset<W: Write>(w: &mut W, isset: &InstructIsset) -> Result<(), W::Error> {
1554 use InstructIsset as I;
1556 I::IssetC => w.write("IssetC"),
1557 I::IssetL(local) => {
1558 w.write("IssetL ")?;
1559 print_local(w, local)
1561 I::IsUnsetL(local) => {
1562 w.write("IsUnsetL ")?;
1563 print_local(w, local)
1565 I::IssetG => w.write("IssetG"),
1566 I::IssetS => w.write("IssetS"),
1568 w.write("IsTypeC ")?;
1569 print_istype_op(w, op)
1571 I::IsTypeL(local, op) => {
1572 w.write("IsTypeL ")?;
1573 print_local(w, local)?;
1575 print_istype_op(w, op)
1580 fn print_istype_op<W: Write>(w: &mut W, op: &IstypeOp) -> Result<(), W::Error> {
1583 Op::OpNull => w.write("Null"),
1584 Op::OpBool => w.write("Bool"),
1585 Op::OpInt => w.write("Int"),
1586 Op::OpDbl => w.write("Dbl"),
1587 Op::OpStr => w.write("Str"),
1588 Op::OpObj => w.write("Obj"),
1589 Op::OpRes => w.write("Res"),
1590 Op::OpScalar => w.write("Scalar"),
1591 Op::OpKeyset => w.write("Keyset"),
1592 Op::OpDict => w.write("Dict"),
1593 Op::OpVec => w.write("Vec"),
1594 Op::OpArrLike => w.write("ArrLike"),
1595 Op::OpLegacyArrLike => w.write("LegacyArrLike"),
1596 Op::OpClsMeth => w.write("ClsMeth"),
1597 Op::OpFunc => w.write("Func"),
1598 Op::OpClass => w.write("Class"),
1602 fn print_try<W: Write>(w: &mut W, itry: &InstructTry) -> Result<(), W::Error> {
1603 use InstructTry as T;
1605 T::TryCatchBegin => w.write(".try {"),
1606 T::TryCatchMiddle => w.write("} .catch {"),
1607 T::TryCatchEnd => w.write("}"),
1611 fn print_mutator<W: Write>(w: &mut W, mutator: &InstructMutator) -> Result<(), W::Error> {
1612 use InstructMutator as M;
1616 print_local(w, local)
1622 M::SetG => w.write("SetG"),
1625 print_readonly_op(w, op)
1627 M::SetOpL(id, op) => {
1628 w.write("SetOpL ")?;
1629 print_local(w, id)?;
1634 w.write("SetOpG ")?;
1638 w.write("SetOpS ")?;
1641 M::IncDecL(id, op) => {
1642 w.write("IncDecL ")?;
1643 print_local(w, id)?;
1645 print_incdec_op(w, op)
1648 w.write("IncDecG ")?;
1649 print_incdec_op(w, op)
1652 w.write("IncDecS ")?;
1653 print_incdec_op(w, op)
1656 w.write("UnsetL ")?;
1659 M::UnsetG => w.write("UnsetG"),
1660 M::CheckProp(id) => {
1661 w.write("CheckProp ")?;
1662 print_prop_id(w, id)
1664 M::InitProp(id, op) => {
1665 w.write("InitProp ")?;
1666 print_prop_id(w, id)?;
1669 InitpropOp::Static => w.write("Static"),
1670 InitpropOp::NonStatic => w.write("NonStatic"),
1677 fn print_eq_op<W: Write>(w: &mut W, op: &EqOp) -> Result<(), W::Error> {
1679 EqOp::PlusEqual => "PlusEqual",
1680 EqOp::MinusEqual => "MinusEqual",
1681 EqOp::MulEqual => "MulEqual",
1682 EqOp::ConcatEqual => "ConcatEqual",
1683 EqOp::DivEqual => "DivEqual",
1684 EqOp::PowEqual => "PowEqual",
1685 EqOp::ModEqual => "ModEqual",
1686 EqOp::AndEqual => "AndEqual",
1687 EqOp::OrEqual => "OrEqual",
1688 EqOp::XorEqual => "XorEqual",
1689 EqOp::SlEqual => "SlEqual",
1690 EqOp::SrEqual => "SrEqual",
1691 EqOp::PlusEqualO => "PlusEqualO",
1692 EqOp::MinusEqualO => "MinusEqualO",
1693 EqOp::MulEqualO => "MulEqualO",
1697 fn print_readonly_op<W: Write>(w: &mut W, op: &ReadOnlyOp) -> Result<(), W::Error> {
1699 ReadOnlyOp::ReadOnly => "ReadOnly",
1700 ReadOnlyOp::Mutable => "Mutable",
1701 ReadOnlyOp::Any => "Any",
1702 ReadOnlyOp::CheckROCOW => "CheckROCOW",
1706 fn print_incdec_op<W: Write>(w: &mut W, op: &IncdecOp) -> Result<(), W::Error> {
1708 IncdecOp::PreInc => "PreInc",
1709 IncdecOp::PostInc => "PostInc",
1710 IncdecOp::PreDec => "PreDec",
1711 IncdecOp::PostDec => "PostDec",
1712 IncdecOp::PreIncO => "PreIncO",
1713 IncdecOp::PostIncO => "PostIncO",
1714 IncdecOp::PreDecO => "PreDecO",
1715 IncdecOp::PostDecO => "PostDecO",
1719 fn print_gen_creation_execution<W: Write>(
1721 gen: &GenCreationExecution,
1722 ) -> Result<(), W::Error> {
1723 use GenCreationExecution as G;
1725 G::CreateCont => w.write("CreateCont"),
1726 G::ContEnter => w.write("ContEnter"),
1727 G::ContRaise => w.write("ContRaise"),
1728 G::Yield => w.write("Yield"),
1729 G::YieldK => w.write("YieldK"),
1730 G::ContCheck(CheckStarted::IgnoreStarted) => w.write("ContCheck IgnoreStarted"),
1731 G::ContCheck(CheckStarted::CheckStarted) => w.write("ContCheck CheckStarted"),
1732 G::ContValid => w.write("ContValid"),
1733 G::ContKey => w.write("ContKey"),
1734 G::ContGetReturn => w.write("ContGetReturn"),
1735 G::ContCurrent => w.write("ContCurrent"),
1739 fn print_misc<W: Write>(w: &mut W, misc: &InstructMisc) -> Result<(), W::Error> {
1740 use InstructMisc as M;
1742 M::This => w.write("This"),
1743 M::CheckThis => w.write("CheckThis"),
1744 M::FuncNumArgs => w.write("FuncNumArgs"),
1745 M::ChainFaults => w.write("ChainFaults"),
1746 M::VerifyRetTypeC => w.write("VerifyRetTypeC"),
1747 M::VerifyRetTypeTS => w.write("VerifyRetTypeTS"),
1748 M::Self_ => w.write("Self"),
1749 M::Parent => w.write("Parent"),
1750 M::LateBoundCls => w.write("LateBoundCls"),
1751 M::ClassName => w.write("ClassName"),
1752 M::LazyClassFromClass => w.write("LazyClassFromClass"),
1753 M::RecordReifiedGeneric => w.write("RecordReifiedGeneric"),
1754 M::CheckReifiedGenericMismatch => w.write("CheckReifiedGenericMismatch"),
1755 M::NativeImpl => w.write("NativeImpl"),
1756 M::AKExists => w.write("AKExists"),
1757 M::Idx => w.write("Idx"),
1758 M::ArrayIdx => w.write("ArrayIdx"),
1759 M::ArrayMarkLegacy => w.write("ArrayMarkLegacy"),
1760 M::ArrayUnmarkLegacy => w.write("ArrayUnmarkLegacy"),
1761 M::BreakTraceHint => w.write("BreakTraceHint"),
1762 M::CGetCUNop => w.write("CGetCUNop"),
1763 M::UGetCUNop => w.write("UGetCUNop"),
1764 M::LockObj => w.write("LockObj"),
1765 M::ThrowNonExhaustiveSwitch => w.write("ThrowNonExhaustiveSwitch"),
1766 M::RaiseClassStringConversionWarning => w.write("RaiseClassStringConversionWarning"),
1767 M::VerifyParamType(id) => {
1768 w.write("VerifyParamType ")?;
1769 print_param_id(w, id)
1771 M::VerifyParamTypeTS(id) => {
1772 w.write("VerifyParamTypeTS ")?;
1773 print_param_id(w, id)
1775 M::Silence(local, op) => {
1776 w.write("Silence ")?;
1777 print_local(w, local)?;
1780 OpSilence::Start => w.write("Start"),
1781 OpSilence::End => w.write("End"),
1784 M::VerifyOutType(id) => {
1785 w.write("VerifyOutType ")?;
1786 print_param_id(w, id)
1788 M::CreateCl(n, cid) => concat_str_by(
1791 ["CreateCl", n.to_string().as_str(), cid.to_string().as_str()],
1793 M::BareThis(op) => concat_str_by(
1799 BareThisOp::Notice => "Notice",
1800 BareThisOp::NoNotice => "NoNotice",
1801 BareThisOp::NeverNull => "NeverNull",
1806 M::MemoGet(label, Just(Pair(Local::Unnamed(first), local_count))) => {
1807 w.write("MemoGet ")?;
1808 print_label(w, label)?;
1809 write!(w, " L:{}+{}", first, local_count)
1811 M::MemoGet(label, Nothing) => {
1812 w.write("MemoGet ")?;
1813 print_label(w, label)?;
1816 M::MemoGet(_, _) => Err(Error::fail("MemoGet needs an unnamed local")),
1818 M::MemoSet(Just(Pair(Local::Unnamed(first), local_count))) => {
1819 write!(w, "MemoSet L:{}+{}", first, local_count)
1821 M::MemoSet(Nothing) => w.write("MemoSet L:0+0"),
1822 M::MemoSet(_) => Err(Error::fail("MemoSet needs an unnamed local")),
1824 M::MemoGetEager(label1, label2, Just(Pair(Local::Unnamed(first), local_count))) => {
1825 w.write("MemoGetEager ")?;
1826 print_label(w, label1)?;
1828 print_label(w, label2)?;
1829 write!(w, " L:{}+{}", first, local_count)
1831 M::MemoGetEager(label1, label2, Nothing) => {
1832 w.write("MemoGetEager ")?;
1833 print_label(w, label1)?;
1835 print_label(w, label2)?;
1838 M::MemoGetEager(_, _, _) => Err(Error::fail("MemoGetEager needs an unnamed local")),
1840 M::MemoSetEager(Just(Pair(Local::Unnamed(first), local_count))) => {
1841 write!(w, "MemoSetEager L:{}+{}", first, local_count)
1843 M::MemoSetEager(Nothing) => w.write("MemoSetEager L:0+0"),
1844 M::MemoSetEager(_) => Err(Error::fail("MemoSetEager needs an unnamed local")),
1846 M::OODeclExists(k) => concat_str_by(
1852 ClassishKind::Class => "Class",
1853 ClassishKind::Interface => "Interface",
1854 ClassishKind::Trait => "Trait",
1858 M::AssertRATL(local, s) => {
1859 w.write("AssertRATL ")?;
1860 print_local(w, local)?;
1864 M::AssertRATStk(n, s) => {
1865 concat_str_by(w, " ", ["AssertRATStk", n.to_string().as_str(), s.as_str()])
1867 M::GetMemoKeyL(local) => {
1868 w.write("GetMemoKeyL ")?;
1869 print_local(w, local)
1874 fn print_include_eval_define<W: Write>(
1876 ed: &InstructIncludeEvalDefine,
1877 ) -> Result<(), W::Error> {
1878 use InstructIncludeEvalDefine::*;
1880 Incl => w.write("Incl"),
1881 InclOnce => w.write("InclOnce"),
1882 Req => w.write("Req"),
1883 ReqOnce => w.write("ReqOnce"),
1884 ReqDoc => w.write("ReqDoc"),
1885 Eval => w.write("Eval"),
1889 fn print_control_flow<W: Write>(w: &mut W, cf: &InstructControlFlow) -> Result<(), W::Error> {
1890 use InstructControlFlow as CF;
1908 CF::RetC => w.write("RetC"),
1909 CF::RetCSuspended => w.write("RetCSuspended"),
1910 CF::RetM(p) => concat_str_by(w, " ", ["RetM", p.to_string().as_str()]),
1911 CF::Throw => w.write("Throw"),
1912 CF::Switch(kind, base, labels) => print_switch(w, kind, base, labels.as_ref()),
1913 CF::SSwitch(cases) => match cases.as_ref() {
1914 [] => Err(Error::fail("sswitch should have at least one case")),
1915 [rest @ .., Pair(_, lastlabel)] => {
1916 w.write("SSwitch ")?;
1918 concat_by(w, " ", rest, |w, Pair(s, l)| {
1919 concat_str(w, [quote_string(s.as_ref()).as_str(), ":"])?;
1923 print_label(w, &lastlabel)
1930 fn print_switch<W: Write>(
1935 ) -> Result<(), W::Error> {
1936 w.write("Switch ")?;
1937 w.write(match kind {
1938 Switchkind::Bounded => "Bounded ",
1939 Switchkind::Unbounded => "Unbounded ",
1941 w.write(base.to_string())?;
1943 angle(w, |w| concat_by(w, " ", labels, print_label))
1946 fn print_lit_const<W: Write>(w: &mut W, lit: &InstructLitConst) -> Result<(), W::Error> {
1947 use InstructLitConst as LC;
1949 LC::Null => w.write("Null"),
1950 LC::Int(i) => concat_str_by(w, " ", ["Int", i.to_string().as_str()]),
1952 w.write("String ")?;
1953 quotes(w, |w| w.write(escape(s.as_str())))
1955 LC::LazyClass(id) => {
1956 w.write("LazyClass ")?;
1957 print_class_id(w, id)
1959 LC::True => w.write("True"),
1960 LC::False => w.write("False"),
1961 LC::Double(d) => concat_str_by(w, " ", ["Double", d.as_str()]),
1962 LC::AddElemC => w.write("AddElemC"),
1963 LC::AddNewElemC => w.write("AddNewElemC"),
1964 LC::NewPair => w.write("NewPair"),
1965 LC::File => w.write("File"),
1966 LC::Dir => w.write("Dir"),
1967 LC::Method => w.write("Method"),
1968 LC::FuncCred => w.write("FuncCred"),
1971 print_adata_id(w, id)
1974 w.write("Keyset ")?;
1975 print_adata_id(w, id)
1979 print_adata_id(w, id)
1981 LC::NewDictArray(i) => concat_str_by(w, " ", ["NewDictArray", i.to_string().as_str()]),
1982 LC::NewVec(i) => concat_str_by(w, " ", ["NewVec", i.to_string().as_str()]),
1983 LC::NewKeysetArray(i) => concat_str_by(w, " ", ["NewKeysetArray", i.to_string().as_str()]),
1984 LC::NewStructDict(l) => {
1985 let ls: Vec<&str> = l.as_ref().into_iter().map(|s| s.as_str()).collect();
1986 w.write("NewStructDict ")?;
1987 angle(w, |w| print_shape_fields(w, &ls[0..]))
1989 LC::NewRecord(cid, l) => {
1990 let ls: Vec<&str> = l.as_ref().into_iter().map(|s| s.as_str()).collect();
1991 w.write("NewRecord ")?;
1992 print_class_id(w, cid)?;
1994 angle(w, |w| print_shape_fields(w, &ls[0..]))
1998 print_const_id(w, id)
2001 w.write("ClsCns ")?;
2002 print_const_id(w, id)
2004 LC::ClsCnsD(const_id, cid) => {
2005 w.write("ClsCnsD ")?;
2006 print_const_id(w, const_id)?;
2008 print_class_id(w, cid)
2010 LC::ClsCnsL(id) => {
2011 w.write("ClsCnsL ")?;
2015 w.write("NewCol ")?;
2016 print_collection_type(w, ct)
2018 LC::ColFromArray(ct) => {
2019 w.write("ColFromArray ")?;
2020 print_collection_type(w, ct)
2022 LC::NullUninit => w.write("NullUninit"),
2023 LC::TypedValue(_) => Err(Error::fail("print_lit_const: TypedValue")),
2027 fn print_collection_type<W: Write>(w: &mut W, ct: &CollectionType) -> Result<(), W::Error> {
2028 use CollectionType as CT;
2030 CT::Vector => w.write("Vector"),
2031 CT::Map => w.write("Map"),
2032 CT::Set => w.write("Set"),
2033 CT::Pair => w.write("Pair"),
2034 CT::ImmVector => w.write("ImmVector"),
2035 CT::ImmMap => w.write("ImmMap"),
2036 CT::ImmSet => w.write("ImmSet"),
2037 CT::Dict => w.write("dict"),
2038 CT::Array => w.write("array"),
2039 CT::Keyset => w.write("keyset"),
2040 CT::Vec => w.write("vec"),
2044 fn print_shape_fields<W: Write>(w: &mut W, sf: &[&str]) -> Result<(), W::Error> {
2045 concat_by(w, " ", sf, |w, f| quotes(w, |w| w.write(escape(*f))))
2048 fn print_op<W: Write>(w: &mut W, op: &InstructOperator) -> Result<(), W::Error> {
2049 use InstructOperator as I;
2051 I::Concat => w.write("Concat"),
2052 I::ConcatN(n) => concat_str_by(w, " ", ["ConcatN", n.to_string().as_str()]),
2053 I::Add => w.write("Add"),
2054 I::Sub => w.write("Sub"),
2055 I::Mul => w.write("Mul"),
2056 I::AddO => w.write("AddO"),
2057 I::SubO => w.write("SubO"),
2058 I::MulO => w.write("MulO"),
2059 I::Div => w.write("Div"),
2060 I::Mod => w.write("Mod"),
2061 I::Pow => w.write("Pow"),
2062 I::Not => w.write("Not"),
2063 I::Same => w.write("Same"),
2064 I::NSame => w.write("NSame"),
2065 I::Eq => w.write("Eq"),
2066 I::Neq => w.write("Neq"),
2067 I::Lt => w.write("Lt"),
2068 I::Lte => w.write("Lte"),
2069 I::Gt => w.write("Gt"),
2070 I::Gte => w.write("Gte"),
2071 I::Cmp => w.write("Cmp"),
2072 I::BitAnd => w.write("BitAnd"),
2073 I::BitOr => w.write("BitOr"),
2074 I::BitXor => w.write("BitXor"),
2075 I::BitNot => w.write("BitNot"),
2076 I::Shl => w.write("Shl"),
2077 I::Shr => w.write("Shr"),
2078 I::CastBool => w.write("CastBool"),
2079 I::CastInt => w.write("CastInt"),
2080 I::CastDouble => w.write("CastDouble"),
2081 I::CastString => w.write("CastString"),
2082 I::CastVec => w.write("CastVec"),
2083 I::CastDict => w.write("CastDict"),
2084 I::CastKeyset => w.write("CastKeyset"),
2085 I::InstanceOf => w.write("InstanceOf"),
2086 I::InstanceOfD(id) => {
2087 w.write("InstanceOfD ")?;
2088 print_class_id(w, id)
2090 I::IsLateBoundCls => w.write("IsLateBoundCls"),
2091 I::IsTypeStructC(op) => concat_str_by(
2097 TypestructResolveOp::Resolve => "Resolve",
2098 TypestructResolveOp::DontResolve => "DontResolve",
2102 I::ThrowAsTypeStructException => w.write("ThrowAsTypeStructException"),
2103 I::CombineAndResolveTypeStruct(n) => concat_str_by(
2106 ["CombineAndResolveTypeStruct", n.to_string().as_str()],
2108 I::Print => w.write("Print"),
2109 I::Clone => w.write("Clone"),
2110 I::Exit => w.write("Exit"),
2111 I::ResolveFunc(id) => {
2112 w.write("ResolveFunc ")?;
2113 print_function_id(w, id)
2115 I::ResolveRFunc(id) => {
2116 w.write("ResolveRFunc ")?;
2117 print_function_id(w, id)
2119 I::ResolveMethCaller(id) => {
2120 w.write("ResolveMethCaller ")?;
2121 print_function_id(w, id)
2123 I::ResolveObjMethod => w.write("ResolveObjMethod"),
2124 I::ResolveClsMethod(mid) => {
2125 w.write("ResolveClsMethod ")?;
2126 print_method_id(w, mid)
2128 I::ResolveClsMethodD(cid, mid) => {
2129 w.write("ResolveClsMethodD ")?;
2130 print_class_id(w, cid)?;
2132 print_method_id(w, mid)
2134 I::ResolveClsMethodS(r, mid) => {
2135 w.write("ResolveClsMethodS ")?;
2136 print_special_cls_ref(w, r)?;
2138 print_method_id(w, mid)
2140 I::ResolveRClsMethod(mid) => {
2141 w.write("ResolveRClsMethod ")?;
2142 print_method_id(w, mid)
2144 I::ResolveRClsMethodD(cid, mid) => {
2145 w.write("ResolveRClsMethodD ")?;
2146 print_class_id(w, cid)?;
2148 print_method_id(w, mid)
2150 I::ResolveRClsMethodS(r, mid) => {
2151 w.write("ResolveRClsMethodS ")?;
2152 print_special_cls_ref(w, r)?;
2154 print_method_id(w, mid)
2156 I::ResolveClass(id) => {
2157 w.write("ResolveClass ")?;
2158 print_class_id(w, id)
2160 I::Fatal(fatal_op) => print_fatal_op(w, fatal_op),
2164 fn print_fatal_op<W: Write>(w: &mut W, f: &FatalOp) -> Result<(), W::Error> {
2166 FatalOp::Parse => w.write("Fatal Parse"),
2167 FatalOp::Runtime => w.write("Fatal Runtime"),
2168 FatalOp::RuntimeOmitFrame => w.write("Fatal RuntimeOmitFrame"),
2172 fn print_params<W: Write>(
2175 body_env: Option<&HhasBodyEnv>,
2176 params: &[HhasParam],
2177 ) -> Result<(), W::Error> {
2179 concat_by(w, ", ", params, |w, i| print_param(ctx, w, body_env, i))
2183 fn print_param<W: Write>(
2186 body_env: Option<&HhasBodyEnv>,
2188 ) -> Result<(), W::Error> {
2189 print_param_user_attributes(ctx, w, param)?;
2190 w.write_if(param.is_inout, "inout ")?;
2191 w.write_if(param.is_variadic, "...")?;
2192 option(w, ¶m.type_info, |w, ty| {
2193 print_type_info(w, ty)?;
2196 w.write(¶m.name)?;
2197 option(w, ¶m.default_value, |w, i| {
2198 print_param_default_value(ctx, w, body_env, i)
2202 fn print_param_id<W: Write>(w: &mut W, param_id: &ParamId) -> Result<(), W::Error> {
2204 ParamId::ParamUnnamed(i) => w.write(i.to_string()),
2205 ParamId::ParamNamed(s) => w.write(s),
2209 fn print_param_default_value<W: Write>(
2212 body_env: Option<&HhasBodyEnv>,
2213 default_val: &(Label, ast::Expr),
2214 ) -> Result<(), W::Error> {
2215 let expr_env = ExprEnv {
2216 codegen_env: body_env,
2219 print_label(w, &default_val.0)?;
2221 triple_quotes(w, |w| print_expr(ctx, w, &expr_env, &default_val.1))
2225 fn print_label<W: Write>(w: &mut W, label: &Label) -> Result<(), W::Error> {
2227 Label::Regular(id) => {
2231 Label::DefaultArg(id) => {
2238 fn print_local<W: Write>(w: &mut W, local: &Local) -> Result<(), W::Error> {
2240 Local::Unnamed(id) => {
2244 Local::Named(id) => w.write(id),
2248 fn print_int<W: Write>(w: &mut W, i: &usize) -> Result<(), W::Error> {
2252 fn print_key_value<W: Write>(
2258 ) -> Result<(), W::Error> {
2259 print_key_value_(ctx, w, env, k, print_expr, v)
2262 fn print_key_value_<W: Write, K, KeyPrinter>(
2269 ) -> Result<(), W::Error>
2271 KeyPrinter: FnMut(&mut Context, &mut W, &ExprEnv, K) -> Result<(), W::Error>,
2273 kp(ctx, w, env, k)?;
2275 print_expr(ctx, w, env, v)
2278 fn print_afield<W: Write>(
2282 afield: &ast::Afield,
2283 ) -> Result<(), W::Error> {
2284 use ast::Afield as A;
2286 A::AFvalue(e) => print_expr(ctx, w, env, &e),
2287 A::AFkvalue(k, v) => print_key_value(ctx, w, env, &k, &v),
2291 fn print_afields<W: Write>(
2295 afields: impl AsRef<[ast::Afield]>,
2296 ) -> Result<(), W::Error> {
2297 concat_by(w, ", ", afields, |w, i| print_afield(ctx, w, env, i))
2300 fn print_uop<W: Write>(w: &mut W, op: ast::Uop) -> Result<(), W::Error> {
2310 U::Upincr | U::Updecr => {
2311 return Err(Error::fail(
2312 "string_of_uop - should have been captures earlier",
2318 fn print_key_values<W: Write>(
2322 kvs: impl AsRef<[(ast::Expr, ast::Expr)]>,
2323 ) -> Result<(), W::Error> {
2324 print_key_values_(ctx, w, env, print_expr, kvs)
2327 fn print_key_values_<W: Write, K, KeyPrinter>(
2332 kvs: impl AsRef<[(K, ast::Expr)]>,
2333 ) -> Result<(), W::Error>
2335 KeyPrinter: Fn(&mut Context, &mut W, &ExprEnv, &K) -> Result<(), W::Error>,
2337 concat_by(w, ", ", kvs, |w, (k, v)| {
2338 print_key_value_(ctx, w, env, k, &mut kp, v)
2342 fn print_expr_darray<W: Write, K, KeyPrinter>(
2347 kvs: impl AsRef<[(K, ast::Expr)]>,
2348 ) -> Result<(), W::Error>
2350 KeyPrinter: Fn(&mut Context, &mut W, &ExprEnv, &K) -> Result<(), W::Error>,
2352 wrap_by_(w, "darray[", "]", |w| {
2353 print_key_values_(ctx, w, env, kp, kvs)
2357 fn print_expr_varray<W: Write>(
2361 varray: &[ast::Expr],
2362 ) -> Result<(), W::Error> {
2363 wrap_by_(w, "varray[", "]", |w| {
2364 concat_by(w, ", ", varray, |w, e| print_expr(ctx, w, env, e))
2368 fn print_shape_field_name<W: Write>(
2372 field: &ast::ShapeFieldName,
2373 ) -> Result<(), W::Error> {
2374 use ast::ShapeFieldName as S;
2376 S::SFlitInt((_, s)) => print_expr_int(w, s.as_ref()),
2377 S::SFlitStr((_, s)) => print_expr_string(w, s),
2378 S::SFclassConst(_, (_, s)) => print_expr_string(w, s.as_bytes()),
2382 fn print_expr_int<W: Write>(w: &mut W, i: &str) -> Result<(), W::Error> {
2383 match integer::to_decimal(i) {
2384 Ok(s) => w.write(s),
2385 Err(_) => Err(Error::fail("ParseIntError")),
2389 fn print_expr_string<W: Write>(w: &mut W, s: &[u8]) -> Result<(), W::Error> {
2390 fn escape_char(c: u8) -> Option<Cow<'static, [u8]>> {
2392 b'\n' => Some((&b"\\\\n"[..]).into()),
2393 b'\r' => Some((&b"\\\\r"[..]).into()),
2394 b'\t' => Some((&b"\\\\t"[..]).into()),
2395 b'\\' => Some((&b"\\\\\\\\"[..]).into()),
2396 b'"' => Some((&b"\\\\\\\""[..]).into()),
2397 b'$' => Some((&b"\\\\$"[..]).into()),
2398 c if is_lit_printable(c) => None,
2401 write!(r, "\\\\{:03o}", c).unwrap();
2406 // FIXME: This is not safe--string literals are binary strings.
2407 // There's no guarantee that they're valid UTF-8.
2408 let s = unsafe { std::str::from_utf8_unchecked(s) };
2409 wrap_by(w, "\\\"", |w| w.write(escape_by(s.into(), escape_char)))
2412 fn print_expr_to_string<W: Write>(
2416 ) -> Result<String, W::Error> {
2417 let mut buf = String::new();
2418 print_expr(ctx, &mut buf, env, expr).map_err(|e| match e {
2419 Error::NotImpl(m) => Error::NotImpl(m),
2420 _ => Error::Fail(format!("Failed: {}", e)),
2425 fn print_expr<W: Write>(
2429 ast::Expr(_, _, expr): &ast::Expr,
2430 ) -> Result<(), W::Error> {
2431 fn adjust_id<'a>(env: &ExprEnv, id: &'a str) -> Cow<'a, str> {
2432 let s: Cow<'a, str> = match env.codegen_env {
2434 if env.is_namespaced
2438 .rposition(|c| *c == b'\\')
2439 .map_or(true, |i| i < 1)
2441 strip_global_ns(id).into()
2450 fn print_expr_id<'a, W: Write>(w: &mut W, env: &ExprEnv, s: &'a str) -> Result<(), W::Error> {
2451 w.write(adjust_id(env, s))
2453 fn fmt_class_name<'a>(is_class_constant: bool, id: Cow<'a, str>) -> Cow<'a, str> {
2454 let cn: Cow<'a, str> = if is_xhp(strip_global_ns(&id)) {
2455 escaper::escape(strip_global_ns(&mangle(id.into())))
2459 escaper::escape(strip_global_ns(&id)).to_string().into()
2461 if is_class_constant {
2462 format!("\\\\{}", cn).into()
2467 fn get_class_name_from_id<'e>(
2469 env: Option<&'e HhasBodyEnv>,
2470 should_format: bool,
2471 is_class_constant: bool,
2474 if id == classes::SELF || id == classes::PARENT || id == classes::STATIC {
2475 let name = ctx.special_class_resolver.resolve(env, id);
2476 return fmt_class_name(is_class_constant, name);
2478 fn get<'a>(should_format: bool, is_class_constant: bool, id: &'a str) -> Cow<'a, str> {
2480 fmt_class_name(is_class_constant, id.into())
2487 let alloc = bumpalo::Bump::new();
2488 let class_id = class::ClassType::from_ast_name(&alloc, id);
2489 let id = class_id.to_raw_string();
2490 get(should_format, is_class_constant, id)
2494 get(should_format, is_class_constant, id)
2497 fn handle_possible_colon_colon_class_expr<W: Write>(
2503 ) -> Result<Option<()>, W::Error> {
2504 match e_.as_class_const() {
2506 ast::ClassId(_, _, ast::ClassId_::CIexpr(ast::Expr(_, _, ast::Expr_::Id(id)))),
2508 )) if is_class(&s2) && !(is_self(&id.1) || is_parent(&id.1) || is_static(&id.1)) => {
2510 let s1 = get_class_name_from_id(ctx, env.codegen_env, false, false, &id.1);
2512 print_expr_id(w, env, s1.as_ref())?
2514 print_expr_string(w, s1.as_bytes())?
2521 use ast::Expr_ as E_;
2523 E_::Id(id) => print_expr_id(w, env, id.1.as_ref()),
2524 E_::Lvar(lid) => w.write(escaper::escape(&(lid.1).1)),
2526 if f.contains('E') || f.contains('e') {
2530 .map_err(|_| Error::fail(format!("ParseFloatError: {}", f)))?
2532 // to_uppercase() here because s might be "inf" or "nan"
2536 static ref UNSIGNED_EXP: Regex =
2537 Regex::new(r"(?P<first>E)(?P<second>\d+)").unwrap();
2538 static ref SIGNED_SINGLE_DIGIT_EXP: Regex =
2539 Regex::new(r"(?P<first>E[+-])(?P<second>\d$)").unwrap();
2541 // turn mEn into mE+n
2542 let s = UNSIGNED_EXP.replace(&s, "${first}+${second}");
2543 // turn mE+n or mE-n into mE+0n or mE-0n (where n is a single digit)
2544 let s = SIGNED_SINGLE_DIGIT_EXP.replace(&s, "${first}0${second}");
2550 E_::Int(i) => print_expr_int(w, i.as_ref()),
2551 E_::String(s) => print_expr_string(w, s),
2552 E_::Null => w.write("NULL"),
2553 E_::True => w.write("true"),
2554 E_::False => w.write("false"),
2555 // For arrays and collections, we are making a conscious decision to not
2556 // match HHMV has HHVM's emitter has inconsistencies in the pretty printer
2557 // https://fburl.com/tzom2qoe
2558 E_::Collection(c) if (c.0).1 == "vec" || (c.0).1 == "dict" || (c.0).1 == "keyset" => {
2560 square(w, |w| print_afields(ctx, w, env, &c.2))
2562 E_::Collection(c) => {
2563 let name = strip_ns((c.0).1.as_str());
2564 let name = types::fix_casing(&name);
2566 "Set" | "Pair" | "Vector" | "Map" | "ImmSet" | "ImmVector" | "ImmMap" => {
2569 wrap_by_(w, " {", "}", |w| {
2570 Ok(if !c.2.is_empty() {
2572 print_afields(ctx, w, env, &c.2)?;
2577 _ => Err(Error::fail(format!(
2578 "Default value for an unknow collection - {}",
2583 E_::Shape(fl) => print_expr_darray(ctx, w, env, print_shape_field_name, fl),
2585 let (bop, e1, e2) = &**x;
2586 print_expr(ctx, w, env, e1)?;
2590 print_expr(ctx, w, env, e2)
2593 let (e, _, es, unpacked_element) = &**c;
2595 Some(ast_defs::Id(_, call_id)) => {
2596 w.write(lstrip(adjust_id(env, &call_id).as_ref(), "\\\\"))?
2599 let buf = print_expr_to_string::<W>(ctx, env, e)?;
2600 w.write(lstrip(&buf, "\\\\"))?
2604 concat_by(w, ", ", &es, |w, e| print_expr(ctx, w, env, e))?;
2605 match unpacked_element {
2611 // TODO: Should probably have ... also but we are not doing that in ocaml
2612 print_expr(ctx, w, env, e)
2618 let (cid, _, es, unpacked_element, _) = &**x;
2619 match cid.2.as_ciexpr() {
2622 match ci_expr.2.as_id() {
2623 Some(ast_defs::Id(_, cname)) => w.write(lstrip(
2626 &class::ClassType::from_ast_name(&bumpalo::Bump::new(), cname)
2632 let buf = print_expr_to_string::<W>(ctx, env, ci_expr)?;
2633 w.write(lstrip(&buf, "\\\\"))?
2637 concat_by(w, ", ", es, |w, e| print_expr(ctx, w, env, e))?;
2638 match unpacked_element {
2642 print_expr(ctx, w, env, e)
2648 match cid.2.as_ci() {
2650 // Xml exprs rewritten as New exprs come
2652 print_xml(ctx, w, env, &id.1, es)
2654 None => not_impl!(),
2660 w.write(lstrip(adjust_id(env, &(r.0).1).as_ref(), "\\\\"))?;
2661 print_key_values(ctx, w, env, &r.1)
2663 E_::ClassGet(cg) => {
2665 ast::ClassId_::CIexpr(e) => match e.as_id() {
2666 Some(id) => w.write(&get_class_name_from_id(
2669 true, /* should_format */
2670 false, /* is_class_constant */
2673 _ => print_expr(ctx, w, env, e)?,
2675 _ => return Err(Error::fail("TODO Unimplemented unexpected non-CIexpr")),
2679 ast::ClassGetExpr::CGstring((_, litstr)) => w.write(escaper::escape(litstr)),
2680 ast::ClassGetExpr::CGexpr(e) => print_expr(ctx, w, env, e),
2683 E_::ClassConst(cc) => {
2684 if let Some(e1) = (cc.0).2.as_ciexpr() {
2685 handle_possible_colon_colon_class_expr(ctx, w, env, false, expr)?.map_or_else(
2688 match e1.2.as_id() {
2689 Some(ast_defs::Id(_, s1)) => {
2691 get_class_name_from_id(ctx, env.codegen_env, true, true, s1);
2692 concat_str_by(w, "::", [&s1.into(), s2])
2695 print_expr(ctx, w, env, e1)?;
2704 Err(Error::fail("TODO: Only expected CIexpr in class_const"))
2707 E_::Unop(u) => match u.0 {
2708 ast::Uop::Upincr => {
2709 print_expr(ctx, w, env, &u.1)?;
2712 ast::Uop::Updecr => {
2713 print_expr(ctx, w, env, &u.1)?;
2718 print_expr(ctx, w, env, &u.1)
2722 print_expr(ctx, w, env, &og.0)?;
2723 w.write(match og.2 {
2724 ast::OgNullFlavor::OGNullthrows => "->",
2725 ast::OgNullFlavor::OGNullsafe => "?->",
2727 print_expr(ctx, w, env, &og.1)
2731 print_expr(ctx, w, env, e)
2733 E_::ArrayGet(ag) => {
2734 print_expr(ctx, w, env, &ag.0)?;
2736 option(w, &ag.1, |w, e: &ast::Expr| {
2737 handle_possible_colon_colon_class_expr(ctx, w, env, true, &e.2)
2739 .unwrap_or_else(|| print_expr(ctx, w, env, e))
2743 E_::String2(ss) => concat_by(w, " . ", ss, |w, s| print_expr(ctx, w, env, s)),
2744 E_::PrefixedString(s) => {
2747 print_expr(ctx, w, env, &s.1)
2750 print_expr(ctx, w, env, &eif.0)?;
2752 option(w, &eif.1, |w, etrue| print_expr(ctx, w, env, etrue))?;
2754 print_expr(ctx, w, env, &eif.2)
2757 paren(w, |w| print_hint(w, false, &c.0))?;
2758 print_expr(ctx, w, env, &c.1)
2761 print_expr(ctx, w, env, &p.1)?;
2763 print_expr(ctx, w, env, &p.2)
2766 print_expr(ctx, w, env, &i.0)?;
2768 print_hint(w, true, &i.1)
2771 print_expr(ctx, w, env, &a.0)?;
2772 w.write(if a.2 { " ?as " } else { " as " })?;
2773 print_hint(w, true, &a.1)
2775 E_::Varray(va) => print_expr_varray(ctx, w, env, &va.1),
2776 E_::Darray(da) => print_expr_darray(ctx, w, env, print_expr, &da.1),
2777 E_::Tuple(t) => wrap_by_(w, "varray[", "]", |w| {
2778 // A tuple is represented by a varray when using reflection.
2779 concat_by(w, ", ", t, |w, i| print_expr(ctx, w, env, i))
2781 E_::List(l) => wrap_by_(w, "list(", ")", |w| {
2782 concat_by(w, ", ", l, |w, i| print_expr(ctx, w, env, i))
2786 print_afield(ctx, w, env, y)
2790 print_expr(ctx, w, env, e)
2793 print_import_flavor(w, &i.0)?;
2795 print_expr(ctx, w, env, &i.1)
2797 E_::Xml(_) => Err(Error::fail(
2798 "expected Xml to be converted to New during rewriting",
2800 E_::Efun(f) => print_efun(ctx, w, env, &f.0, &f.1),
2801 E_::FunctionPointer(fp) => {
2802 let (fp_id, targs) = &**fp;
2804 ast::FunctionPtrId::FPId(ast::Id(_, sid)) => {
2805 w.write(lstrip(adjust_id(env, &sid).as_ref(), "\\\\"))?
2807 ast::FunctionPtrId::FPClassConst(ast::ClassId(_, _, class_id), (_, meth_name)) => {
2809 ast::ClassId_::CIexpr(e) => match e.as_id() {
2810 Some(id) => w.write(&get_class_name_from_id(
2813 true, /* should_format */
2814 false, /* is_class_constant */
2817 _ => print_expr(ctx, w, env, e)?,
2820 return Err(Error::fail(
2821 "TODO Unimplemented unexpected non-CIexpr in function pointer",
2829 wrap_by_(w, "<", ">", |w| {
2830 concat_by(w, ", ", targs, |w, _targ| w.write("_"))
2833 E_::Omitted => Ok(()),
2835 if ctx.dump_lambdas {
2839 concat_by(w, ", ", &fun_.params, |w, param| {
2840 print_fparam(ctx, w, env, param)
2844 print_block_(ctx, w, env, &fun_.body.ast, None)
2848 "expected Lfun to be converted to Efun during closure conversion print_expr",
2852 E_::Callconv(_) => Err(Error::fail("illegal default value")),
2853 E_::ETSplice(splice) => {
2855 print_expr(ctx, w, env, splice)?;
2858 _ => Err(Error::fail(format!(
2859 "TODO Unimplemented: Cannot print: {:?}",
2865 fn print_xml<W: Write>(
2871 ) -> Result<(), W::Error> {
2872 use ast::{Expr as E, Expr_ as E_};
2874 fn syntax_error<W: Write>(_: &W) -> crate::write::Error<<W as crate::write::Write>::Error> {
2875 Error::NotImpl(String::from("print_xml: unexpected syntax"))
2877 fn print_xhp_attr<W: Write>(
2881 attr: &(ast_defs::ShapeFieldName, ast::Expr),
2882 ) -> Result<(), W::Error> {
2884 (ast_defs::ShapeFieldName::SFlitStr(s), e) => print_key_value_(
2889 |_, w, _, k| print_expr_string(w, k.as_slice()),
2892 _ => Err(syntax_error(w)),
2896 let (attrs, children) = if es.len() < 2 {
2897 Err(syntax_error(w))
2899 match (&es[0], &es[1]) {
2900 (E(_, _, E_::Shape(attrs)), E(_, _, E_::Varray(children))) => Ok((attrs, &children.1)),
2901 _ => Err(syntax_error(w)),
2905 codegen_env: env.codegen_env,
2907 write!(w, "new {}", mangle(id.into()))?;
2909 wrap_by_(w, "darray[", "]", |w| {
2910 concat_by(w, ", ", attrs, |w, attr| print_xhp_attr(ctx, w, &env, attr))
2913 print_expr_varray(ctx, w, &env, children)?;
2914 w.write(", __FILE__, __LINE__")
2918 fn print_efun<W: Write>(
2923 use_list: &[ast::Lid],
2924 ) -> Result<(), W::Error> {
2926 f.fun_kind.is_fasync() || f.fun_kind.is_fasync_generator(),
2929 w.write("function ")?;
2931 concat_by(w, ", ", &f.params, |w, p| print_fparam(ctx, w, env, p))
2934 if !use_list.is_empty() {
2937 concat_by(w, ", ", use_list, |w: &mut W, ast::Lid(_, id)| {
2938 w.write(local_id::get_name(id))
2943 print_block_(ctx, w, env, &f.body.ast, None)
2946 fn print_block<W: Write>(
2950 block: &[ast::Stmt],
2951 ident: Option<&str>,
2952 ) -> Result<(), W::Error> {
2954 [] | [ast::Stmt(_, ast::Stmt_::Noop)] => Ok(()),
2955 [ast::Stmt(_, ast::Stmt_::Block(b))] if b.len() == 1 => print_block_(ctx, w, env, b, ident),
2956 [_, _, ..] => print_block_(ctx, w, env, block, ident),
2957 [stmt] => print_statement(ctx, w, env, stmt, None),
2961 fn print_block_<W: Write>(
2965 block: &[ast::Stmt],
2966 ident: Option<&str>,
2967 ) -> Result<(), W::Error> {
2968 wrap_by_(w, "{\\n", "}\\n", |w| {
2969 concat(w, block, |w, stmt| {
2970 option(w, ident, |w, i: &str| w.write(i))?;
2971 print_statement(ctx, w, env, stmt, Some(" "))
2973 option(w, ident, |w, i: &str| w.write(i))
2977 fn print_statement<W: Write>(
2982 ident: Option<&str>,
2983 ) -> Result<(), W::Error> {
2984 use ast::Stmt_ as S_;
2986 S_::Return(expr) => {
2987 option(w, ident, |w, i: &str| w.write(i))?;
2988 wrap_by_(w, "return", ";\\n", |w| {
2989 option(w, &**expr, |w, e| {
2991 print_expr(ctx, w, env, e)
2996 option(w, ident, |w, i: &str| w.write(i))?;
2997 print_expr(ctx, w, env, &**expr)?;
3000 S_::Throw(expr) => {
3001 option(w, ident, |w, i: &str| w.write(i))?;
3002 wrap_by_(w, "throw ", ";\\n", |w| print_expr(ctx, w, env, &**expr))
3005 option(w, ident, |w, i: &str| w.write(i))?;
3006 w.write("break;\\n")
3009 option(w, ident, |w, i: &str| w.write(i))?;
3010 w.write("continue;\\n")
3013 let (cond, block) = &**x;
3014 option(w, ident, |w, i: &str| w.write(i))?;
3015 wrap_by_(w, "while (", ") ", |w| print_expr(ctx, w, env, cond))?;
3016 print_block(ctx, w, env, block.as_ref(), ident)
3019 let (cond, if_block, else_block) = &**x;
3020 option(w, ident, |w, i: &str| w.write(i))?;
3021 wrap_by_(w, "if (", ") ", |w| print_expr(ctx, w, env, cond))?;
3022 print_block(ctx, w, env, if_block, ident)?;
3023 let mut buf = String::new();
3024 print_block(ctx, &mut buf, env, else_block, ident).map_err(|e| match e {
3025 Error::NotImpl(m) => Error::NotImpl(m),
3026 _ => Error::Fail(format!("Failed: {}", e)),
3028 w.write_if(!buf.is_empty(), " else ")?;
3029 w.write_if(!buf.is_empty(), buf)
3031 S_::Block(block) => {
3032 option(w, ident, |w, i: &str| w.write(i))?;
3033 print_block_(ctx, w, env, block, ident)
3036 /* TODO(T29869930) */
3037 _ => w.write("TODO Unimplemented NYI: Default value printing"),
3041 fn print_fparam<W: Write>(
3045 param: &ast::FunParam,
3046 ) -> Result<(), W::Error> {
3047 if let Some(ast_defs::ParamKind::Pinout) = param.callconv {
3050 if param.is_variadic {
3053 option(w, &(param.type_hint).1, |w, h| {
3054 print_hint(w, true, h)?;
3057 w.write(¶m.name)?;
3058 option(w, ¶m.expr, |w, e| {
3060 print_expr(ctx, w, env, e)
3064 fn print_bop<W: Write>(w: &mut W, bop: &ast_defs::Bop) -> Result<(), W::Error> {
3067 Bop::Plus => w.write("+"),
3068 Bop::Minus => w.write("-"),
3069 Bop::Star => w.write("*"),
3070 Bop::Slash => w.write("/"),
3071 Bop::Eqeq => w.write("=="),
3072 Bop::Eqeqeq => w.write("==="),
3073 Bop::Starstar => w.write("**"),
3074 Bop::Eq(None) => w.write("="),
3075 Bop::Eq(Some(bop)) => {
3079 Bop::Ampamp => w.write("&&"),
3080 Bop::Barbar => w.write("||"),
3081 Bop::Lt => w.write("<"),
3082 Bop::Lte => w.write("<="),
3083 Bop::Cmp => w.write("<=>"),
3084 Bop::Gt => w.write(">"),
3085 Bop::Gte => w.write(">="),
3086 Bop::Dot => w.write("."),
3087 Bop::Amp => w.write("&"),
3088 Bop::Bar => w.write("|"),
3089 Bop::Ltlt => w.write("<<"),
3090 Bop::Gtgt => w.write(">>"),
3091 Bop::Percent => w.write("%"),
3092 Bop::Xor => w.write("^"),
3093 Bop::Diff => w.write("!="),
3094 Bop::Diff2 => w.write("!=="),
3095 Bop::QuestionQuestion => w.write("??"),
3099 fn print_hint<W: Write>(w: &mut W, ns: bool, hint: &ast::Hint) -> Result<(), W::Error> {
3100 let alloc = bumpalo::Bump::new();
3101 let h = emit_type_hint::fmt_hint(&alloc, &[], false, hint).map_err(|e| match e {
3102 Unrecoverable(s) => Error::fail(s),
3103 _ => Error::fail("Error printing hint"),
3106 w.write(escaper::escape(h))
3108 w.write(escaper::escape(strip_ns(&h)))
3112 fn print_import_flavor<W: Write>(w: &mut W, flavor: &ast::ImportFlavor) -> Result<(), W::Error> {
3113 use ast::ImportFlavor as F;
3114 w.write(match flavor {
3115 F::Include => "include",
3116 F::Require => "require",
3117 F::IncludeOnce => "include_once",
3118 F::RequireOnce => "require_once",
3122 fn print_param_user_attributes<W: Write>(
3126 ) -> Result<(), W::Error> {
3127 match ¶m.user_attributes[..] {
3129 _ => square(w, |w| print_attributes(ctx, w, ¶m.user_attributes)),
3133 fn print_span<W: Write>(w: &mut W, &Span(line_begin, line_end): &Span) -> Result<(), W::Error> {
3134 write!(w, "({},{})", line_begin, line_end)
3137 fn print_fun_attrs<W: Write>(
3141 ) -> Result<(), W::Error> {
3142 use hhas_attribute::*;
3143 let user_attrs = &f.attributes;
3144 let mut special_attrs = vec![];
3145 if has_meth_caller(user_attrs) {
3146 special_attrs.push("builtin");
3147 special_attrs.push("is_meth_caller");
3149 if f.is_interceptable() {
3150 special_attrs.push("interceptable");
3152 if has_foldable(user_attrs) {
3153 special_attrs.push("foldable");
3155 if has_provenance_skip_frame(user_attrs) {
3156 special_attrs.push("prov_skip_frame");
3158 if f.is_no_injection() {
3159 special_attrs.push("no_injection");
3161 if ctx.is_system_lib() || (has_dynamically_callable(user_attrs) && !f.is_memoize_impl()) {
3162 special_attrs.push("dyn_callable")
3164 if ctx.is_system_lib() {
3165 special_attrs.push("unique");
3166 special_attrs.push("builtin");
3167 special_attrs.push("persistent");
3169 print_special_and_user_attrs(ctx, w, &special_attrs, user_attrs)
3172 fn print_special_and_user_attrs<W: Write>(
3176 users: &[HhasAttribute],
3177 ) -> Result<(), W::Error> {
3178 if !users.is_empty() || !specials.is_empty() {
3180 concat_str_by(w, " ", specials)?;
3181 if !specials.is_empty() && !users.is_empty() {
3184 print_attributes(ctx, w, users)
3191 fn print_upper_bounds<'arena, W: Write>(
3193 ubs: impl AsRef<[(String, Vec<HhasTypeInfo<'arena>>)]>,
3194 ) -> Result<(), W::Error> {
3195 braces(w, |w| concat_by(w, ", ", ubs, print_upper_bound))
3198 fn print_upper_bound<W: Write>(
3200 (id, tys): &(String, Vec<HhasTypeInfo>),
3201 ) -> Result<(), W::Error> {
3203 concat_str_by(w, " ", [id.as_str(), "as", ""])?;
3204 concat_by(w, ", ", &tys, print_type_info)
3208 fn print_type_info<W: Write>(w: &mut W, ti: &HhasTypeInfo) -> Result<(), W::Error> {
3209 print_type_info_(w, false, ti)
3212 fn print_type_flags<W: Write>(
3214 flag: constraint::ConstraintFlags,
3215 ) -> Result<(), W::Error> {
3216 let mut first = true;
3217 let mut print_space = |w: &mut W| -> Result<(), W::Error> {
3224 use constraint::ConstraintFlags as F;
3225 if flag.contains(F::DISPLAY_NULLABLE) {
3227 w.write("display_nullable")?;
3229 if flag.contains(F::EXTENDED_HINT) {
3231 w.write("extended_hint")?;
3233 if flag.contains(F::NULLABLE) {
3235 w.write("nullable")?;
3238 if flag.contains(F::SOFT) {
3242 if flag.contains(F::TYPE_CONSTANT) {
3244 w.write("type_constant")?;
3247 if flag.contains(F::TYPE_VAR) {
3249 w.write("type_var")?;
3252 if flag.contains(F::UPPERBOUND) {
3254 w.write("upper_bound")?;
3259 fn print_type_info_<W: Write>(w: &mut W, is_enum: bool, ti: &HhasTypeInfo) -> Result<(), W::Error> {
3260 let print_quote_str = |w: &mut W, opt: &Option<String>| {
3264 |w, s: &String| quotes(w, |w| w.write(escape(s))),
3271 &Option::from(ti.user_type.map(|n| n.as_str().to_owned())),
3277 &Option::from(ti.type_constraint.name.map(|n| n.as_str().to_owned())),
3281 print_type_flags(w, ti.type_constraint.flags)
3285 fn print_typedef_info<W: Write>(w: &mut W, ti: &HhasTypeInfo) -> Result<(), W::Error> {
3287 w.write(quote_string(
3288 ti.type_constraint.name.as_ref().map_or("", |n| n.as_str()),
3290 let flags = ti.type_constraint.flags & constraint::ConstraintFlags::NULLABLE;
3291 if !flags.is_empty() {
3292 wrap_by(w, " ", |w| {
3295 ti.type_constraint.flags & constraint::ConstraintFlags::NULLABLE,
3303 fn print_extends<W: Write>(w: &mut W, base: Option<&str>) -> Result<(), W::Error> {
3306 Some(b) => concat_str_by(w, " ", [" extends", b]),
3310 fn print_record_field<W: Write>(
3313 Field(name, type_info, intial_value): &Field,
3314 ) -> Result<(), W::Error> {
3316 w.write(".property ")?;
3317 match intial_value {
3318 Some(_) => w.write("[public] ")?,
3319 None => w.write("[public sys_initial_val] ")?,
3321 print_type_info(w, type_info)?;
3322 concat_str_by(w, " ", ["", name, "="])?;
3324 ctx.block(w, |c, w| {
3326 match intial_value {
3327 None => w.write("uninit")?,
3328 Some(value) => triple_quotes(w, |w| print_adata(c, w, value))?,
3334 fn print_record_def<W: Write>(
3337 record: &HhasRecord,
3338 ) -> Result<(), W::Error> {
3340 if record.is_abstract {
3341 concat_str_by(w, " ", [".record", record.name.to_raw_string()])?;
3343 concat_str_by(w, " ", [".record", "[final]", record.name.to_raw_string()])?;
3346 print_span(w, &record.span)?;
3347 print_extends(w, record.base.as_ref().map(|b| b.to_raw_string()))?;
3351 ctx.block(w, |c, w| {
3352 concat(w, &record.fields, |w, rf| print_record_field(c, w, rf))
3359 /// Convert an `Expr` to a `String` of the equivalent source code.
3361 /// This is a debugging tool abusing a printer written for bytecode
3362 /// emission. It does not support all Hack expressions, and panics
3363 /// on unsupported syntax.
3365 /// If you have an `Expr` with positions, you are much better off
3366 /// getting the source code at those positions rather than using this.
3367 pub fn expr_to_string_lossy(mut ctx: Context, expr: &ast::Expr) -> String {
3368 ctx.dump_lambdas = true;
3370 let env = ExprEnv { codegen_env: None };
3371 let mut escaped_src = String::new();
3372 print_expr(&mut ctx, &mut escaped_src, &env, expr).expect("Printing failed");
3374 let bs = escaper::unescape_double(&escaped_src).expect("Unescaping failed");
3375 let s = String::from_utf8_lossy(&bs);