language
stringlengths 0
24
| filename
stringlengths 9
214
| code
stringlengths 99
9.93M
|
---|---|---|
Rust | hhvm/hphp/hack/src/hackc/emitter/emit_statement.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 emit_pos::emit_pos_then;
use env::emitter::Emitter;
use env::Env;
use error::Error;
use error::Result;
use ffi::Slice;
use hack_macros::hack_expr;
use hhbc::FCallArgs;
use hhbc::FCallArgsFlags;
use hhbc::IsTypeOp;
use hhbc::IterArgs;
use hhbc::Label;
use hhbc::Local;
use hhbc::MOpMode;
use hhbc::MemberKey;
use hhbc::QueryMOp;
use hhbc::ReadonlyOp;
use hhbc::SetRangeOp;
use instruction_sequence::instr;
use instruction_sequence::InstrSeq;
use lazy_static::lazy_static;
use naming_special_names_rust::special_idents;
use naming_special_names_rust::superglobals;
use oxidized::aast as a;
use oxidized::ast;
use oxidized::ast_defs;
use oxidized::local_id;
use oxidized::pos::Pos;
use regex::Regex;
use statement_state::StatementState;
use crate::emit_expression::emit_await;
use crate::emit_expression::emit_expr;
use crate::emit_expression::LValOp;
use crate::emit_expression::SetRange;
use crate::emit_expression::{self as emit_expr};
use crate::emit_fatal;
use crate::try_finally_rewriter as tfr;
// Expose a mutable ref to state for emit_body so that it can set it appropriately
pub(crate) fn set_state<'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
state: StatementState<'arena>,
) {
*e.statement_state_mut() = state;
}
// Wrapper functions
fn emit_return<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
) -> Result<InstrSeq<'arena>> {
tfr::emit_return(e, false, env)
}
fn is_readonly_expr(e: &ast::Expr) -> bool {
match &e.2 {
ast::Expr_::ReadonlyExpr(_) => true,
_ => false,
}
}
fn set_bytes_kind(name: &str) -> Option<SetRange> {
lazy_static! {
static ref RE: Regex =
Regex::new(r#"(?i)^hh\\set_bytes(_rev)?_([a-z0-9]+)(_vec)?$"#).unwrap();
}
RE.captures(name).and_then(|groups| {
let op = if groups.get(1).is_some() {
// == _rev
SetRangeOp::Reverse
} else {
SetRangeOp::Forward
};
let kind = groups.get(2).unwrap().as_str();
let vec = groups.get(3).is_some(); // == _vec
if kind == "string" && !vec {
Some(SetRange {
size: 1,
vec: true,
op,
})
} else {
let size = match kind {
"bool" | "int8" => 1,
"int16" => 2,
"int32" | "float32" => 4,
"int64" | "float64" => 8,
_ => return None,
};
Some(SetRange { size, vec, op })
}
})
}
pub fn emit_stmt<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
stmt: &ast::Stmt,
) -> Result<InstrSeq<'arena>> {
let pos = &stmt.0;
match &stmt.1 {
a::Stmt_::YieldBreak => emit_yieldbreak(e, env, pos),
a::Stmt_::Expr(e_) => match &e_.2 {
a::Expr_::Await(a) => emit_await_(e, env, e_, pos, a),
a::Expr_::Call(c) => emit_call(e, env, e_, pos, c),
a::Expr_::Binop(bop) => emit_binop(e, env, e_, pos, bop),
_ => emit_expr::emit_ignored_expr(e, env, pos, e_),
},
a::Stmt_::Return(r_opt) => emit_return_(e, env, (**r_opt).as_ref(), pos),
a::Stmt_::Block(b) => emit_block(env, e, b),
a::Stmt_::If(f) => emit_if(e, env, pos, &f.0, &f.1, &f.2),
a::Stmt_::While(x) => emit_while(e, env, &x.0, &x.1),
a::Stmt_::Using(x) => emit_using(e, env, x),
a::Stmt_::Break => Ok(emit_break(e, env, pos)),
a::Stmt_::Continue => Ok(emit_continue(e, env, pos)),
a::Stmt_::Do(x) => emit_do(e, env, &x.0, &x.1),
a::Stmt_::For(x) => emit_for(e, env, &x.0, x.1.as_ref(), &x.2, &x.3),
a::Stmt_::Throw(x) => emit_throw(e, env, x, pos),
a::Stmt_::Try(x) => emit_try(e, env, x, pos),
a::Stmt_::Switch(x) => emit_switch(e, env, pos, &x.0, &x.1, &x.2),
a::Stmt_::Foreach(x) => emit_foreach(e, env, pos, &x.0, &x.1, &x.2),
a::Stmt_::Awaitall(x) => emit_awaitall(e, env, pos, &x.0, &x.1),
a::Stmt_::Markup(x) => emit_markup(e, env, x, false),
a::Stmt_::Fallthrough | a::Stmt_::Noop => Ok(instr::empty()),
a::Stmt_::AssertEnv(_) => Ok(instr::empty()),
a::Stmt_::DeclareLocal(x) => emit_declare_local(e, env, pos, &x.0, &x.2),
a::Stmt_::Match(..) => todo!("TODO(jakebailey): match statements"),
}
}
fn emit_await_<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
e_: &ast::Expr,
_pos: &Pos,
a: &ast::Expr,
) -> Result<InstrSeq<'arena>> {
Ok(InstrSeq::gather(vec![
emit_await(e, env, &e_.1, a)?,
instr::pop_c(),
]))
}
fn emit_binop<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
e_: &ast::Expr,
pos: &Pos,
bop: &ast::Binop,
) -> Result<InstrSeq<'arena>> {
if let ast::Binop {
bop: ast_defs::Bop::Eq(None),
lhs,
rhs,
} = bop
{
if let Some(e_await) = rhs.2.as_await() {
let await_pos = &rhs.1;
if let Some(l) = lhs.2.as_list() {
let awaited_instrs = emit_await(e, env, await_pos, e_await)?;
let has_elements = l.iter().any(|e| !e.2.is_omitted());
if has_elements {
scope::with_unnamed_local(e, |e, temp| {
let (init, assign) = emit_expr::emit_lval_op_list(
e,
env,
pos,
Some(&temp),
&[],
lhs,
false,
is_readonly_expr(rhs),
)?;
Ok((
InstrSeq::gather(vec![awaited_instrs, instr::pop_l(temp)]),
InstrSeq::gather(vec![init, assign]),
instr::unset_l(temp),
))
})
} else {
Ok(InstrSeq::gather(vec![awaited_instrs, instr::pop_c()]))
}
} else {
emit_await_assignment(e, env, await_pos, lhs, e_await)
}
} else {
emit_expr::emit_ignored_expr(e, env, pos, e_)
}
} else {
emit_expr::emit_ignored_expr(e, env, pos, e_)
}
}
fn emit_yieldbreak<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
_pos: &Pos,
) -> Result<InstrSeq<'arena>> {
Ok(InstrSeq::gather(vec![instr::null(), emit_return(e, env)?]))
}
fn emit_try<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
x: &(ast::Block, Vec<ast::Catch>, ast::FinallyBlock),
pos: &Pos,
) -> Result<InstrSeq<'arena>> {
let (try_block, catch_list, finally_block) = x;
if catch_list.is_empty() {
emit_try_finally(e, env, pos, try_block, finally_block)
} else if finally_block.is_empty() {
emit_try_catch(e, env, pos, try_block, &catch_list[..])
} else {
emit_try_catch_finally(e, env, pos, try_block, &catch_list[..], finally_block)
}
}
fn emit_throw<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
x: &ast::Expr,
pos: &Pos,
) -> Result<InstrSeq<'arena>> {
Ok(InstrSeq::gather(vec![
emit_expr::emit_expr(e, env, x)?,
emit_pos(pos),
instr::throw(),
]))
}
fn emit_return_<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
r_opt: Option<&ast::Expr>,
pos: &Pos,
) -> Result<InstrSeq<'arena>> {
match r_opt {
Some(r) => {
let ret = emit_return(e, env)?;
let expr_instr = if let Some(e_) = r.2.as_await() {
emit_await(e, env, &r.1, e_)?
} else {
emit_expr(e, env, r)?
};
Ok(InstrSeq::gather(vec![expr_instr, emit_pos(pos), ret]))
}
None => Ok(InstrSeq::gather(vec![
instr::null(),
emit_pos(pos),
emit_return(e, env)?,
])),
}
}
fn emit_call<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
e_: &ast::Expr,
_pos: &Pos,
c: &ast::CallExpr,
) -> Result<InstrSeq<'arena>> {
let alloc = env.arena;
if let a::CallExpr {
func: a::Expr(_, _, a::Expr_::Id(sid)),
args,
unpacked_arg: None,
..
} = c
{
let ft = hhbc::FunctionName::from_ast_name(alloc, &sid.1);
let fname = ft.unsafe_as_str();
if fname.eq_ignore_ascii_case("unset") {
Ok(InstrSeq::gather(
args.iter()
.map(|ex| {
emit_expr::emit_unset_expr(e, env, error::expect_normal_paramkind(ex)?)
})
.collect::<Result<Vec<_>, _>>()?,
))
} else if let Some(kind) = set_bytes_kind(fname) {
emit_expr::emit_set_range_expr(e, env, &e_.1, fname, kind, args)
} else {
emit_expr::emit_ignored_expr(e, env, &e_.1, e_)
}
} else {
emit_expr::emit_ignored_expr(e, env, &e_.1, e_)
}
}
fn emit_case<'c, 'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
case: &'c ast::Case,
addbreak: bool,
) -> Result<(InstrSeq<'arena>, (&'c ast::Expr, Label))> {
let ast::Case(case_expr, body) = case;
let label = e.label_gen_mut().next_regular();
let mut res = vec![instr::label(label), emit_block(env, e, body)?];
if addbreak {
res.push(emit_break(e, env, &Pos::NONE));
}
Ok((InstrSeq::gather(res), (case_expr, label)))
}
fn emit_default_case<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
dfl: &ast::DefaultCase,
) -> Result<(InstrSeq<'arena>, Label)> {
let ast::DefaultCase(_, body) = dfl;
let label = e.label_gen_mut().next_regular();
Ok((
InstrSeq::gather(vec![instr::label(label), emit_block(env, e, body)?]),
label,
))
}
fn emit_check_case<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
scrutinee_expr: &ast::Expr,
(case_expr, case_handler_label): (&ast::Expr, Label),
) -> Result<InstrSeq<'arena>> {
Ok(if scrutinee_expr.2.is_lvar() {
InstrSeq::gather(vec![
emit_expr::emit_two_exprs(e, env, &case_expr.1, scrutinee_expr, case_expr)?,
instr::eq(),
instr::jmp_nz(case_handler_label),
])
} else {
let next_case_label = e.label_gen_mut().next_regular();
InstrSeq::gather(vec![
instr::dup(),
emit_expr::emit_expr(e, env, case_expr)?,
emit_pos(&case_expr.1),
instr::eq(),
instr::jmp_z(next_case_label),
instr::pop_c(),
instr::jmp(case_handler_label),
instr::label(next_case_label),
])
})
}
fn emit_awaitall<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
pos: &Pos,
el: &[(Option<ast::Lid>, ast::Expr)],
block: &[ast::Stmt],
) -> Result<InstrSeq<'arena>> {
match el {
[] => Ok(instr::empty()),
[(lvar, expr)] => emit_awaitall_single(e, env, pos, lvar.as_ref(), expr, block),
_ => emit_awaitall_multi(e, env, pos, el, block),
}
}
fn emit_awaitall_single<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
pos: &Pos,
lval: Option<&ast::Lid>,
expr: &ast::Expr,
block: &[ast::Stmt],
) -> Result<InstrSeq<'arena>> {
scope::with_unnamed_locals(e, |e| {
let load_arg = emit_expr::emit_await(e, env, pos, expr)?;
let (load, unset) = match lval {
None => (instr::pop_c(), instr::empty()),
Some(ast::Lid(_, id)) => {
let l = e
.local_gen_mut()
.init_unnamed_for_tempname(local_id::get_name(id));
(instr::pop_l(*l), instr::unset_l(*l))
}
};
Ok((
InstrSeq::gather(vec![load_arg, load]),
emit_stmts(e, env, block)?,
unset,
))
})
}
fn emit_awaitall_multi<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
pos: &Pos,
el: &[(Option<ast::Lid>, ast::Expr)],
block: &[ast::Stmt],
) -> Result<InstrSeq<'arena>> {
scope::with_unnamed_locals(e, |e| {
let mut instrs = vec![];
let mut locals: Vec<Local> = vec![];
for (lvar, expr) in el.iter() {
let local = match lvar {
None => e.local_gen_mut().get_unnamed(),
Some(ast::Lid(_, id)) => e
.local_gen_mut()
.init_unnamed_for_tempname(local_id::get_name(id))
.to_owned(),
};
instrs.push(emit_expr::emit_expr(e, env, expr)?);
instrs.push(instr::pop_l(local));
locals.push(local);
}
let load_args = InstrSeq::gather(instrs);
let unset_locals = InstrSeq::gather(locals.iter().map(|l| instr::unset_l(*l)).collect());
let mut instrs = vec![];
for l in locals.iter() {
instrs.push({
let label_done = e.label_gen_mut().next_regular();
InstrSeq::gather(vec![
instr::push_l(*l),
instr::dup(),
instr::is_type_c(IsTypeOp::Null),
instr::jmp_nz(label_done),
instr::wh_result(),
instr::label(label_done),
instr::pop_l(*l),
])
});
}
let unpack = InstrSeq::gather(instrs);
let await_all = InstrSeq::gather(vec![instr::await_all_list(locals), instr::pop_c()]);
let block_instrs = emit_stmts(e, env, block)?;
Ok((
// before
instr::empty(),
// inner
InstrSeq::gather(vec![
load_args,
emit_pos(pos),
await_all,
unpack,
block_instrs,
]),
// after
unset_locals,
))
})
}
fn emit_using<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
using: &ast::UsingStmt,
) -> Result<InstrSeq<'arena>> {
let alloc = env.arena;
let block_pos = block_pos(&using.block)?;
if using.exprs.1.len() > 1 {
emit_stmts(
e,
env,
using
.exprs
.1
.iter()
.rev()
.fold(using.block.clone(), |block, expr| {
ast::Block(vec![ast::Stmt(
expr.1.clone(),
ast::Stmt_::mk_using(ast::UsingStmt {
has_await: using.has_await,
is_block_scoped: using.is_block_scoped,
exprs: (expr.1.clone(), vec![expr.clone()]),
block,
}),
)])
})
.as_slice(),
)
} else {
e.local_scope(|e| {
let (local, preamble) = match &(using.exprs.1[0].2) {
ast::Expr_::Binop(binop) => match (&binop.bop, (binop.lhs).2.as_lvar()) {
(ast_defs::Bop::Eq(None), Some(ast::Lid(_, id))) => (
e.named_local(local_id::get_name(id).into()),
InstrSeq::gather(vec![
emit_expr::emit_expr(e, env, &(using.exprs.1[0]))?,
emit_pos(&block_pos),
instr::pop_c(),
]),
),
_ => {
let l = e.local_gen_mut().get_unnamed();
(
l,
InstrSeq::gather(vec![
emit_expr::emit_expr(e, env, &(using.exprs.1[0]))?,
instr::set_l(l),
instr::pop_c(),
]),
)
}
},
ast::Expr_::Lvar(lid) => (
e.named_local(local_id::get_name(&lid.1).into()),
InstrSeq::gather(vec![
emit_expr::emit_expr(e, env, &(using.exprs.1[0]))?,
emit_pos(&block_pos),
instr::pop_c(),
]),
),
_ => {
let l = e.local_gen_mut().get_unnamed();
(
l,
InstrSeq::gather(vec![
emit_expr::emit_expr(e, env, &(using.exprs.1[0]))?,
instr::set_l(l),
instr::pop_c(),
]),
)
}
};
let finally_start = e.label_gen_mut().next_regular();
let finally_end = e.label_gen_mut().next_regular();
let body = env.do_in_using_body(e, finally_start, &using.block, emit_block)?;
let jump_instrs = tfr::JumpInstructions::collect(&body, &mut env.jump_targets_gen);
let jump_instrs_is_empty = jump_instrs.is_empty();
let finally_epilogue =
tfr::emit_finally_epilogue(e, env, &using.exprs.1[0].1, jump_instrs, finally_end)?;
let try_instrs = if jump_instrs_is_empty {
body
} else {
tfr::cleanup_try_body(body)
};
let emit_finally = |e: &mut Emitter<'arena, 'decl>,
local: Local,
has_await: bool,
is_block_scoped: bool|
-> InstrSeq<'arena> {
let (epilogue, async_eager_label) = if has_await {
let after_await = e.label_gen_mut().next_regular();
(
InstrSeq::gather(vec![
instr::await_(),
instr::label(after_await),
instr::pop_c(),
]),
Some(after_await),
)
} else {
(instr::pop_c(), None)
};
let fn_name = hhbc::MethodName::from_raw_string(
alloc,
if has_await {
"__disposeAsync"
} else {
"__dispose"
},
);
InstrSeq::gather(vec![
instr::c_get_l(local),
instr::null_uninit(),
instr::f_call_obj_method_d(
FCallArgs::new(
FCallArgsFlags::default(),
1,
0,
Slice::empty(),
Slice::empty(),
async_eager_label,
env.call_context
.as_ref()
.map(|s| -> &str { alloc.alloc_str(s.as_ref()) }),
),
fn_name,
),
epilogue,
if is_block_scoped {
instr::unset_l(local)
} else {
instr::empty()
},
])
};
let exn_local = e.local_gen_mut().get_unnamed();
let middle = if is_empty_block(&using.block) {
instr::empty()
} else {
let finally_instrs = emit_finally(e, local, using.has_await, using.is_block_scoped);
let catch_instrs = InstrSeq::gather(vec![
emit_pos(&block_pos),
make_finally_catch(e, exn_local, finally_instrs),
emit_pos(&using.exprs.1[0].1),
]);
scope::create_try_catch(e.label_gen_mut(), None, true, try_instrs, catch_instrs)
};
Ok(InstrSeq::gather(vec![
preamble,
middle,
instr::label(finally_start),
emit_finally(e, local, using.has_await, using.is_block_scoped),
finally_epilogue,
instr::label(finally_end),
]))
})
}
}
fn block_pos(block: &[ast::Stmt]) -> Result<Pos> {
if block.iter().all(|b| b.0.is_none()) {
return Ok(Pos::NONE);
}
let mut first = 0;
let mut last = block.len() - 1;
loop {
if !block[first].0.is_none() && !block[last].0.is_none() {
return Pos::btw(&block[first].0, &block[last].0).map_err(Error::unrecoverable);
}
if block[first].0.is_none() {
first += 1;
}
if block[last].0.is_none() {
last -= 1;
}
}
}
fn emit_cases<'a, 'arena, 'decl>(
env: &mut Env<'a, 'arena>,
e: &mut Emitter<'arena, 'decl>,
pos: &Pos,
scrutinee_expr: &ast::Expr,
cases: &[ast::Case],
dfl: &Option<ast::DefaultCase>,
) -> Result<(InstrSeq<'arena>, InstrSeq<'arena>, Label)> {
let should_gen_break = |i: usize| -> bool { dfl.is_none() && (i + 1 == cases.len()) };
let mut instr_cases = cases
.iter()
.enumerate()
.map(|(i, case)| emit_case(e, env, case, should_gen_break(i)))
.map(|x| x.map(|(instr_body, label)| (instr_body, Some(label))))
.collect::<Result<Vec<_>>>()?;
let default_label = match dfl {
None => {
// emit warning/exception for missing default
let default_label = e.label_gen_mut().next_regular();
instr_cases.push((
InstrSeq::gather(vec![
instr::label(default_label),
emit_pos_then(pos, instr::throw_non_exhaustive_switch()),
]),
None,
));
default_label
}
Some(dfl) => {
let (dinstrs, default_label) = emit_default_case(e, env, dfl)?;
instr_cases.push((dinstrs, None));
default_label
}
};
let (case_body_instrs, case_exprs): (Vec<InstrSeq<'arena>>, Vec<_>) =
instr_cases.into_iter().unzip();
let case_expr_instrs = case_exprs
.into_iter()
.filter_map(|x| x.map(|x| emit_check_case(e, env, scrutinee_expr, x)))
.collect::<Result<Vec<_>>>()?;
Ok((
InstrSeq::gather(case_expr_instrs),
InstrSeq::gather(case_body_instrs),
default_label,
))
}
fn emit_switch<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
pos: &Pos,
scrutinee_expr: &ast::Expr,
cl: &[ast::Case],
dfl: &Option<ast::DefaultCase>,
) -> Result<InstrSeq<'arena>> {
let (instr_init, instr_free) = if scrutinee_expr.2.is_lvar() {
(instr::empty(), instr::empty())
} else {
(
emit_expr::emit_expr(e, env, scrutinee_expr)?,
instr::pop_c(),
)
};
let break_label = e.label_gen_mut().next_regular();
let (case_expr_instrs, case_body_instrs, default_label) =
env.do_in_switch_body(e, break_label, cl, dfl, |env, e, cases, dfl| {
emit_cases(env, e, pos, scrutinee_expr, cases, dfl)
})?;
Ok(InstrSeq::gather(vec![
instr_init,
case_expr_instrs,
instr_free,
instr::jmp(default_label),
case_body_instrs,
instr::label(break_label),
]))
}
fn is_empty_block(b: &[ast::Stmt]) -> bool {
b.iter().all(|s| s.1.is_noop())
}
fn emit_try_catch_finally<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
pos: &Pos,
r#try: &[ast::Stmt],
catch: &[ast::Catch],
finally: &[ast::Stmt],
) -> Result<InstrSeq<'arena>> {
let is_try_block_empty = false;
let emit_try_block =
|env: &mut Env<'a, 'arena>, e: &mut Emitter<'arena, 'decl>, finally_start: Label| {
env.do_in_try_catch_body(e, finally_start, r#try, catch, |env, e, t, c| {
emit_try_catch(e, env, pos, t, c)
})
};
e.local_scope(|e| emit_try_finally_(e, env, pos, emit_try_block, finally, is_try_block_empty))
}
fn emit_try_finally<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
pos: &Pos,
try_block: &[ast::Stmt],
finally_block: &[ast::Stmt],
) -> Result<InstrSeq<'arena>> {
let is_try_block_empty = is_empty_block(try_block);
let emit_try_block =
|env: &mut Env<'a, 'arena>, e: &mut Emitter<'arena, 'decl>, finally_start: Label| {
env.do_in_try_body(e, finally_start, try_block, emit_block)
};
e.local_scope(|e| {
emit_try_finally_(
e,
env,
pos,
emit_try_block,
finally_block,
is_try_block_empty,
)
})
}
fn emit_try_finally_<
'a,
'arena,
'decl,
E: Fn(&mut Env<'a, 'arena>, &mut Emitter<'arena, 'decl>, Label) -> Result<InstrSeq<'arena>>,
>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
pos: &Pos,
emit_try_block: E,
finally_block: &[ast::Stmt],
is_try_block_empty: bool,
) -> Result<InstrSeq<'arena>> {
if is_try_block_empty {
return env.do_in_finally_body(e, finally_block, emit_block);
};
// We need to generate four things:
// (1) the try-body, which will be followed by
// (2) the normal-continuation finally body, and
// (3) an epilogue to the finally body that deals with finally-blocked
// break and continue
// (4) the exceptional-continuation catch body.
//
// (1) Try body
// The try body might have un-rewritten continues and breaks which
// branch to a label outside of the try. This means that we must
// first run the normal-continuation finally, and then branch to the
// appropriate label.
// We do this by running a rewriter which turns continues and breaks
// inside the try body into setting temp_local to an integer which indicates
// what action the finally must perform when it is finished, followed by a
// jump directly to the finally.
let finally_start = e.label_gen_mut().next_regular();
let finally_end = e.label_gen_mut().next_regular();
let in_try = env.flags.contains(env::Flags::IN_TRY);
env.flags.set(env::Flags::IN_TRY, true);
let try_body_result = emit_try_block(env, e, finally_start);
env.flags.set(env::Flags::IN_TRY, in_try);
let try_body = try_body_result?;
let jump_instrs = tfr::JumpInstructions::collect(&try_body, &mut env.jump_targets_gen);
let jump_instrs_is_empty = jump_instrs.is_empty();
// (2) Finally body
// Note that this is used both in the normal-continuation and
// exceptional-continuation cases; we generate the same code twice.
// TODO: We might consider changing the codegen so that the finally block
// is only generated once. We could do this by making the catch block set a
// temp local to -1, and then branch to the finally block. In the finally block
// epilogue it can check to see if the local is -1, and if so, issue an unwind
// instruction.
// It is illegal to have a continue or break which branches out of a finally.
// Unfortunately we at present do not detect this at parse time; rather, we
// generate an exception at run-time by rewriting continue and break
// instructions found inside finally blocks.
// TODO: If we make this illegal at parse time then we can remove this pass.
let exn_local = e.local_gen_mut().get_unnamed();
let finally_body = env.do_in_finally_body(e, finally_block, emit_block)?;
let mut finally_body_for_catch = finally_body.clone();
label_rewriter::rewrite_with_fresh_regular_labels(e, &mut finally_body_for_catch);
// (3) Finally epilogue
let finally_epilogue = tfr::emit_finally_epilogue(e, env, pos, jump_instrs, finally_end)?;
// (4) Catch body
// We now emit the catch body; it is just cleanup code for the temp_local,
// a copy of the finally body (without the branching epilogue, since we are
// going to unwind rather than branch), and an unwind instruction.
// TODO: The HHVM emitter sometimes emits seemingly spurious
// unset-unnamed-local instructions into the catch block. These look
// like bugs in the emitter. Investigate; if they are bugs in the HHVM
// emitter, get them fixed there. If not, get a clear explanation of
// what they are for and why they are required.
let enclosing_span = env.scope.get_span_or_none();
let try_instrs = if jump_instrs_is_empty {
try_body
} else {
tfr::cleanup_try_body(try_body)
};
let catch_instrs = InstrSeq::gather(vec![
emit_pos(&enclosing_span),
make_finally_catch(e, exn_local, finally_body_for_catch),
]);
let middle = scope::create_try_catch(e.label_gen_mut(), None, true, try_instrs, catch_instrs);
// Putting it all together
Ok(InstrSeq::gather(vec![
middle,
instr::label(finally_start),
emit_pos(pos),
finally_body,
finally_epilogue,
instr::label(finally_end),
]))
}
fn make_finally_catch<'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
exn_local: Local,
finally_body: InstrSeq<'arena>,
) -> InstrSeq<'arena> {
let l2 = instr::unset_l(*e.local_gen_mut().get_retval());
let l1 = instr::unset_l(*e.local_gen_mut().get_label());
InstrSeq::gather(vec![
instr::pop_l(exn_local),
l1,
l2,
scope::create_try_catch(
e.label_gen_mut(),
None,
false,
finally_body,
InstrSeq::gather(vec![instr::push_l(exn_local), instr::chain_faults()]),
),
instr::push_l(exn_local),
instr::throw(),
])
}
fn emit_try_catch<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
pos: &Pos,
try_block: &[ast::Stmt],
catch_list: &[ast::Catch],
) -> Result<InstrSeq<'arena>> {
e.local_scope(|e| emit_try_catch_(e, env, pos, try_block, catch_list))
}
fn emit_try_catch_<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
pos: &Pos,
try_block: &[ast::Stmt],
catch_list: &[ast::Catch],
) -> Result<InstrSeq<'arena>> {
if is_empty_block(try_block) {
return Ok(instr::empty());
};
let end_label = e.label_gen_mut().next_regular();
let catch_instrs = InstrSeq::gather(
catch_list
.iter()
.map(|catch| emit_catch(e, env, pos, end_label, catch))
.collect::<Result<Vec<_>>>()?,
);
let in_try = env.flags.contains(env::Flags::IN_TRY);
env.flags.set(env::Flags::IN_TRY, true);
let try_body = emit_stmts(e, env, try_block);
env.flags.set(env::Flags::IN_TRY, in_try);
let try_instrs = InstrSeq::gather(vec![try_body?, emit_pos(pos)]);
Ok(scope::create_try_catch(
e.label_gen_mut(),
Some(end_label),
false,
try_instrs,
catch_instrs,
))
}
fn emit_catch<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
pos: &Pos,
end_label: Label,
ast::Catch(catch_ty, catch_lid, catch_block): &ast::Catch,
) -> Result<InstrSeq<'arena>> {
let alloc = env.arena;
// Note that this is a "regular" label; we're not going to branch to
// it directly in the event of an exception.
let next_catch = e.label_gen_mut().next_regular();
let class_id = hhbc::ClassName::from_ast_name_and_mangle(alloc, &catch_ty.1);
let ast::Lid(_pos, catch_local_id) = catch_lid;
Ok(InstrSeq::gather(vec![
instr::dup(),
instr::instance_of_d(class_id),
instr::jmp_z(next_catch),
instr::set_l(e.named_local(local_id::get_name(catch_local_id).into())),
instr::pop_c(),
emit_stmts(e, env, catch_block)?,
emit_pos(pos),
instr::jmp(end_label),
instr::label(next_catch),
]))
}
fn emit_foreach<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
pos: &Pos,
collection: &ast::Expr,
iterator: &ast::AsExpr,
block: &[ast::Stmt],
) -> Result<InstrSeq<'arena>> {
use ast::AsExpr as A;
e.local_scope(|e| match iterator {
A::AsV(_) | A::AsKv(_, _) => emit_foreach_(e, env, pos, collection, iterator, block),
A::AwaitAsV(pos, _) | A::AwaitAsKv(pos, _, _) => {
emit_foreach_await(e, env, pos, collection, iterator, block)
}
})
}
fn emit_foreach_<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
pos: &Pos,
collection: &ast::Expr,
iterator: &ast::AsExpr,
block: &[ast::Stmt],
) -> Result<InstrSeq<'arena>> {
let collection_instrs = emit_expr::emit_expr(e, env, collection)?;
scope::with_unnamed_locals_and_iterators(e, |e| {
let iter_id = e.iterator_mut().get();
let loop_break_label = e.label_gen_mut().next_regular();
let loop_continue_label = e.label_gen_mut().next_regular();
let loop_head_label = e.label_gen_mut().next_regular();
let (key_id, val_id, preamble) = emit_iterator_key_value_storage(e, env, iterator)?;
let iter_args = IterArgs {
iter_id,
key_id: key_id.unwrap_or(Local::INVALID),
val_id,
};
let body = env.do_in_loop_body(
e,
loop_break_label,
loop_continue_label,
Some(iter_id),
block,
emit_block,
)?;
let iter_init = InstrSeq::gather(vec![
collection_instrs,
emit_pos(&collection.1),
instr::iter_init(iter_args.clone(), loop_break_label),
]);
let iterate = InstrSeq::gather(vec![
instr::label(loop_head_label),
preamble,
body,
instr::label(loop_continue_label),
emit_pos(pos),
instr::iter_next(iter_args, loop_head_label),
]);
let iter_done = instr::label(loop_break_label);
Ok((iter_init, iterate, iter_done))
})
}
fn emit_foreach_await<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
pos: &Pos,
collection: &ast::Expr,
iterator: &ast::AsExpr,
block: &[ast::Stmt],
) -> Result<InstrSeq<'arena>> {
let instr_collection = emit_expr::emit_expr(e, env, collection)?;
scope::with_unnamed_local(e, |e, iter_temp_local| {
let alloc = e.alloc;
let input_is_async_iterator_label = e.label_gen_mut().next_regular();
let next_label = e.label_gen_mut().next_regular();
let exit_label = e.label_gen_mut().next_regular();
let pop_and_exit_label = e.label_gen_mut().next_regular();
let async_eager_label = e.label_gen_mut().next_regular();
let next_meth = hhbc::MethodName::from_raw_string(alloc, "next");
let iter_init = InstrSeq::gather(vec![
instr_collection,
instr::dup(),
instr::instance_of_d(hhbc::ClassName::from_raw_string(alloc, "HH\\AsyncIterator")),
instr::jmp_nz(input_is_async_iterator_label),
emit_fatal::emit_fatal_runtime(
alloc,
pos,
"Unable to iterate non-AsyncIterator asynchronously",
),
instr::label(input_is_async_iterator_label),
instr::pop_l(iter_temp_local),
]);
let loop_body_instr =
env.do_in_loop_body(e, exit_label, next_label, None, block, emit_block)?;
let iterate = InstrSeq::gather(vec![
instr::label(next_label),
instr::c_get_l(iter_temp_local),
instr::null_uninit(),
instr::f_call_obj_method_d(
FCallArgs::new(
FCallArgsFlags::default(),
1,
0,
Slice::empty(),
Slice::empty(),
Some(async_eager_label),
None,
),
next_meth,
),
instr::await_(),
instr::label(async_eager_label),
instr::dup(),
instr::is_type_c(IsTypeOp::Null),
instr::jmp_nz(pop_and_exit_label),
emit_foreach_await_key_value_storage(e, env, iterator)?,
loop_body_instr,
emit_pos(pos),
instr::jmp(next_label),
instr::label(pop_and_exit_label),
instr::pop_c(),
instr::label(exit_label),
]);
let iter_done = instr::unset_l(iter_temp_local);
Ok((iter_init, iterate, iter_done))
})
}
// Assigns a location to store values for foreach-key and foreach-value and
// creates a code to populate them.
// NOT suitable for foreach (... await ...) which uses different code-gen
// Returns: key_local_opt * value_local * key_preamble * value_preamble
// where:
// - key_local_opt - local variable to store a foreach-key value if it is
// declared
// - value_local - local variable to store a foreach-value
// - key_preamble - list of instructions to populate foreach-key
// - value_preamble - list of instructions to populate foreach-value
fn emit_iterator_key_value_storage<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
iterator: &ast::AsExpr,
) -> Result<(Option<Local>, Local, InstrSeq<'arena>)> {
use ast::AsExpr as A;
fn get_id_of_simple_lvar_opt(lvar: &ast::Expr_) -> Result<Option<&str>> {
if let Some(ast::Lid(pos, id)) = lvar.as_lvar() {
let name = local_id::get_name(id);
if name == special_idents::THIS {
return Err(Error::fatal_parse(pos, "Cannot re-assign $this"));
} else if !(superglobals::is_superglobal(name)) {
return Ok(Some(name));
}
};
Ok(None)
}
match iterator {
A::AsKv(k, v) => Ok(
match (
get_id_of_simple_lvar_opt(&k.2)?,
get_id_of_simple_lvar_opt(&v.2)?,
) {
(Some(key_id), Some(val_id)) => (
Some(e.named_local(key_id.into())),
e.named_local(val_id.into()),
instr::empty(),
),
_ => {
let key_local = e.local_gen_mut().get_unnamed();
let val_local = e.local_gen_mut().get_unnamed();
let (mut key_preamble, key_load) =
emit_iterator_lvalue_storage(e, env, k, key_local)?;
let (mut val_preamble, val_load) =
emit_iterator_lvalue_storage(e, env, v, val_local)?;
// HHVM prepends code to initialize non-plain, non-list foreach-key
// to the value preamble - do the same to minimize diffs
if !(k.2).is_list() {
key_preamble.extend(val_preamble);
val_preamble = key_preamble;
key_preamble = vec![];
};
(
Some(key_local),
val_local,
InstrSeq::gather(vec![
InstrSeq::gather(val_preamble),
InstrSeq::gather(val_load),
InstrSeq::gather(key_preamble),
InstrSeq::gather(key_load),
]),
)
}
},
),
A::AsV(v) => Ok(match get_id_of_simple_lvar_opt(&v.2)? {
Some(val_id) => (None, e.named_local(val_id.into()), instr::empty()),
None => {
let val_local = e.local_gen_mut().get_unnamed();
let (val_preamble, val_load) = emit_iterator_lvalue_storage(e, env, v, val_local)?;
(
None,
val_local,
InstrSeq::gather(vec![
InstrSeq::gather(val_preamble),
InstrSeq::gather(val_load),
]),
)
}
}),
_ => Err(Error::unrecoverable(
"emit_iterator_key_value_storage with iterator using await",
)),
}
}
fn emit_iterator_lvalue_storage<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
lvalue: &ast::Expr,
local: Local,
) -> Result<(Vec<InstrSeq<'arena>>, Vec<InstrSeq<'arena>>)> {
match &lvalue.2 {
ast::Expr_::Call(_) => Err(Error::fatal_parse(
&lvalue.1,
"Can't use return value in write context",
)),
ast::Expr_::List(es) => {
let (preamble, load_values) = emit_load_list_elements(
e,
env,
vec![instr::base_l(local, MOpMode::Warn, ReadonlyOp::Any)],
es,
)?;
let load_values = vec![
InstrSeq::gather(load_values.into_iter().rev().collect()),
instr::unset_l(local),
];
Ok((preamble, load_values))
}
_ => {
let (lhs, rhs, set_op) = emit_expr::emit_lval_op_nonlist_steps(
e,
env,
&lvalue.1,
LValOp::Set,
lvalue,
instr::c_get_l(local),
1,
false,
false, // TODO: Readonly iterator assignment
)?;
Ok((
vec![lhs],
vec![rhs, set_op, instr::pop_c(), instr::unset_l(local)],
))
}
}
}
fn emit_load_list_elements<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
path: Vec<InstrSeq<'arena>>,
es: &[ast::Expr],
) -> Result<(Vec<InstrSeq<'arena>>, Vec<InstrSeq<'arena>>)> {
let (preamble, load_value): (Vec<Vec<InstrSeq<'arena>>>, Vec<Vec<InstrSeq<'arena>>>) = es
.iter()
.enumerate()
.map(|(i, x)| {
emit_load_list_element(
e,
env,
path.iter().map(InstrSeq::clone).collect::<Vec<_>>(),
i,
x,
)
})
.collect::<Result<Vec<_>>>()?
.into_iter()
.unzip();
Ok((
preamble.into_iter().flatten().collect(),
load_value.into_iter().flatten().collect(),
))
}
fn emit_load_list_element<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
mut path: Vec<InstrSeq<'arena>>,
i: usize,
elem: &ast::Expr,
) -> Result<(Vec<InstrSeq<'arena>>, Vec<InstrSeq<'arena>>)> {
let query_value = |path| {
InstrSeq::gather(vec![
InstrSeq::gather(path),
instr::query_m(0, QueryMOp::CGet, MemberKey::EI(i as i64, ReadonlyOp::Any)),
])
};
Ok(match &elem.2 {
ast::Expr_::Lvar(lid) => {
let load_value = InstrSeq::gather(vec![
query_value(path),
instr::set_l(e.named_local(local_id::get_name(&lid.1).into())),
instr::pop_c(),
]);
(vec![], vec![load_value])
}
ast::Expr_::List(es) => {
let instr_dim = instr::dim(MOpMode::Warn, MemberKey::EI(i as i64, ReadonlyOp::Any));
path.push(instr_dim);
emit_load_list_elements(e, env, path, es)?
}
_ => {
let set_instrs = emit_expr::emit_lval_op_nonlist(
e,
env,
&elem.1,
LValOp::Set,
elem,
query_value(path),
1,
false,
false, // TODO readonly load list elements
)?;
let load_value = InstrSeq::gather(vec![set_instrs, instr::pop_c()]);
(vec![], vec![load_value])
}
})
}
//Emit code for the value and possibly key l-value operation in a foreach
// await statement. The result of invocation of the `next` method has been
// stored on top of the stack. For example:
// foreach (foo() await as $a->f => list($b[0], $c->g)) { ... }
// Here, we need to construct l-value operations that access the [0] (for $a->f)
// and [1;0] (for $b[0]) and [1;1] (for $c->g) indices of the array returned
// from the `next` method.
fn emit_foreach_await_key_value_storage<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
iterator: &ast::AsExpr,
) -> Result<InstrSeq<'arena>> {
use ast::AsExpr as A;
match iterator {
A::AwaitAsKv(_, k, v) | A::AsKv(k, v) => Ok(InstrSeq::gather(vec![
emit_foreach_await_lvalue_storage(e, env, k, &[0], true)?,
emit_foreach_await_lvalue_storage(e, env, v, &[1], false)?,
])),
A::AwaitAsV(_, v) | A::AsV(v) => emit_foreach_await_lvalue_storage(e, env, v, &[1], false),
}
}
// Emit code for either the key or value l-value operation in foreach await.
// `indices` is the initial prefix of the array indices ([0] for key or [1] for
// value) that is prepended onto the indices needed for list destructuring
//
// TODO: we don't need unnamed local if the target is a local
fn emit_foreach_await_lvalue_storage<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
lvalue: &ast::Expr,
indices: &[isize],
keep_on_stack: bool,
) -> Result<InstrSeq<'arena>> {
scope::with_unnamed_local(e, |e, local| {
let (init, assign) = emit_expr::emit_lval_op_list(
e,
env,
&lvalue.1,
Some(&local),
indices,
lvalue,
false,
false,
)?;
Ok((
instr::pop_l(local),
InstrSeq::gather(vec![init, assign]),
if keep_on_stack {
instr::push_l(local)
} else {
instr::unset_l(local)
},
))
})
}
fn emit_stmts<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
stl: &[ast::Stmt],
) -> Result<InstrSeq<'arena>> {
Ok(InstrSeq::gather(
stl.iter()
.map(|s| emit_stmt(e, env, s))
.collect::<Result<Vec<_>>>()?,
))
}
fn emit_block<'a, 'arena, 'decl>(
env: &mut Env<'a, 'arena>,
emitter: &mut Emitter<'arena, 'decl>,
block: &[ast::Stmt],
) -> Result<InstrSeq<'arena>> {
emit_stmts(emitter, env, block)
}
fn emit_do<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
body: &[ast::Stmt],
cond: &ast::Expr,
) -> Result<InstrSeq<'arena>> {
let break_label = e.label_gen_mut().next_regular();
let cont_label = e.label_gen_mut().next_regular();
let start_label = e.label_gen_mut().next_regular();
let jmpnz_instr = emit_expr::emit_jmpnz(e, env, cond, start_label)?.instrs;
Ok(InstrSeq::gather(vec![
instr::label(start_label),
env.do_in_loop_body(e, break_label, cont_label, None, body, emit_block)?,
instr::label(cont_label),
jmpnz_instr,
instr::label(break_label),
]))
}
fn emit_while<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
cond: &ast::Expr,
body: &[ast::Stmt],
) -> Result<InstrSeq<'arena>> {
let break_label = e.label_gen_mut().next_regular();
let cont_label = e.label_gen_mut().next_regular();
let start_label = e.label_gen_mut().next_regular();
/* TODO: This is *bizarre* codegen for a while loop.
It would be better to generate this as
instr_label continue_label;
emit_expr e;
instr_jmpz break_label;
body;
instr_jmp continue_label;
instr_label break_label;
*/
let i3 = emit_expr::emit_jmpnz(e, env, cond, start_label)?.instrs;
let i2 = env.do_in_loop_body(e, break_label, cont_label, None, body, emit_block)?;
let i1 = emit_expr::emit_jmpz(e, env, cond, break_label)?.instrs;
Ok(InstrSeq::gather(vec![
i1,
instr::label(start_label),
i2,
instr::label(cont_label),
i3,
instr::label(break_label),
]))
}
fn emit_for<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
e1: &[ast::Expr],
e2: Option<&ast::Expr>,
e3: &[ast::Expr],
body: &[ast::Stmt],
) -> Result<InstrSeq<'arena>> {
let break_label = e.label_gen_mut().next_regular();
let cont_label = e.label_gen_mut().next_regular();
let start_label = e.label_gen_mut().next_regular();
fn emit_cond<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
jmpz: bool,
label: Label,
cond: Option<&ast::Expr>,
) -> Result<InstrSeq<'arena>> {
Ok(match cond {
None => {
if jmpz {
instr::empty()
} else {
instr::jmp(label)
}
}
Some(cond) => {
if jmpz {
emit_expr::emit_jmpz(emitter, env, cond, label)
} else {
emit_expr::emit_jmpnz(emitter, env, cond, label)
}?
.instrs
}
})
}
// TODO: this is bizarre codegen for a "for" loop.
// This should be codegen'd as
// emit_ignored_expr initializer;
// instr_label start_label;
// from_expr condition;
// instr_jmpz break_label;
// body;
// instr_label continue_label;
// emit_ignored_expr increment;
// instr_jmp start_label;
// instr_label break_label;
let i5 = emit_cond(e, env, false, start_label, e2)?;
let i4 = emit_expr::emit_ignored_exprs(e, env, &Pos::NONE, e3)?;
let i3 = env.do_in_loop_body(e, break_label, cont_label, None, body, emit_block)?;
let i2 = emit_cond(e, env, true, break_label, e2)?;
let i1 = emit_expr::emit_ignored_exprs(e, env, &Pos::NONE, e1)?;
Ok(InstrSeq::gather(vec![
i1,
i2,
instr::label(start_label),
i3,
instr::label(cont_label),
i4,
i5,
instr::label(break_label),
]))
}
pub fn emit_dropthrough_return<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
) -> Result<InstrSeq<'arena>> {
match e.statement_state().default_dropthrough.as_ref() {
Some(instrs) => Ok(InstrSeq::clone(instrs)),
None => {
let ret = emit_return(e, env)?;
let state = e.statement_state();
Ok(InstrSeq::gather(vec![
emit_pos(&(state.function_pos.last_char())),
state.default_return_value.clone(),
ret,
]))
}
}
}
pub fn emit_final_stmt<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
stmt: &ast::Stmt,
) -> Result<InstrSeq<'arena>> {
match &stmt.1 {
a::Stmt_::Throw(_) | a::Stmt_::Return(_) | a::Stmt_::YieldBreak => emit_stmt(e, env, stmt),
a::Stmt_::Block(stmts) => emit_final_stmts(env, e, stmts),
_ => {
let ret = emit_dropthrough_return(e, env)?;
Ok(InstrSeq::gather(vec![emit_stmt(e, env, stmt)?, ret]))
}
}
}
pub fn emit_final_stmts<'a, 'arena, 'decl>(
env: &mut Env<'a, 'arena>,
e: &mut Emitter<'arena, 'decl>,
block: &[ast::Stmt],
) -> Result<InstrSeq<'arena>> {
match block {
[] => emit_dropthrough_return(e, env),
_ => {
let mut ret = Vec::with_capacity(block.len());
for (i, s) in block.iter().enumerate() {
let instrs = if i == block.len() - 1 {
emit_final_stmt(e, env, s)?
} else {
emit_stmt(e, env, s)?
};
ret.push(instrs);
}
Ok(InstrSeq::gather(ret))
}
}
}
pub fn emit_markup<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
(_, s): &ast::Pstring,
check_for_hashbang: bool,
) -> Result<InstrSeq<'arena>> {
let markup = if s.is_empty() {
instr::empty()
} else {
lazy_static! {
static ref HASHBANG_PAT: regex::Regex = regex::Regex::new(r"^#!.*\n").unwrap();
}
let tail = String::from(match HASHBANG_PAT.shortest_match(s) {
Some(i) if check_for_hashbang => {
// if markup text starts with #!
// - extract a line with hashbang
// - it will be emitted as a call to print_hashbang function
// - emit remaining part of text as regular markup
&s[i..]
}
_ => s,
});
if tail.is_empty() {
instr::empty()
} else {
let call_expr = hack_expr!("echo #{str(tail)}");
emit_expr::emit_ignored_expr(e, env, &Pos::NONE, &call_expr)?
}
};
Ok(markup)
}
fn emit_break<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
pos: &Pos,
) -> InstrSeq<'arena> {
use tfr::EmitBreakOrContinueFlags as Flags;
tfr::emit_break_or_continue(e, Flags::IS_BREAK, env, pos)
}
fn emit_continue<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
pos: &Pos,
) -> InstrSeq<'arena> {
use tfr::EmitBreakOrContinueFlags as Flags;
tfr::emit_break_or_continue(e, Flags::empty(), env, pos)
}
fn emit_await_assignment<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
pos: &Pos,
lval: &ast::Expr,
r: &ast::Expr,
) -> Result<InstrSeq<'arena>> {
match lval.2.as_lvar() {
Some(ast::Lid(_, id)) if !emit_expr::is_local_this(env, id) => Ok(InstrSeq::gather(vec![
emit_expr::emit_await(e, env, pos, r)?,
emit_pos(pos),
instr::pop_l(emit_expr::get_local(e, env, pos, local_id::get_name(id))?),
])),
_ => {
let awaited_instrs = emit_await(e, env, pos, r)?;
scope::with_unnamed_local(e, |e, temp| {
let rhs_instrs = instr::push_l(temp);
let (lhs, rhs, setop) = emit_expr::emit_lval_op_nonlist_steps(
e,
env,
pos,
LValOp::Set,
lval,
rhs_instrs,
1,
false,
false, // unnamed local assignment does not need readonly check
)?;
Ok((
InstrSeq::gather(vec![awaited_instrs, instr::pop_l(temp)]),
lhs,
InstrSeq::gather(vec![rhs, setop, instr::pop_c()]),
))
})
}
}
}
fn emit_if<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
pos: &Pos,
condition: &ast::Expr,
consequence: &[ast::Stmt],
alternative: &[ast::Stmt],
) -> Result<InstrSeq<'arena>> {
if alternative.is_empty() || (alternative.len() == 1 && alternative[0].1.is_noop()) {
let done_label = e.label_gen_mut().next_regular();
let consequence_instr = emit_stmts(e, env, consequence)?;
Ok(InstrSeq::gather(vec![
emit_expr::emit_jmpz(e, env, condition, done_label)?.instrs,
consequence_instr,
instr::label(done_label),
]))
} else {
let alternative_label = e.label_gen_mut().next_regular();
let done_label = e.label_gen_mut().next_regular();
let consequence_instr = emit_stmts(e, env, consequence)?;
let alternative_instr = emit_stmts(e, env, alternative)?;
Ok(InstrSeq::gather(vec![
emit_expr::emit_jmpz(e, env, condition, alternative_label)?.instrs,
consequence_instr,
emit_pos(pos),
instr::jmp(done_label),
instr::label(alternative_label),
alternative_instr,
instr::label(done_label),
]))
}
}
// Treat the declaration of a local as a binop assignment.
// TODO: clone less
// TODO: Enforce the type hint from the declaration?
fn emit_declare_local<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
pos: &Pos,
id: &ast::Lid,
e_: &Option<ast::Expr>,
) -> Result<InstrSeq<'arena>> {
if let Some(e_) = e_ {
let bop = ast::Binop {
bop: ast_defs::Bop::Eq(None),
lhs: ast::Expr::new((), pos.clone(), ast::Expr_::mk_lvar(id.clone())),
rhs: e_.clone(),
};
let e2 = ast::Expr::new((), pos.clone(), ast::Expr_::mk_binop(bop.clone()));
emit_binop(e, env, &e2, pos, &bop)
} else {
Ok(InstrSeq::gather(vec![]))
}
} |
Rust | hhvm/hphp/hack/src/hackc/emitter/emit_typedef.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::ClassName;
use hhbc::Span;
use hhbc::Typedef;
use hhvm_types_ffi::ffi::Attr;
use oxidized::ast;
use crate::emit_attribute;
use crate::emit_body;
use crate::emit_type_constant;
pub fn emit_typedefs_from_program<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
prog: &'a [ast::Def],
) -> Result<Vec<Typedef<'arena>>> {
prog.iter()
.filter_map(|def| {
def.as_typedef().and_then(|td| {
if !td.is_ctx {
Some(emit_typedef(e, td))
} else {
None
}
})
})
.collect()
}
fn emit_typedef<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
typedef: &'a ast::Typedef,
) -> Result<Typedef<'arena>> {
let name = ClassName::<'arena>::from_ast_name_and_mangle(emitter.alloc, &typedef.name.1);
let attributes_res = emit_attribute::from_asts(emitter, &typedef.user_attributes);
let tparams = emit_body::get_tp_names(typedef.tparams.as_slice());
let type_info_union_res = emit_type_hint::hint_to_type_info_union(
emitter.alloc,
&emit_type_hint::Kind::TypeDef,
false,
typedef.kind.1.is_hoption(),
&tparams,
&typedef.kind,
);
let type_structure_res = emit_type_constant::typedef_to_type_structure(
emitter.alloc,
emitter.options(),
&tparams,
typedef,
);
let span = Span::from_pos(&typedef.span);
let mut attrs = Attr::AttrNone;
attrs.set(Attr::AttrPersistent, emitter.systemlib());
attributes_res.and_then(|attributes| {
type_info_union_res.and_then(|type_info_union| {
type_structure_res.map(|type_structure| Typedef {
name,
attributes: emitter
.alloc
.alloc_slice_fill_iter(attributes.into_iter())
.into(),
type_info_union,
type_structure,
span,
attrs,
case_type: typedef.vis.is_case_type(),
})
})
})
} |
Rust | hhvm/hphp/hack/src/hackc/emitter/emit_type_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 std::collections::BTreeMap;
use error::Error;
use error::Result;
use hhbc::DictEntry;
use hhbc::TypedValue;
use hhbc_string_utils as string_utils;
use hhvm_types_ffi::ffi::TypeStructureKind;
use naming_special_names_rust::classes;
use naming_special_names_rust::typehints;
use options::Options;
use oxidized::aast;
use oxidized::aast_defs;
use oxidized::aast_defs::Hint;
use oxidized::aast_defs::NastShapeInfo;
use oxidized::aast_defs::ShapeFieldInfo;
use oxidized::ast;
use oxidized::ast_defs;
use oxidized::ast_defs::ShapeFieldName;
use super::TypeRefinementInHint;
fn ts_kind(tparams: &[&str], p: &str) -> TypeStructureKind {
if tparams.contains(&p) {
TypeStructureKind::T_typevar
} else {
match p.to_lowercase().as_str() {
"hh\\void" => TypeStructureKind::T_void,
"hh\\int" => TypeStructureKind::T_int,
"hh\\bool" => TypeStructureKind::T_bool,
"hh\\float" => TypeStructureKind::T_float,
"hh\\string" => TypeStructureKind::T_string,
"hh\\resource" => TypeStructureKind::T_resource,
"hh\\num" => TypeStructureKind::T_num,
"hh\\noreturn" => TypeStructureKind::T_noreturn,
"hh\\arraykey" => TypeStructureKind::T_arraykey,
"hh\\mixed" => TypeStructureKind::T_mixed,
"tuple" => TypeStructureKind::T_tuple,
"$$internal$$fun" => TypeStructureKind::T_fun,
"_" | "$$internal$$typevar" => TypeStructureKind::T_typevar,
"shape" => TypeStructureKind::T_shape,
"class" => TypeStructureKind::T_class,
"interface" => TypeStructureKind::T_interface,
"trait" => TypeStructureKind::T_trait,
"enum" => TypeStructureKind::T_enum,
"hh\\dict" => TypeStructureKind::T_dict,
"hh\\vec" => TypeStructureKind::T_vec,
"hh\\keyset" => TypeStructureKind::T_keyset,
"hh\\vec_or_dict" => TypeStructureKind::T_vec_or_dict,
"hh\\nonnull" => TypeStructureKind::T_nonnull,
"hh\\darray" => TypeStructureKind::T_darray,
"hh\\varray" => TypeStructureKind::T_varray,
"hh\\varray_or_darray" => TypeStructureKind::T_varray_or_darray,
"hh\\anyarray" => TypeStructureKind::T_any_array,
"hh\\null" => TypeStructureKind::T_null,
"hh\\nothing" => TypeStructureKind::T_nothing,
"hh\\dynamic" => TypeStructureKind::T_dynamic,
"unresolved" => TypeStructureKind::T_unresolved,
"$$internal$$typeaccess" => TypeStructureKind::T_typeaccess,
"$$internal$$reifiedtype" => TypeStructureKind::T_reifiedtype,
_ if p.len() > 4 && p.starts_with("xhp_") => TypeStructureKind::T_xhp,
_ => TypeStructureKind::T_unresolved,
}
}
}
fn is_prim_or_resolved_classname(kind: TypeStructureKind) -> bool {
matches!(
kind,
// primitives
TypeStructureKind::T_void
| TypeStructureKind::T_int
| TypeStructureKind::T_bool
| TypeStructureKind::T_float
| TypeStructureKind::T_string
| TypeStructureKind::T_resource
| TypeStructureKind::T_num
| TypeStructureKind::T_noreturn
| TypeStructureKind::T_arraykey
| TypeStructureKind::T_mixed
| TypeStructureKind::T_nonnull
| TypeStructureKind::T_null
| TypeStructureKind::T_nothing
| TypeStructureKind::T_dynamic
// resolved classnames
| TypeStructureKind::T_darray
| TypeStructureKind::T_varray
| TypeStructureKind::T_varray_or_darray
| TypeStructureKind::T_vec
| TypeStructureKind::T_dict
| TypeStructureKind::T_keyset
| TypeStructureKind::T_vec_or_dict
| TypeStructureKind::T_any_array
)
}
fn shape_field_name<'arena>(alloc: &'arena bumpalo::Bump, sf: &ShapeFieldName) -> (String, bool) {
use oxidized::ast_defs::Id;
match sf {
ShapeFieldName::SFlitInt((_, s)) => (s.to_string(), false),
ShapeFieldName::SFlitStr((_, s)) => {
(
// 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()) },
false,
)
}
ShapeFieldName::SFclassConst(Id(_, cname), (_, s)) => {
let id = hhbc::ClassName::from_ast_name_and_mangle(alloc, cname);
(format!("{}::{}", id.unsafe_as_str(), s), true)
}
}
}
fn shape_field_to_entry<'arena>(
alloc: &'arena bumpalo::Bump,
opts: &Options,
tparams: &[&str],
targ_map: &BTreeMap<&str, i64>,
type_refinement_in_hint: TypeRefinementInHint,
sfi: &ShapeFieldInfo,
) -> Result<DictEntry<'arena>> {
let (name, is_class_const) = shape_field_name(alloc, &sfi.name);
let mut r = bumpalo::vec![in alloc];
if is_class_const {
r.push(encode_entry("is_cls_cns", TypedValue::Bool(true)));
}
if sfi.optional {
r.push(encode_entry("optional_shape_field", TypedValue::Bool(true)));
};
r.push(encode_entry(
"value",
hint_to_type_constant(
alloc,
opts,
tparams,
targ_map,
&sfi.hint,
type_refinement_in_hint,
)?,
));
Ok(encode_entry(
alloc.alloc_str(&name),
TypedValue::dict(r.into_bump_slice()),
))
}
fn shape_info_to_typed_value<'arena>(
alloc: &'arena bumpalo::Bump,
opts: &Options,
tparams: &[&str],
targ_map: &BTreeMap<&str, i64>,
type_refinement_in_hint: TypeRefinementInHint,
si: &NastShapeInfo,
) -> Result<TypedValue<'arena>> {
let info = si
.field_map
.iter()
.map(|sfi| {
shape_field_to_entry(alloc, opts, tparams, targ_map, type_refinement_in_hint, sfi)
})
.collect::<Result<Vec<_>>>()?;
Ok(TypedValue::dict(
alloc.alloc_slice_fill_iter(info.into_iter()),
))
}
fn shape_allows_unknown_fields<'arena>(si: &NastShapeInfo) -> Option<DictEntry<'arena>> {
if si.allows_unknown_fields {
Some(encode_entry(
"allows_unknown_fields",
TypedValue::Bool(true),
))
} else {
None
}
}
fn type_constant_access_list<'arena>(
alloc: &'arena bumpalo::Bump,
sl: &[aast::Sid],
) -> TypedValue<'arena> {
let sl_ = alloc.alloc_slice_fill_iter(
sl.iter()
.map(|ast_defs::Id(_, s)| TypedValue::alloc_string(s, alloc)),
);
TypedValue::vec(sl_)
}
fn resolve_classname<'arena>(
alloc: &'arena bumpalo::Bump,
tparams: &[&str],
mut s: String,
) -> (Option<DictEntry<'arena>>, String) {
let kind = ts_kind(tparams, &s);
let name_key = if kind != TypeStructureKind::T_typevar {
s = hhbc::ClassName::from_ast_name_and_mangle(alloc, s.as_str()).unsafe_into_string();
"classname"
} else {
"name"
};
let entry = if is_prim_or_resolved_classname(ts_kind(tparams, &s)) {
None
} else {
Some(encode_entry(
name_key,
TypedValue::alloc_string(s.as_str(), alloc),
))
};
(entry, s)
}
fn get_generic_types<'arena>(
alloc: &'arena bumpalo::Bump,
opts: &Options,
tparams: &[&str],
targ_map: &BTreeMap<&str, i64>,
type_refinement_in_hint: TypeRefinementInHint,
hints: &[Hint],
) -> Result<bumpalo::collections::vec::Vec<'arena, DictEntry<'arena>>> {
Ok(if hints.is_empty() {
bumpalo::vec![in alloc]
} else {
bumpalo::vec![in alloc; encode_entry(
"generic_types",
hints_to_type_constant(alloc, opts, tparams, targ_map, type_refinement_in_hint, hints)?,
)]
})
}
fn get_union_types<'arena>(
alloc: &'arena bumpalo::Bump,
opts: &Options,
tparams: &[&str],
targ_map: &BTreeMap<&str, i64>,
type_refinement_in_hint: TypeRefinementInHint,
hints: &[Hint],
) -> Result<bumpalo::collections::vec::Vec<'arena, DictEntry<'arena>>> {
Ok(bumpalo::vec![in alloc; encode_entry(
"union_types",
hints_to_type_constant(alloc, opts, tparams, targ_map, type_refinement_in_hint, hints)?,
)])
}
fn encode_entry<'a>(key: &'a str, value: TypedValue<'a>) -> DictEntry<'a> {
DictEntry {
key: TypedValue::string(key),
value,
}
}
fn encode_kind(kind: TypeStructureKind) -> DictEntry<'static> {
encode_entry("kind", TypedValue::Int(kind.repr as i64))
}
fn encode_root_name<'a>(alloc: &'a bumpalo::Bump, s: &str) -> DictEntry<'a> {
let s = if s == "this" {
string_utils::prefix_namespace("HH", s)
} else {
hhbc::ClassName::from_ast_name_and_mangle(alloc, s).unsafe_into_string()
};
encode_entry("root_name", TypedValue::alloc_string(&s, alloc))
}
fn get_typevars<'arena>(
alloc: &'arena bumpalo::Bump,
tparams: &[&str],
) -> bumpalo::collections::Vec<'arena, DictEntry<'arena>> {
if tparams.is_empty() {
bumpalo::vec![in alloc]
} else {
bumpalo::vec![in alloc;
encode_entry("typevars", TypedValue::alloc_string(tparams.join(","), alloc)),
]
}
}
fn hint_to_type_constant_list<'arena>(
alloc: &'arena bumpalo::Bump,
opts: &Options,
tparams: &[&str],
targ_map: &BTreeMap<&str, i64>,
type_refinement_in_hint: TypeRefinementInHint,
Hint(_, hint): &Hint,
) -> Result<bumpalo::collections::Vec<'arena, DictEntry<'arena>>> {
use aast_defs::Hint_;
Ok(match hint.as_ref() {
Hint_::Happly(s, hints) => {
let ast_defs::Id(_, name) = s;
if hints.is_empty() {
if let Some(id) = targ_map.get(name.as_str()) {
return Ok(bumpalo::vec![in alloc;
encode_kind(TypeStructureKind::T_reifiedtype),
encode_entry("id", TypedValue::Int(*id)),
]);
}
}
let hints = match &hints[..] {
[h] if name == typehints::POISON_MARKER => {
return hint_to_type_constant_list(
alloc,
opts,
tparams,
targ_map,
type_refinement_in_hint,
h,
);
}
[_h] if name == typehints::TANY_MARKER => <&[Hint]>::default(),
_ => hints,
};
let (classname, s_res) = resolve_classname(alloc, tparams, name.to_owned());
let mut r = bumpalo::vec![in alloc];
if s_res.eq_ignore_ascii_case("tuple") || s_res.eq_ignore_ascii_case("shape") {
r.push(encode_kind(TypeStructureKind::T_unresolved));
} else {
r.push(encode_kind(ts_kind(tparams, s_res.as_str())));
}
if let Some(c) = classname {
r.push(c);
}
if !(name.eq_ignore_ascii_case(classes::CLASS_NAME)
|| name.eq_ignore_ascii_case(classes::TYPE_NAME))
{
r.append(&mut get_generic_types(
alloc,
opts,
tparams,
targ_map,
type_refinement_in_hint,
hints,
)?);
};
r
}
Hint_::Hwildcard => {
let (classname, _s_res) = resolve_classname(alloc, &[], "_".to_owned());
let mut r = bumpalo::vec![in alloc];
r.push(encode_kind(TypeStructureKind::T_typevar));
if let Some(c) = classname {
r.push(c);
}
r
}
Hint_::Hshape(si) => {
let mut r = bumpalo::vec![in alloc];
if let Some(v) = shape_allows_unknown_fields(si) {
r.push(v);
}
r.push(encode_kind(TypeStructureKind::T_shape));
r.push(encode_entry(
"fields",
shape_info_to_typed_value(
alloc,
opts,
tparams,
targ_map,
type_refinement_in_hint,
si,
)?,
));
r
}
Hint_::Haccess(Hint(_, h), ids) => match h.as_happly() {
Some((root_id, hs)) if hs.is_empty() => {
bumpalo::vec![in alloc;
encode_kind(TypeStructureKind::T_typeaccess),
encode_root_name(alloc, &root_id.1),
encode_entry(
"access_list",
type_constant_access_list(alloc, ids),
)
]
}
_ => {
return Err(Error::unrecoverable(
"Structure not translated according to ast_to_nast",
));
}
},
Hint_::Hfun(hf) => {
let mut r = bumpalo::vec![in alloc];
r.push(encode_kind(TypeStructureKind::T_fun));
let single_hint = |name: &str, h| {
hint_to_type_constant(alloc, opts, tparams, targ_map, h, type_refinement_in_hint)
.map(|tc| bumpalo::vec![in alloc; encode_entry(alloc.alloc_str(name), tc)])
};
let mut return_type = single_hint("return_type", &hf.return_ty)?;
let mut variadic_type = hf.variadic_ty.as_ref().map_or_else(
|| Ok(bumpalo::vec![in alloc]),
|h| single_hint("variadic_type", h),
)?;
let mut param_types = bumpalo::vec![in alloc;
encode_entry("param_types",
hints_to_type_constant(alloc, opts, tparams, targ_map, type_refinement_in_hint, &hf.param_tys)?,
)];
param_types.append(&mut variadic_type);
return_type.append(&mut param_types);
r.append(&mut return_type);
r
}
Hint_::Htuple(hints) => {
let mut r = bumpalo::vec![in alloc];
r.push(encode_kind(TypeStructureKind::T_tuple));
r.push(encode_entry(
"elem_types",
hints_to_type_constant(
alloc,
opts,
tparams,
targ_map,
type_refinement_in_hint,
hints,
)?,
));
r
}
Hint_::Hoption(h) => {
let mut r = bumpalo::vec![in alloc];
r.push(encode_entry("nullable", TypedValue::Bool(true)));
r.append(&mut hint_to_type_constant_list(
alloc,
opts,
tparams,
targ_map,
type_refinement_in_hint,
h,
)?);
r
}
Hint_::Hsoft(h) => {
let mut r = bumpalo::vec![in alloc];
r.push(encode_entry("soft", TypedValue::Bool(true)));
r.append(&mut hint_to_type_constant_list(
alloc,
opts,
tparams,
targ_map,
type_refinement_in_hint,
h,
)?);
r
}
Hint_::Hlike(h) => {
let mut r = bumpalo::vec![in alloc];
r.append(&mut hint_to_type_constant_list(
alloc,
opts,
tparams,
targ_map,
type_refinement_in_hint,
h,
)?);
r
}
// TODO(coeffects) actually handle emission of context constants
Hint_::Hintersection(_) => {
let mut r = bumpalo::vec![in alloc];
r.push(encode_kind(TypeStructureKind::T_mixed));
r
}
Hint_::Hunion(hints) => {
let mut r = bumpalo::vec![in alloc];
r.push(encode_kind(TypeStructureKind::T_union));
r.append(&mut get_union_types(
alloc,
opts,
tparams,
targ_map,
type_refinement_in_hint,
hints,
)?);
r
}
Hint_::Hrefinement(h, _) => {
match type_refinement_in_hint {
TypeRefinementInHint::Disallowed => {
let aast::Hint(pos, _) = h;
return Err(Error::fatal_parse(pos, "Refinement in type structure"));
}
TypeRefinementInHint::Allowed => {
// check recursively (e.g.: Class<T1, T2> with { ... })
hint_to_type_constant_list(
alloc,
opts,
tparams,
targ_map,
TypeRefinementInHint::Allowed,
h,
)?
}
}
}
_ => {
return Err(Error::unrecoverable(
"Hints not available on the original AST",
));
}
})
}
pub(crate) fn typedef_to_type_structure<'a, 'arena>(
alloc: &'arena bumpalo::Bump,
opts: &Options,
tparams: &[&str],
typedef: &'a ast::Typedef,
) -> Result<TypedValue<'arena>> {
let mut tconsts = hint_to_type_constant_list(
alloc,
opts,
tparams,
&BTreeMap::new(),
TypeRefinementInHint::Disallowed, // Note: only called by `emit_typedef
&typedef.kind,
)?;
tconsts.append(&mut get_typevars(alloc, tparams));
if typedef.vis.is_opaque() || typedef.vis.is_opaque_module() {
tconsts.push(encode_entry("opaque", TypedValue::Bool(true)));
};
let mangled_name = hhbc_string_utils::mangle(typedef.name.1.clone());
let name = ffi::Str::new_str(alloc, hhbc_string_utils::strip_global_ns(&mangled_name));
let key = if typedef.vis.is_case_type() {
"case_type"
} else {
"alias"
};
tconsts.push(encode_entry(key, TypedValue::string(name)));
Ok(TypedValue::dict(tconsts.into_bump_slice()))
}
pub(crate) fn hint_to_type_constant<'arena>(
alloc: &'arena bumpalo::Bump,
opts: &Options,
tparams: &[&str],
targ_map: &BTreeMap<&str, i64>,
hint: &Hint,
type_refinement_in_hint: TypeRefinementInHint,
) -> Result<TypedValue<'arena>> {
let tconsts = hint_to_type_constant_list(
alloc,
opts,
tparams,
targ_map,
type_refinement_in_hint,
hint,
)?;
Ok(TypedValue::dict(tconsts.into_bump_slice()))
}
fn hints_to_type_constant<'arena>(
alloc: &'arena bumpalo::Bump,
opts: &Options,
tparams: &[&str],
targ_map: &BTreeMap<&str, i64>,
type_refinement_in_hint: TypeRefinementInHint,
hints: &[Hint],
) -> Result<TypedValue<'arena>> {
hints
.iter()
.map(|h| hint_to_type_constant(alloc, opts, tparams, targ_map, h, type_refinement_in_hint))
.collect::<Result<Vec<_>>>()
.map(|hs| TypedValue::vec(alloc.alloc_slice_fill_iter(hs.into_iter())))
} |
Rust | hhvm/hphp/hack/src/hackc/emitter/emit_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.
#![feature(box_patterns)]
mod emit_adata;
mod emit_attribute;
mod emit_body;
mod emit_class;
mod emit_constant;
mod emit_expression;
mod emit_fatal;
mod emit_file_attributes;
mod emit_function;
mod emit_memoize_function;
mod emit_memoize_helpers;
mod emit_memoize_method;
mod emit_method;
mod emit_module;
mod emit_native_opcode;
mod emit_param;
mod emit_property;
mod emit_statement;
mod emit_type_constant;
mod emit_typedef;
mod emit_xhp;
mod generator;
mod reified_generics_helpers;
mod try_finally_rewriter;
mod xhp_attribute;
use std::borrow::Borrow;
use std::collections::HashSet;
use std::collections::VecDeque;
use std::sync::Arc;
use decl_provider::DeclProvider;
use decl_provider::TypeDecl;
use emit_class::emit_classes_from_program;
use emit_constant::emit_constants_from_program;
use emit_file_attributes::emit_file_attributes_from_program;
use emit_function::emit_functions_from_program;
use emit_module::emit_module_use_from_program;
use emit_module::emit_modules_from_program;
use emit_typedef::emit_typedefs_from_program;
use env::emitter::Emitter;
use env::Env;
use error::Error;
use error::ErrorKind;
use error::Result;
use ffi::Maybe::*;
use ffi::Slice;
use ffi::Str;
use hhbc::Fatal;
use hhbc::FatalOp;
use hhbc::Unit;
use oxidized::ast;
use oxidized::namespace_env;
use oxidized::pos::Pos;
use oxidized_by_ref::typing_defs;
use oxidized_by_ref::typing_defs_core::Exact;
// PUBLIC INTERFACE (ENTRY POINTS)
/// This is the entry point from hh_single_compile & fuzzer
pub fn emit_fatal_unit<'arena>(
alloc: &'arena bumpalo::Bump,
op: FatalOp,
pos: Pos,
msg: impl AsRef<str> + 'arena,
) -> Result<Unit<'arena>> {
Ok(Unit {
fatal: Just(Fatal {
op,
loc: pos.into(),
message: Str::new_str(alloc, msg.as_ref()),
}),
..Unit::default()
})
}
/// This is the entry point from hh_single_compile
pub fn emit_unit<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
namespace: Arc<namespace_env::Env>,
tast: &'a ast::Program,
) -> Result<Unit<'arena>> {
let result = emit_unit_(emitter, namespace, tast);
match result {
Err(e) => match e.into_kind() {
ErrorKind::IncludeTimeFatalException(op, pos, msg) => {
emit_fatal_unit(emitter.alloc, op, pos, msg)
}
ErrorKind::Unrecoverable(x) => Err(Error::unrecoverable(x)),
},
_ => result,
}
}
fn record_error<'arena>(
sym: Str<'arena>,
e: decl_provider::Error,
missing: &mut Vec<Str<'arena>>,
error: &mut Vec<Str<'arena>>,
) {
match e {
decl_provider::Error::NotFound => {
missing.push(sym);
}
decl_provider::Error::Bincode(_) => {
error.push(sym);
}
}
}
fn scan_types<'decl, F>(p: &dyn DeclProvider<'decl>, q: &mut VecDeque<(String, u64)>, mut efunc: F)
where
F: FnMut(&String, decl_provider::Error),
{
use typing_defs::Ty_;
let mut seen = HashSet::new();
q.iter().for_each(|(s, _i)| {
seen.insert(s.clone());
});
while let Some((name, idx)) = q.pop_front() {
match p.type_decl(&name, idx) {
Ok(TypeDecl::Class(class_decl)) => {
class_decl
.extends
.iter()
.chain(class_decl.implements.iter())
.chain(class_decl.req_class.iter())
.chain(class_decl.req_extends.iter())
.chain(class_decl.req_implements.iter())
.chain(class_decl.uses.iter())
.for_each(|ty| {
if let Ty_::Tclass(((_, cn), Exact::Exact, _ty_args)) = ty.1 {
if seen.insert(cn.to_string()) {
q.push_back((cn.to_string(), idx + 1))
}
}
});
}
Ok(TypeDecl::Typedef(_)) => {}
Err(e) => {
efunc(&name, e);
}
}
}
}
fn emit_unit_<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
namespace: Arc<namespace_env::Env>,
prog: &'a ast::Program,
) -> Result<Unit<'arena>> {
let prog = prog.as_slice();
let mut functions = emit_functions_from_program(emitter, prog)?;
let classes = emit_classes_from_program(emitter.alloc, emitter, prog)?;
let modules = emit_modules_from_program(emitter.alloc, emitter, prog)?;
let typedefs = emit_typedefs_from_program(emitter, prog)?;
let (constants, mut const_inits) = {
let mut env = Env::default(emitter.alloc, namespace);
emit_constants_from_program(emitter, &mut env, prog)?
};
functions.append(&mut const_inits);
let file_attributes = emit_file_attributes_from_program(emitter, prog)?;
let adata = emitter.adata_state_mut().take_adata();
let module_use = emit_module_use_from_program(emitter, prog);
let symbol_refs = emitter.finish_symbol_refs();
let fatal = Nothing;
let mut missing_syms = Vec::new();
let mut error_syms = Vec::new();
if let Some(p) = &emitter.decl_provider {
if emitter.options().hhbc.stress_shallow_decl_deps {
for cns in &symbol_refs.constants {
if let Err(e) = p.const_decl(cns.unsafe_as_str()) {
record_error(cns.as_ffi_str(), e, &mut missing_syms, &mut error_syms);
}
}
for fun in &symbol_refs.functions {
if let Err(e) = p.func_decl(fun.unsafe_as_str()) {
record_error(fun.as_ffi_str(), e, &mut missing_syms, &mut error_syms);
}
}
for cls in &symbol_refs.classes {
if let Err(e) = p.type_decl(cls.unsafe_as_str(), 0) {
record_error(cls.as_ffi_str(), e, &mut missing_syms, &mut error_syms);
}
}
}
if emitter.options().hhbc.stress_folded_decl_deps {
let mut q = VecDeque::new();
classes.iter().for_each(|c| {
if let Just(b) = c.base {
q.push_back((b.unsafe_into_string(), 0u64));
}
c.uses
.iter()
.chain(c.implements.iter())
.for_each(|i| q.push_back((i.unsafe_into_string(), 0u64)));
c.requirements
.iter()
.for_each(|r| q.push_back((r.name.unsafe_into_string(), 0u64)));
});
let error_func = |sym: &String, e: decl_provider::Error| {
let s = Str::new_str(emitter.alloc, sym.as_str());
record_error(s, e, &mut missing_syms, &mut error_syms);
};
scan_types(p.borrow(), &mut q, error_func);
}
}
Ok(Unit {
classes: Slice::fill_iter(emitter.alloc, classes.into_iter()),
modules: Slice::fill_iter(emitter.alloc, modules.into_iter()),
functions: Slice::fill_iter(emitter.alloc, functions.into_iter()),
typedefs: Slice::fill_iter(emitter.alloc, typedefs.into_iter()),
constants: Slice::fill_iter(emitter.alloc, constants.into_iter()),
adata: Slice::fill_iter(emitter.alloc, adata.into_iter()),
file_attributes: Slice::fill_iter(emitter.alloc, file_attributes.into_iter()),
module_use,
symbol_refs,
fatal,
missing_symbols: Slice::fill_iter(emitter.alloc, missing_syms.into_iter()),
error_symbols: Slice::fill_iter(emitter.alloc, error_syms.into_iter()),
})
}
#[derive(Clone, Copy, Debug)]
enum TypeRefinementInHint {
Allowed,
Disallowed,
} |
Rust | hhvm/hphp/hack/src/hackc/emitter/emit_xhp.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_property::PropAndInit;
use env::emitter::Emitter;
use error::Error;
use error::Result;
use hack_macros::hack_expr;
use hack_macros::hack_stmts;
use hhbc::Method;
use hhbc_string_utils as string_utils;
use oxidized::ast::*;
use oxidized::ast_defs;
use oxidized::pos::Pos;
use crate::emit_method;
use crate::emit_property;
use crate::xhp_attribute::XhpAttribute;
pub fn properties_for_cache<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
class: &'a Class_,
class_is_const: bool,
class_is_closure: bool,
) -> Result<PropAndInit<'arena>> {
let initial_value = Some(Expr((), Pos::NONE, Expr_::mk_null()));
emit_property::from_ast(
emitter,
class,
&[],
class_is_const,
class_is_closure,
emit_property::FromAstArgs {
initial_value: &initial_value,
visibility: Visibility::Private,
is_static: true,
is_abstract: false,
is_readonly: false,
typehint: None,
doc_comment: None,
user_attributes: &[],
id: &ast_defs::Id(Pos::NONE, "__xhpAttributeDeclarationCache".into()),
},
)
}
pub fn from_attribute_declaration<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
class: &'a Class_,
xal: &[XhpAttribute<'_>],
xual: &[Hint],
) -> Result<Method<'arena>> {
let mut args = vec![(
ParamKind::Pnormal,
hack_expr!("parent::__xhpAttributeDeclaration()"),
)];
for xua in xual.iter() {
match xua.1.as_happly() {
Some((ast_defs::Id(_, s), hints)) if hints.is_empty() => {
let s = string_utils::mangle(string_utils::strip_global_ns(s).into());
let arg = hack_expr!("#{id(s)}::__xhpAttributeDeclaration()");
args.push((ParamKind::Pnormal, arg));
}
_ => {
return Err(Error::unrecoverable(
"Xhp use attribute - unexpected attribute",
));
}
}
}
args.push((
ParamKind::Pnormal,
emit_xhp_attribute_array(emitter.alloc, xal)?,
));
let body = Block(hack_stmts!(
r#"
$r = self::$__xhpAttributeDeclarationCache;
if ($r === null) {
self::$__xhpAttributeDeclarationCache = __SystemLib\merge_xhp_attr_declarations(#{args*});
$r = self::$__xhpAttributeDeclarationCache;
}
return $r;
"#
));
from_xhp_attribute_declaration_method(
emitter,
class,
None,
"__xhpAttributeDeclaration",
false,
false,
true,
Visibility::Protected,
body,
)
}
pub fn from_children_declaration<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
ast_class: &'a Class_,
(pos, children): &(&ast_defs::Pos, Vec<&XhpChild>),
) -> Result<Method<'arena>> {
let children_arr = mk_expr(emit_xhp_children_array(children)?);
let body = Block(vec![Stmt(
(*pos).clone(),
Stmt_::mk_return(Some(children_arr)),
)]);
from_xhp_attribute_declaration_method(
emitter,
ast_class,
Some((*pos).clone()),
"__xhpChildrenDeclaration",
false,
false,
false,
Visibility::Protected,
body,
)
}
pub fn from_category_declaration<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
ast_class: &'a Class_,
(pos, categories): &(&ast_defs::Pos, Vec<&String>),
) -> Result<Method<'arena>> {
let category_arr = mk_expr(get_category_array(categories));
let body = Block(vec![mk_stmt(Stmt_::mk_return(Some(category_arr)))]);
from_xhp_attribute_declaration_method(
emitter,
ast_class,
Some((*pos).clone()),
"__xhpCategoryDeclaration",
false,
false,
false,
Visibility::Protected,
body,
)
}
fn get_category_array(categories: &[&String]) -> Expr_ {
// TODO: is this always 1?
Expr_::mk_darray(
None,
categories
.iter()
.map(|&s| {
(
mk_expr(Expr_::String(s.clone().into())),
mk_expr(Expr_::Int("1".into())),
)
})
.collect(),
)
}
fn emit_xhp_children_array(children: &[&XhpChild]) -> Result<Expr_> {
match children {
[] => Ok(Expr_::mk_int("0".into())),
[c] => match c.as_child_name() {
Some(ast_defs::Id(_, n)) => {
if n.eq_ignore_ascii_case("empty") {
Ok(Expr_::mk_int("0".into()))
} else if n.eq_ignore_ascii_case("any") {
Ok(Expr_::mk_int("1".into()))
} else {
emit_xhp_children_paren_expr(c)
}
}
None => emit_xhp_children_paren_expr(c),
},
_ => Err(Error::unrecoverable(
"HHVM does not support multiple children declarations",
)),
}
}
fn emit_xhp_children_paren_expr(child: &XhpChild) -> Result<Expr_> {
let (children, op_num) = if let Some(l) = child.as_child_list() {
(l, xhp_child_op_to_int(None))
} else if let Some((Some(l), op)) = child
.as_child_unary()
.map(|(c, op)| (c.as_child_list(), op))
{
(l, xhp_child_op_to_int(Some(op)))
} else {
return Err(Error::unrecoverable(concat!(
"Xhp children declarations cannot be plain id, ",
"plain binary or unary without an inside list"
)));
};
let arr = emit_xhp_children_decl_expr("0", children)?;
get_array3(Expr_::Int(op_num.to_string()), Expr_::Int("5".into()), arr)
}
fn emit_xhp_children_decl_expr(unary: &str, children: &[XhpChild]) -> Result<Expr_> {
match children {
[] => Err(Error::unrecoverable("xhp children: unexpected empty list")),
[c] => emit_xhp_child_decl(unary, c),
[c1, c2, cs @ ..] => {
let first_two = get_array3(
Expr_::Int("4".into()),
emit_xhp_child_decl(unary, c1)?,
emit_xhp_child_decl(unary, c2)?,
);
cs.iter().fold(first_two, |acc, c| {
get_array3(Expr_::Int("4".into()), acc?, emit_xhp_child_decl(unary, c)?)
})
}
}
}
fn emit_xhp_child_decl(unary: &str, child: &XhpChild) -> Result<Expr_> {
match child {
XhpChild::ChildList(l) => get_array3(
Expr_::Int(unary.into()),
Expr_::Int("5".into()),
emit_xhp_children_decl_expr("0", l)?,
),
XhpChild::ChildName(ast_defs::Id(_, name)) => {
if name.eq_ignore_ascii_case("any") {
get_array3(
Expr_::Int(unary.into()),
Expr_::Int("1".into()),
Expr_::Null,
)
} else if name.eq_ignore_ascii_case("pcdata") {
get_array3(
Expr_::Int(unary.into()),
Expr_::Int("2".into()),
Expr_::Null,
)
} else if let Some(end) = name.strip_prefix('%') {
get_array3(
Expr_::Int(unary.into()),
Expr_::Int("4".into()),
Expr_::String(string_utils::mangle(end.into()).into()),
)
} else {
get_array3(
Expr_::Int(unary.into()),
Expr_::Int("3".into()),
Expr_::String(string_utils::mangle(name.into()).into()),
)
}
}
XhpChild::ChildUnary(c, op) => {
emit_xhp_child_decl(xhp_child_op_to_int(Some(op)).to_string().as_str(), c)
}
XhpChild::ChildBinary(c1, c2) => get_array3(
Expr_::Int("5".into()),
emit_xhp_child_decl(unary, c1)?,
emit_xhp_child_decl(unary, c2)?,
),
}
}
fn get_array3(i0: Expr_, i1: Expr_, i2: Expr_) -> Result<Expr_> {
Ok(Expr_::mk_varray(
None,
vec![mk_expr(i0), mk_expr(i1), mk_expr(i2)],
))
}
fn xhp_child_op_to_int(op: Option<&XhpChildOp>) -> usize {
match op {
None => 0,
Some(XhpChildOp::ChildStar) => 1,
Some(XhpChildOp::ChildQuestion) => 2,
Some(XhpChildOp::ChildPlus) => 3,
}
}
fn emit_xhp_attribute_array<'arena>(
alloc: &'arena bumpalo::Bump,
xal: &[XhpAttribute<'_>],
) -> Result<Expr> {
fn hint_to_num(id: &str) -> usize {
match id {
"HH\\string" => 1,
"HH\\bool" => 2,
"HH\\int" => 3,
"array" => 4,
"var" | "HH\\mixed" => 6,
"enum" => 7,
"HH\\float" => 8,
"callable" => 9,
// Regular class names are type 5
_ => 5,
}
}
fn get_enum_attributes(enum_opt: Option<&Vec<Expr>>) -> Result<Expr> {
match enum_opt {
None => Err(Error::unrecoverable(
"Xhp attribute that's supposed to be an enum but not really",
)),
Some(es) => Ok(mk_expr(Expr_::mk_varray(None, es.to_vec()))),
}
}
fn get_attribute_array_values<'arena>(
alloc: &'arena bumpalo::Bump,
id: &str,
enum_opt: Option<&Vec<Expr>>,
) -> Result<(Expr, Expr)> {
let id = hhbc::ClassName::from_ast_name_and_mangle(alloc, id).unsafe_as_str();
let type_ = hint_to_num(id);
let type_ident = mk_expr(Expr_::Int(type_.to_string()));
let class_name = match type_ {
5 => mk_expr(Expr_::String(id.into())),
7 => get_enum_attributes(enum_opt)?,
_ => mk_expr(Expr_::Null),
};
Ok((class_name, type_ident))
}
fn extract_from_hint<'arena>(
alloc: &'arena bumpalo::Bump,
hint: &Hint,
enum_opt: Option<&Vec<Expr>>,
) -> Result<(Expr, Expr)> {
match &*(hint.1) {
Hint_::Hlike(h) | Hint_::Hoption(h) => extract_from_hint(alloc, h, enum_opt),
Hint_::Happly(ast_defs::Id(_, id), _) => {
get_attribute_array_values(alloc, id, enum_opt)
}
_ => Err(Error::unrecoverable(
"There are no other possible xhp attribute hints",
)),
}
}
fn inner_array<'arena>(
alloc: &'arena bumpalo::Bump,
xa: &XhpAttribute<'_>,
) -> Result<Vec<Expr>> {
let enum_opt = xa.maybe_enum.map(|(_, es)| es);
let expr = match &(xa.class_var).expr {
Some(e) => e.clone(),
None => mk_expr(Expr_::Null),
};
let (class_name, hint) = match &xa.type_ {
// attribute declared with the var identifier - we treat it as mixed
None if enum_opt.is_none() => {
get_attribute_array_values(alloc, "\\HH\\mixed", enum_opt)
}
None => get_attribute_array_values(alloc, "enum", enum_opt),
// As it turns out, if there is a type list, HHVM discards it
Some(h) => extract_from_hint(alloc, h, enum_opt),
}?;
let is_required = mk_expr(Expr_::Int(
(if xa.is_required() { "1" } else { "0" }).into(),
));
Ok(vec![hint, class_name, expr, is_required])
}
fn emit_xhp_attribute<'arena>(
alloc: &'arena bumpalo::Bump,
xa: &XhpAttribute<'_>,
) -> Result<(Expr, Expr)> {
let k = mk_expr(Expr_::String(
string_utils::clean(&((xa.class_var).id).1).into(),
));
let v = mk_expr(Expr_::mk_varray(None, inner_array(alloc, xa)?));
Ok((k, v))
}
let xal_arr = xal
.iter()
.map(|x| emit_xhp_attribute(alloc, x))
.collect::<Result<Vec<_>>>()?;
Ok(mk_expr(Expr_::mk_darray(None, xal_arr)))
}
fn from_xhp_attribute_declaration_method<'a, 'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
class: &'a Class_,
pos: Option<Pos>,
name: &str,
final_: bool,
abstract_: bool,
static_: bool,
visibility: Visibility,
fb_ast: Block,
) -> Result<Method<'arena>> {
let meth = Method_ {
span: pos.clone().unwrap_or(Pos::NONE),
annotation: (),
final_,
abstract_,
static_,
readonly_this: false, // TODO readonly emitter
visibility,
name: ast_defs::Id(Pos::NONE, name.into()),
tparams: vec![],
where_constraints: vec![],
params: vec![],
ctxs: Some(Contexts(pos.unwrap_or(Pos::NONE), vec![])),
unsafe_ctxs: None,
body: FuncBody { fb_ast },
fun_kind: ast_defs::FunKind::FSync,
user_attributes: Default::default(),
readonly_ret: None, // TODO readonly emitter
ret: TypeHint((), None),
external: false,
doc_comment: None,
};
emit_method::from_ast(emitter, class, meth)
}
fn mk_expr(expr_: Expr_) -> Expr {
Expr((), Pos::NONE, expr_)
}
fn mk_stmt(stmt_: Stmt_) -> Stmt {
Stmt(Pos::NONE, stmt_)
} |
Rust | hhvm/hphp/hack/src/hackc/emitter/env.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 adata_state;
mod class_expr;
pub mod emitter; // emitter is public API for mutating state
mod iterator;
pub mod jump_targets;
mod label;
mod local;
use std::sync::Arc;
use ast_scope::Scope;
use ast_scope::ScopeItem;
use bitflags::bitflags;
pub use class_expr::ClassExpr;
use emitter::Emitter;
use hhbc::IterId;
use hhbc::Label;
use hhbc::Local;
pub use iterator::*;
pub use label::*;
pub use local::*;
use oxidized::ast;
use oxidized::namespace_env::Env as NamespaceEnv;
bitflags! {
#[derive(Default)]
pub struct Flags: u8 {
const NEEDS_LOCAL_THIS = 0b0000_0001;
const IN_TRY = 0b0000_0010;
const ALLOWS_ARRAY_APPEND = 0b0000_0100;
}
}
/// `'a` is an AST lifetime, `'arena` the lifetime of the `InstrSeq`
/// arena.
#[derive(Clone, Debug)]
pub struct Env<'a, 'arena> {
pub arena: &'arena bumpalo::Bump,
pub flags: Flags,
pub jump_targets_gen: jump_targets::Gen,
pub scope: Scope<'a, 'arena>,
pub namespace: Arc<NamespaceEnv>,
pub call_context: Option<String>,
pub pipe_var: Option<Local>,
}
impl<'a, 'arena> Env<'a, 'arena> {
pub fn default(arena: &'arena bumpalo::Bump, namespace: Arc<NamespaceEnv>) -> Self {
Env {
arena,
namespace,
flags: Flags::default(),
jump_targets_gen: jump_targets::Gen::default(),
scope: Scope::default(),
call_context: None,
pipe_var: None,
}
}
pub fn with_allows_array_append<F, R>(&mut self, alloc: &'arena bumpalo::Bump, f: F) -> R
where
F: FnOnce(&'arena bumpalo::Bump, &mut Self) -> R,
{
let old = self.flags.contains(Flags::ALLOWS_ARRAY_APPEND);
self.flags.set(Flags::ALLOWS_ARRAY_APPEND, true);
let r = f(alloc, self);
self.flags.set(Flags::ALLOWS_ARRAY_APPEND, old);
r
}
pub fn with_need_local_this(&mut self, need_local_this: bool) {
if need_local_this {
self.flags |= Flags::NEEDS_LOCAL_THIS;
}
}
pub fn with_pipe_var(&mut self, local: Local) {
self.pipe_var = Some(local);
}
pub fn with_scope(mut self, scope: Scope<'a, 'arena>) -> Env<'a, 'arena> {
self.scope = scope;
self
}
pub fn make_class_env(arena: &'arena bumpalo::Bump, class: &'a ast::Class_) -> Env<'a, 'arena> {
let scope = Scope::with_item(ScopeItem::Class(ast_scope::Class::new_ref(class)));
Env::default(arena, Arc::clone(&class.namespace)).with_scope(scope)
}
pub fn do_in_loop_body<'decl, R, F>(
&mut self,
e: &mut Emitter<'arena, 'decl>,
label_break: Label,
label_continue: Label,
iterator: Option<IterId>,
b: &[ast::Stmt],
f: F,
) -> R
where
F: FnOnce(&mut Self, &mut Emitter<'arena, 'decl>, &[ast::Stmt]) -> R,
{
self.jump_targets_gen
.with_loop(label_break, label_continue, iterator);
self.run_and_release_ids(e, |env, e| f(env, e, b))
}
pub fn do_in_switch_body<'decl, R, F>(
&mut self,
e: &mut Emitter<'arena, 'decl>,
end_label: Label,
cases: &[ast::Case],
dfl: &Option<ast::DefaultCase>,
f: F,
) -> R
where
F: FnOnce(
&mut Self,
&mut Emitter<'arena, 'decl>,
&[ast::Case],
&Option<ast::DefaultCase>,
) -> R,
{
self.jump_targets_gen.with_switch(end_label);
self.run_and_release_ids(e, |env, e| f(env, e, cases, dfl))
}
pub fn do_in_try_catch_body<'decl, R, F>(
&mut self,
e: &mut Emitter<'arena, 'decl>,
finally_label: Label,
try_block: &[ast::Stmt],
catch_block: &[ast::Catch],
f: F,
) -> R
where
F: FnOnce(&mut Self, &mut Emitter<'arena, 'decl>, &[ast::Stmt], &[ast::Catch]) -> R,
{
self.jump_targets_gen.with_try_catch(finally_label);
self.run_and_release_ids(e, |env, e| f(env, e, try_block, catch_block))
}
pub fn do_in_try_body<'decl, R, F>(
&mut self,
e: &mut Emitter<'arena, 'decl>,
finally_label: Label,
block: &[ast::Stmt],
f: F,
) -> R
where
F: FnOnce(&mut Self, &mut Emitter<'arena, 'decl>, &[ast::Stmt]) -> R,
{
self.jump_targets_gen.with_try(finally_label);
self.run_and_release_ids(e, |env, e| f(env, e, block))
}
pub fn do_in_finally_body<'decl, R, F>(
&mut self,
e: &mut Emitter<'arena, 'decl>,
block: &[ast::Stmt],
f: F,
) -> R
where
F: FnOnce(&mut Self, &mut Emitter<'arena, 'decl>, &[ast::Stmt]) -> R,
{
self.jump_targets_gen.with_finally();
self.run_and_release_ids(e, |env, e| f(env, e, block))
}
pub fn do_in_using_body<'decl, R, F>(
&mut self,
e: &mut Emitter<'arena, 'decl>,
finally_label: Label,
block: &[ast::Stmt],
f: F,
) -> R
where
F: FnOnce(&mut Self, &mut Emitter<'arena, 'decl>, &[ast::Stmt]) -> R,
{
self.jump_targets_gen.with_using(finally_label);
self.run_and_release_ids(e, |env, e| f(env, e, block))
}
pub fn do_function<'decl, R, F>(
&mut self,
e: &mut Emitter<'arena, 'decl>,
defs: &[ast::Stmt],
f: F,
) -> R
where
F: FnOnce(&mut Self, &mut Emitter<'arena, 'decl>, &[ast::Stmt]) -> R,
{
self.jump_targets_gen.with_function();
self.run_and_release_ids(e, |env, e| f(env, e, defs))
}
fn run_and_release_ids<'decl, R, F>(&mut self, e: &mut Emitter<'arena, 'decl>, f: F) -> R
where
F: FnOnce(&mut Self, &mut Emitter<'arena, 'decl>) -> R,
{
let res = f(self, e);
self.jump_targets_gen.release_ids();
self.jump_targets_gen.revert();
res
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn make_env() {
let a = bumpalo::Bump::new();
let alloc: &bumpalo::Bump = &a;
let namespace = Arc::new(NamespaceEnv::empty(vec![], false, false));
let _: Env<'_, '_> = Env::default(alloc, namespace);
}
} |
Rust | hhvm/hphp/hack/src/hackc/emitter/generator.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 oxidized::aast_visitor::visit;
use oxidized::aast_visitor::AstParams;
use oxidized::aast_visitor::Node;
use oxidized::aast_visitor::Visitor;
use oxidized::ast;
pub fn is_function_generator<'a>(body: &'a [ast::Stmt]) -> (bool, bool) {
struct S((bool, bool));
impl<'ast> Visitor<'ast> for S {
type Params = AstParams<(), ()>;
fn object(&mut self) -> &mut dyn Visitor<'ast, Params = Self::Params> {
self
}
fn visit_stmt_(&mut self, c: &mut (), stmt_: &ast::Stmt_) -> Result<(), ()> {
match stmt_ {
ast::Stmt_::YieldBreak => Ok((self.0).0 = true),
_ => stmt_.recurse(c, self),
}
}
fn visit_expr_(&mut self, c: &mut (), expr_: &ast::Expr_) -> Result<(), ()> {
match expr_ {
ast::Expr_::Yield(afield) => Ok(match afield.as_ref() {
ast::Afield::AFvalue(_) => (self.0).0 = true,
ast::Afield::AFkvalue(_, _) => self.0 = (true, true),
}),
_ => expr_.recurse(c, self),
}
}
fn visit_class_(&mut self, _: &mut (), _: &ast::Class_) -> Result<(), ()> {
Ok(())
}
fn visit_fun_(&mut self, _: &mut (), _: &ast::Fun_) -> Result<(), ()> {
Ok(())
}
}
let mut state = S((false, false));
visit(&mut state, &mut (), &body).unwrap();
state.0
} |
Rust | hhvm/hphp/hack/src/hackc/emitter/global_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 std::sync::Arc;
use hhbc::Coeffects;
use oxidized::ast_defs::Abstraction;
use oxidized::ast_defs::ClassishKind;
use oxidized::namespace_env::Env as NamespaceEnv;
use unique_id_builder::get_unique_id_for_method;
use unique_id_builder::SMap;
use unique_id_builder::SSet;
#[derive(Debug, Clone)]
pub struct ClosureEnclosingClassInfo {
pub kind: ClassishKind,
pub name: String,
pub parent_class_name: Option<String>,
}
impl Default for ClosureEnclosingClassInfo {
fn default() -> Self {
Self {
kind: ClassishKind::Cclass(Abstraction::Concrete),
name: "".to_string(),
parent_class_name: None,
}
}
}
#[derive(Default, Debug)]
pub struct GlobalState<'arena> {
pub explicit_use_set: SSet,
pub closure_namespaces: SMap<Arc<NamespaceEnv>>,
pub closure_enclosing_classes: SMap<ClosureEnclosingClassInfo>,
pub lambda_coeffects_of_scope: SMap<Coeffects<'arena>>,
}
impl<'arena> GlobalState<'arena> {
pub fn init() -> Self {
GlobalState::default()
}
pub fn get_lambda_coeffects_of_scope(
&self,
class_name: &str,
meth_name: &str,
) -> Option<&Coeffects<'arena>> {
let key = get_unique_id_for_method(class_name, meth_name);
self.lambda_coeffects_of_scope.get(&key)
}
pub fn get_closure_enclosing_class(
&self,
class_name: &str,
) -> Option<&ClosureEnclosingClassInfo> {
self.closure_enclosing_classes.get(class_name)
}
} |
Rust | hhvm/hphp/hack/src/hackc/emitter/instruction_sequence.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::Slice;
use hhbc::Instruct;
use hhbc::Pseudo;
/// The various from_X functions below take some kind of AST
/// (expression, statement, etc.) and produce what is logically a
/// sequence of instructions. This could be represented by a list, but
/// we wish to avoid the quadratic complexity associated with repeated
/// appending. So, we build a tree of instructions which can be
/// flattened when complete.
#[derive(Debug, Clone)]
pub enum InstrSeq<'a> {
List(Vec<Instruct<'a>>),
Concat(Vec<InstrSeq<'a>>),
}
// The following iterator implementations produce streams of instruction lists
// (vecs or slices) and use an internal stack to flatten InstrSeq. The
// instruction lists can be manipulated directly, doing bulk opertaions like
// extend() or retain(), or flatten()'d once more into streams of instructions.
//
// Some tricks that were done for speed:
// * keep the top-of-stack iterator in a dedicated field
// * filter out empty lists - consumers of the iterator only see nonempty lists.
//
// Some other tricks didn't seem to help and were abandoned:
// * on Concat, if the current `top` iterator is empty, can just overwrite
// with a new iterator instead of pushing it and later having to pop it.
// * Skipping empty Concat sequences.
// * Special cases for 1-entry Lists.
//
// Future ideas to try:
// * use SmallVec for the stack. Can it eliminate the need for `top`?
/// An iterator that owns an InstrSeq and produces a stream of owned lists
/// of instructions: `Vec<Instruct>`.
#[derive(Debug)]
struct IntoListIter<'a> {
// Keeping top-of-stack in its own field for speed.
top: std::vec::IntoIter<InstrSeq<'a>>,
stack: Vec<std::vec::IntoIter<InstrSeq<'a>>>,
}
impl<'a> IntoListIter<'a> {
pub fn new(iseq: InstrSeq<'a>) -> Self {
Self {
top: match iseq {
InstrSeq::List(_) => vec![iseq].into_iter(),
InstrSeq::Concat(s) => s.into_iter(),
},
stack: Vec::new(),
}
}
}
impl<'a> Iterator for IntoListIter<'a> {
type Item = Vec<Instruct<'a>>;
fn next(&mut self) -> Option<Self::Item> {
loop {
match self.top.next() {
// Short-circuit the empty list case for speed
Some(InstrSeq::List(s)) if s.is_empty() => {}
Some(InstrSeq::List(s)) => break Some(s),
Some(InstrSeq::Concat(s)) => self
.stack
.push(std::mem::replace(&mut self.top, s.into_iter())),
None => match self.stack.pop() {
Some(top) => self.top = top,
None => break None,
},
}
}
}
}
/// An iterator that borrows an InstrSeq and produces a stream of borrowed
/// slices of instructions: `&[Instruct]`.
#[derive(Debug)]
struct ListIter<'i, 'a> {
// Keeping top-of-stack in its own field for speed.
top: std::slice::Iter<'i, InstrSeq<'a>>,
stack: Vec<std::slice::Iter<'i, InstrSeq<'a>>>,
}
impl<'i, 'a> ListIter<'i, 'a> {
fn new(iseq: &'i InstrSeq<'a>) -> Self {
Self {
top: match iseq {
InstrSeq::List(_) => std::slice::from_ref(iseq).iter(),
InstrSeq::Concat(s) => s.iter(),
},
stack: Vec::new(),
}
}
}
impl<'i, 'a> Iterator for ListIter<'i, 'a> {
type Item = &'i [Instruct<'a>];
fn next(&mut self) -> Option<Self::Item> {
loop {
match self.top.next() {
// Short-circuit the empty list case for speed
Some(InstrSeq::List(s)) if s.is_empty() => {}
Some(InstrSeq::List(s)) => break Some(s),
Some(InstrSeq::Concat(s)) => {
self.stack.push(std::mem::replace(&mut self.top, s.iter()))
}
None => match self.stack.pop() {
Some(top) => self.top = top,
None => break None,
},
}
}
}
}
/// An iterator that borrows a mutable InstrSeq and produces a stream of
/// borrowed lists of instructions: `&mut Vec<Instruct>`. This is a borrowed
/// Vec instead of a borrowed slice so sub-sequences of instructions can
/// grow or shrink independently, for example by retain().
#[derive(Debug)]
struct ListIterMut<'i, 'a> {
top: std::slice::IterMut<'i, InstrSeq<'a>>,
stack: Vec<std::slice::IterMut<'i, InstrSeq<'a>>>,
}
impl<'i, 'a> ListIterMut<'i, 'a> {
fn new(iseq: &'i mut InstrSeq<'a>) -> Self {
Self {
top: match iseq {
InstrSeq::List(_) => std::slice::from_mut(iseq).iter_mut(),
InstrSeq::Concat(s) => s.iter_mut(),
},
stack: Vec::new(),
}
}
}
impl<'i, 'a> Iterator for ListIterMut<'i, 'a> {
type Item = &'i mut Vec<Instruct<'a>>;
fn next(&mut self) -> Option<Self::Item> {
loop {
match self.top.next() {
// Short-circuit the empty list case for speed
Some(InstrSeq::List(s)) if s.is_empty() => {}
Some(InstrSeq::List(s)) => break Some(s),
Some(InstrSeq::Concat(s)) => self
.stack
.push(std::mem::replace(&mut self.top, s.iter_mut())),
None => match self.stack.pop() {
Some(top) => self.top = top,
None => break None,
},
}
}
}
}
pub mod instr {
use ffi::Slice;
use ffi::Str;
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::Instruct;
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::Pseudo;
use hhbc::QueryMOp;
use hhbc::ReadonlyOp;
use hhbc::RepoAuthType;
use hhbc::SetOpOp;
use hhbc::SetRangeOp;
use hhbc::SilenceOp;
use hhbc::SpecialClsRef;
use hhbc::SrcLoc;
use hhbc::StackIndex;
use hhbc::SwitchKind;
use hhbc::TypeStructResolveOp;
use crate::InstrSeq;
// This macro builds helper functions for each of the given opcodes. See
// the definition of define_instr_seq_helpers for details.
emit_opcodes_macro::define_instr_seq_helpers! {
// These get custom implementations below.
FCallClsMethod | FCallClsMethodM | FCallClsMethodD | FCallClsMethodS | FCallClsMethodSD |
FCallCtor | FCallObjMethod | FCallObjMethodD | MemoGetEager |
NewStructDict | SSwitch | String | Switch => {}
// These are "custom" names that don't match the simple snake-case of
// their Opcodes.
Await => await_,
False => false_,
Mod => mod_,
True => true_,
Yield => yield_,
}
pub fn empty<'a>() -> InstrSeq<'a> {
InstrSeq::new_empty()
}
pub fn instr<'a>(i: Instruct<'a>) -> InstrSeq<'a> {
InstrSeq::List(vec![i])
}
pub(crate) fn instrs<'a>(is: Vec<Instruct<'a>>) -> InstrSeq<'a> {
InstrSeq::List(is)
}
// Special constructors for Opcode
pub fn cont_check_check<'a>() -> InstrSeq<'a> {
cont_check(ContCheckOp::CheckStarted)
}
pub fn cont_check_ignore<'a>() -> InstrSeq<'a> {
cont_check(ContCheckOp::IgnoreStarted)
}
pub fn dim_warn_pt<'a>(key: PropName<'a>, readonly_op: ReadonlyOp) -> InstrSeq<'a> {
dim(MOpMode::Warn, MemberKey::PT(key, readonly_op))
}
pub fn f_call_cls_method<'a>(
log: IsLogAsDynamicCallOp,
fcall_args: FCallArgs<'a>,
) -> InstrSeq<'a> {
instr(Instruct::Opcode(Opcode::FCallClsMethod(
fcall_args,
Default::default(),
log,
)))
}
pub fn f_call_cls_method_m<'a>(
log: IsLogAsDynamicCallOp,
fcall_args: FCallArgs<'a>,
method: MethodName<'a>,
) -> InstrSeq<'a> {
instr(Instruct::Opcode(Opcode::FCallClsMethodM(
fcall_args,
Default::default(),
log,
method,
)))
}
pub fn f_call_cls_method_d<'a>(
fcall_args: FCallArgs<'a>,
method: MethodName<'a>,
class: ClassName<'a>,
) -> InstrSeq<'a> {
instr(Instruct::Opcode(Opcode::FCallClsMethodD(
fcall_args, class, method,
)))
}
pub fn f_call_cls_method_s<'a>(
fcall_args: FCallArgs<'a>,
clsref: SpecialClsRef,
) -> InstrSeq<'a> {
instr(Instruct::Opcode(Opcode::FCallClsMethodS(
fcall_args,
Default::default(),
clsref,
)))
}
pub fn f_call_cls_method_sd<'a>(
fcall_args: FCallArgs<'a>,
clsref: SpecialClsRef,
method: MethodName<'a>,
) -> InstrSeq<'a> {
instr(Instruct::Opcode(Opcode::FCallClsMethodSD(
fcall_args,
Default::default(),
clsref,
method,
)))
}
pub fn f_call_ctor<'a>(fcall_args: FCallArgs<'a>) -> InstrSeq<'a> {
instr(Instruct::Opcode(Opcode::FCallCtor(
fcall_args,
Default::default(),
)))
}
pub fn f_call_obj_method<'a>(fcall_args: FCallArgs<'a>, flavor: ObjMethodOp) -> InstrSeq<'a> {
instr(Instruct::Opcode(Opcode::FCallObjMethod(
fcall_args,
Default::default(),
flavor,
)))
}
pub fn f_call_obj_method_d_<'a>(
fcall_args: FCallArgs<'a>,
method: MethodName<'a>,
flavor: ObjMethodOp,
) -> InstrSeq<'a> {
instr(Instruct::Opcode(Opcode::FCallObjMethodD(
fcall_args,
Default::default(),
flavor,
method,
)))
}
pub fn f_call_obj_method_d<'a>(
fcall_args: FCallArgs<'a>,
method: MethodName<'a>,
) -> InstrSeq<'a> {
f_call_obj_method_d_(fcall_args, method, ObjMethodOp::NullThrows)
}
pub fn is_type_struct_c_dontresolve<'a>() -> InstrSeq<'a> {
is_type_struct_c(TypeStructResolveOp::DontResolve)
}
pub fn is_type_struct_c_resolve<'a>() -> InstrSeq<'a> {
is_type_struct_c(TypeStructResolveOp::Resolve)
}
pub fn iter_break<'a>(label: Label, iters: Vec<IterId>) -> InstrSeq<'a> {
let mut vec: Vec<Instruct<'a>> = iters
.into_iter()
.map(|i| Instruct::Opcode(Opcode::IterFree(i)))
.collect();
vec.push(Instruct::Opcode(Opcode::Jmp(label)));
instrs(vec)
}
pub fn memo_get_eager<'a>(label1: Label, label2: Label, range: LocalRange) -> InstrSeq<'a> {
instr(Instruct::Opcode(Opcode::MemoGetEager(
[label1, label2],
// Need dummy immediate here to satisfy opcodes translator expectation of immediate
// with name _0.
Dummy::DEFAULT,
range,
)))
}
pub fn new_struct_dict<'a>(alloc: &'a bumpalo::Bump, keys: &'a [&'a str]) -> InstrSeq<'a> {
let keys = Slice::new(alloc.alloc_slice_fill_iter(keys.iter().map(|s| Str::from(*s))));
instr(Instruct::Opcode(Opcode::NewStructDict(keys)))
}
pub fn set_m_pt<'a>(
num_params: NumParams,
key: PropName<'a>,
readonly_op: ReadonlyOp,
) -> InstrSeq<'a> {
set_m(num_params, MemberKey::PT(key, readonly_op))
}
pub fn silence_end<'a>(local: Local) -> InstrSeq<'a> {
silence(local, SilenceOp::End)
}
pub fn silence_start<'a>(local: Local) -> InstrSeq<'a> {
silence(local, SilenceOp::Start)
}
pub fn s_switch<'a>(
alloc: &'a bumpalo::Bump,
cases: bumpalo::collections::Vec<'a, (&'a str, Label)>,
) -> InstrSeq<'a> {
let targets = alloc
.alloc_slice_fill_iter(cases.iter().map(|(_, target)| *target))
.into();
let cases = alloc
.alloc_slice_fill_iter(cases.into_iter().map(|(s, _)| Str::from(s)))
.into();
instr(Instruct::Opcode(Opcode::SSwitch {
cases,
targets,
_0: Dummy::DEFAULT,
}))
}
pub fn string<'a>(alloc: &'a bumpalo::Bump, litstr: impl Into<String>) -> InstrSeq<'a> {
instr(Instruct::Opcode(Opcode::String(Str::from(
bumpalo::collections::String::from_str_in(litstr.into().as_str(), alloc)
.into_bump_str(),
))))
}
pub fn switch<'a>(targets: bumpalo::collections::Vec<'a, Label>) -> InstrSeq<'a> {
instr(Instruct::Opcode(Opcode::Switch(
SwitchKind::Unbounded,
0,
targets.into_bump_slice().into(),
)))
}
pub fn await_all_list<'a>(unnamed_locals: Vec<Local>) -> InstrSeq<'a> {
match unnamed_locals.split_first() {
None => panic!("Expected at least one await"),
Some((head, tail)) => {
// Assert that the Locals are sequentially numbered.
let mut prev_id = head;
for id in tail {
assert_eq!(prev_id.idx + 1, id.idx);
prev_id = id;
}
await_all(LocalRange {
start: *head,
len: unnamed_locals.len().try_into().unwrap(),
})
}
}
}
// Special constructors for Pseudo
pub fn break_<'a>() -> InstrSeq<'a> {
instr(Instruct::Pseudo(Pseudo::Break))
}
pub fn continue_<'a>() -> InstrSeq<'a> {
instr(Instruct::Pseudo(Pseudo::Continue))
}
pub fn label<'a>(label: Label) -> InstrSeq<'a> {
instr(Instruct::Pseudo(Pseudo::Label(label)))
}
pub fn srcloc<'a>(
line_begin: isize,
line_end: isize,
col_begin: isize,
col_end: isize,
) -> InstrSeq<'a> {
instr(Instruct::Pseudo(Pseudo::SrcLoc(SrcLoc {
line_begin: line_begin as i32,
line_end: line_end as i32,
col_begin: col_begin as i32,
col_end: col_end as i32,
})))
}
}
impl<'a> InstrSeq<'a> {
/// Produce an empty instruction sequence.
pub fn new_empty() -> Self {
InstrSeq::List(Vec::new())
}
/// Transitional version. We mean to write a `gather!` in the future.
pub fn gather(mut iss: Vec<InstrSeq<'a>>) -> Self {
iss.retain(|iseq| match iseq {
InstrSeq::List(s) if s.is_empty() => false,
_ => true,
});
if iss.is_empty() {
InstrSeq::new_empty()
} else {
InstrSeq::Concat(iss)
}
}
pub fn iter<'i>(&'i self) -> impl Iterator<Item = &'i Instruct<'a>> {
ListIter::new(self).flatten()
}
pub fn iter_mut<'i>(&'i mut self) -> impl Iterator<Item = &'i mut Instruct<'a>> {
ListIterMut::new(self).flatten()
}
fn full_len(&self) -> usize {
ListIter::new(self).map(|s| s.len()).sum()
}
pub fn compact(self, alloc: &'a bumpalo::Bump) -> Slice<'a, Instruct<'a>> {
let mut v = bumpalo::collections::Vec::with_capacity_in(self.full_len(), alloc);
for list in IntoListIter::new(self) {
let len = v.len();
let start = if len > 0 && Self::is_srcloc(&v[len - 1]) {
// v ends with a SrcLoc; back up so we can compact it if eligible.
len - 1
} else {
len
};
v.extend(list);
let mut i = start;
let len = v.len();
for j in start..len {
if Self::is_srcloc(&v[j]) && j + 1 < len && Self::is_srcloc(&v[j + 1]) {
// skip v[j]
} else {
if i < j {
v[i] = v[j].clone();
}
i += 1;
}
}
v.truncate(i);
}
Slice::new(v.into_bump_slice())
}
/// Test whether `i` is of case `Pseudo::SrcLoc`.
fn is_srcloc(instruction: &Instruct<'a>) -> bool {
matches!(instruction, Instruct::Pseudo(Pseudo::SrcLoc(_)))
}
/// Return the first non-SrcLoc instruction.
pub fn first(&self) -> Option<&Instruct<'a>> {
self.iter().find(|&i| !Self::is_srcloc(i))
}
/// Test for the empty instruction sequence, ignoring SrcLocs
pub fn is_empty(&self) -> bool {
self.iter().all(Self::is_srcloc)
}
pub fn retain(&mut self, mut f: impl FnMut(&Instruct<'a>) -> bool) {
for s in ListIterMut::new(self) {
s.retain(&mut f)
}
}
pub fn retain_mut<F>(&mut self, mut f: F)
where
F: FnMut(&mut Instruct<'a>) -> bool,
{
for s in ListIterMut::new(self) {
*s = std::mem::take(s)
.into_iter()
.filter_map(|mut instr| match f(&mut instr) {
true => Some(instr),
false => None,
})
.collect()
}
}
}
#[cfg(test)]
mod tests {
use ffi::Str;
use instr::instr;
use instr::instrs;
use pretty_assertions::assert_eq;
use super::*;
#[test]
fn iter() {
let mk_i = || Instruct::Pseudo(Pseudo::Comment(Str::from("")));
let empty = InstrSeq::new_empty;
let one = || instr(mk_i());
let list0 = || instrs(vec![]);
let list1 = || instrs(vec![mk_i()]);
let list2 = || instrs(vec![mk_i(), mk_i()]);
let concat0 = || InstrSeq::Concat(vec![]);
let concat1 = || InstrSeq::Concat(vec![one()]);
assert_eq!(empty().iter().count(), 0);
assert_eq!(one().iter().count(), 1);
assert_eq!(list0().iter().count(), 0);
assert_eq!(list1().iter().count(), 1);
assert_eq!(list2().iter().count(), 2);
assert_eq!(concat0().iter().count(), 0);
assert_eq!(concat1().iter().count(), 1);
let concat = InstrSeq::Concat(vec![empty()]);
assert_eq!(concat.iter().count(), 0);
let concat = InstrSeq::Concat(vec![empty(), one()]);
assert_eq!(concat.iter().count(), 1);
let concat = InstrSeq::Concat(vec![one(), empty()]);
assert_eq!(concat.iter().count(), 1);
let concat = InstrSeq::Concat(vec![one(), list1()]);
assert_eq!(concat.iter().count(), 2);
let concat = InstrSeq::Concat(vec![list2(), list1()]);
assert_eq!(concat.iter().count(), 3);
let concat = InstrSeq::Concat(vec![concat0(), list2(), list1()]);
assert_eq!(concat.iter().count(), 3);
let concat = InstrSeq::Concat(vec![concat1(), concat1()]);
assert_eq!(concat.iter().count(), 2);
let concat = InstrSeq::Concat(vec![concat0(), concat1()]);
assert_eq!(concat.iter().count(), 1);
let concat = InstrSeq::Concat(vec![list2(), concat1()]);
assert_eq!(concat.iter().count(), 3);
let concat = InstrSeq::Concat(vec![list2(), concat0()]);
assert_eq!(concat.iter().count(), 2);
let concat = InstrSeq::Concat(vec![one(), concat0()]);
assert_eq!(concat.iter().count(), 1);
let concat = InstrSeq::Concat(vec![empty(), concat0()]);
assert_eq!(concat.iter().count(), 0);
}
} |
Rust | hhvm/hphp/hack/src/hackc/emitter/iterator.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 hhbc::IterId;
#[derive(Default, Debug, Clone)]
pub struct IterGen {
pub next: IterId,
count: u32,
}
impl IterGen {
pub fn count(&self) -> usize {
self.count as usize
}
pub fn get(&mut self) -> IterId {
let curr = self.next;
self.next.idx += 1;
self.count = std::cmp::max(self.count, self.next.idx);
curr
}
pub fn free(&mut self) {
self.next.idx -= 1;
}
pub fn reset(&mut self) {
*self = Self::default();
}
} |
Rust | hhvm/hphp/hack/src/hackc/emitter/jump_targets.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 hhbc::IterId;
use hhbc::Label;
#[derive(Clone, Debug, Default, Copy, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct StateId(pub u32);
#[derive(Clone, Debug)]
pub struct LoopLabels {
label_break: Label,
label_continue: Label,
iterator: Option<IterId>,
}
#[derive(Clone, Debug)]
pub enum Region {
Loop(LoopLabels),
Switch(Label),
TryFinally(Label),
Finally,
Function,
Using(Label),
}
#[derive(Debug)]
pub struct ResolvedTryFinally {
pub target_label: Label,
pub finally_label: Label,
pub iterators_to_release: Vec<IterId>,
}
#[derive(Debug)]
pub enum ResolvedJumpTarget {
NotFound,
ResolvedTryFinally(ResolvedTryFinally),
ResolvedRegular(Label, Vec<IterId>),
}
#[derive(Clone, Debug, Default)]
pub struct JumpTargets {
regions: Vec<Region>,
}
impl JumpTargets {
pub fn as_slice(&self) -> &[Region] {
self.regions.as_slice()
}
pub fn get_closest_enclosing_finally_label(&self) -> Option<(Label, Vec<IterId>)> {
let mut iters = vec![];
for r in self.regions.iter().rev() {
match r {
Region::Using(l) | Region::TryFinally(l) => {
return Some((*l, iters));
}
Region::Loop(LoopLabels { iterator, .. }) => {
add_iterator(*iterator, &mut iters);
}
_ => {}
}
}
None
}
/// Return the IterIds of the enclosing iterator loops without allocating/cloning.
pub fn iterators(&self) -> impl Iterator<Item = IterId> + '_ {
self.regions.iter().rev().filter_map(|r| match r {
Region::Loop(LoopLabels { iterator, .. }) => *iterator,
_ => None,
})
}
/// Tries to find a target label for the given jump kind (break or continue)
pub fn get_target(&self, is_break: bool) -> ResolvedJumpTarget {
let mut iters = vec![];
let mut acc = vec![];
let mut label = None;
let mut skip_try_finally = None;
// skip_try_finally is Some if we've already determined that we need to jump out of
// finally and now we are looking for the actual target label (break label of the
// while loop in the example below: )
//
// while (1) {
// try {
// break;
// }
// finally {
// ...
// }
// }
for r in self.regions.iter().rev() {
match *r {
Region::Function | Region::Finally => return ResolvedJumpTarget::NotFound,
Region::Using(finally_label) | Region::TryFinally(finally_label) => {
// we need to jump out of try body in try/finally - in order to do this
// we should go through the finally block first
if skip_try_finally.is_none() {
skip_try_finally = Some((finally_label, iters.clone()));
}
}
Region::Switch(end_label) => {
label = Some(end_label);
iters.append(&mut acc);
break;
}
Region::Loop(LoopLabels {
label_break,
label_continue,
iterator,
}) => {
label = Some(if is_break {
add_iterator(iterator, &mut acc);
label_break
} else {
label_continue
});
iters.append(&mut acc);
break;
}
}
}
match (skip_try_finally, label) {
(Some((finally_label, iterators_to_release)), Some(target_label)) => {
ResolvedJumpTarget::ResolvedTryFinally(ResolvedTryFinally {
target_label,
finally_label,
iterators_to_release,
})
}
(None, Some(l)) => ResolvedJumpTarget::ResolvedRegular(l, iters),
(_, None) => ResolvedJumpTarget::NotFound,
}
}
}
#[derive(Clone, PartialEq, Eq, std::cmp::Ord, std::cmp::PartialOrd, Debug)]
pub enum IdKey {
Return,
Label(Label),
}
#[derive(Clone, Debug, Default)]
pub struct Gen {
label_id_map: std::collections::BTreeMap<IdKey, StateId>,
jump_targets: JumpTargets,
}
impl Gen {
fn new_id(&mut self, key: IdKey) -> StateId {
match self.label_id_map.get(&key) {
Some(id) => *id,
None => {
let mut next_id = StateId(0);
while self.label_id_map.values().any(|&id| id == next_id) {
next_id.0 += 1;
}
self.label_id_map.insert(key, next_id);
next_id
}
}
}
pub fn jump_targets(&self) -> &JumpTargets {
&self.jump_targets
}
pub fn reset(&mut self) {
self.label_id_map.clear();
}
pub fn get_id_for_return(&mut self) -> StateId {
self.new_id(IdKey::Return)
}
pub fn get_id_for_label(&mut self, l: Label) -> StateId {
self.new_id(IdKey::Label(l))
}
pub fn with_loop(
&mut self,
label_break: Label,
label_continue: Label,
iterator: Option<IterId>,
) {
self.jump_targets.regions.push(Region::Loop(LoopLabels {
label_break,
label_continue,
iterator,
}))
}
pub fn with_switch(&mut self, end_label: Label) {
//let labels = self.collect_valid_target_labels_for_switch_cases(cases);
// CONSIDER: now HHVM eagerly reserves state id for the switch end label
// which does not seem to be necessary - do it for now for HHVM compatibility
let _ = self.get_id_for_label(end_label);
self.jump_targets.regions.push(Region::Switch(end_label));
}
pub fn with_try_catch(&mut self, finally_label: Label) {
self.jump_targets
.regions
.push(Region::TryFinally(finally_label));
}
pub fn with_try(&mut self, finally_label: Label) {
self.jump_targets
.regions
.push(Region::TryFinally(finally_label));
}
pub fn with_finally(&mut self) {
self.jump_targets.regions.push(Region::Finally);
}
pub fn with_function(&mut self) {
self.jump_targets.regions.push(Region::Function);
}
pub fn with_using(&mut self, finally_label: Label) {
self.jump_targets.regions.push(Region::Using(finally_label));
}
pub fn revert(&mut self) {
self.jump_targets.regions.pop();
}
pub fn release_ids(&mut self) {
match self
.jump_targets
.regions
.last_mut()
.expect("empty region after executing run_and_release")
{
Region::Loop(LoopLabels {
label_break,
label_continue,
..
}) => {
self.label_id_map.remove(&IdKey::Label(*label_break));
self.label_id_map.remove(&IdKey::Label(*label_continue));
}
Region::Switch(l) | Region::TryFinally(l) | Region::Using(l) => {
self.label_id_map.remove(&IdKey::Label(*l));
}
Region::Finally | Region::Function => {}
};
// CONSIDER: now HHVM does not release state ids for named labels
// even after leaving the scope where labels are accessible
// Do the same for now for compatibility reasons
// labels
// .iter()
// .for_each(|l| self.label_id_map.remove(&IdKey::Label(Label::Named(l.to_string()))));
}
}
fn add_iterator(it_opt: Option<IterId>, iters: &mut Vec<IterId>) {
if let Some(it) = it_opt {
iters.push(it);
}
} |
Rust | hhvm/hphp/hack/src/hackc/emitter/label.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 hhbc::Label;
#[derive(Debug)]
pub struct LabelGen {
next: Label,
}
impl LabelGen {
pub fn new() -> Self {
Self { next: Label::ZERO }
}
pub fn next_regular(&mut self) -> Label {
let curr = self.next;
self.next.0 += 1;
curr
}
pub fn reset(&mut self) {
*self = Self::new();
}
} |
Rust | hhvm/hphp/hack/src/hackc/emitter/label_rewriter.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::LabelGen;
use hash::HashMap;
use hash::HashSet;
use hhbc::Instruct;
use hhbc::Label;
use hhbc::Opcode;
use hhbc::Param;
use hhbc::Pseudo;
use instruction_sequence::InstrSeq;
use oxidized::ast;
/// Create a mapping Label instructions to their position in the InstrSeq without
/// the labels. In other words, all instructions get numbered except labels.
fn create_label_to_offset_map<'arena>(instrseq: &InstrSeq<'arena>) -> HashMap<Label, u32> {
let mut index = 0;
instrseq
.iter()
.filter_map(|instr| match instr {
Instruct::Pseudo(Pseudo::Label(label)) => Some((*label, index)),
_ => {
index += 1;
None
}
})
.collect()
}
fn create_label_ref_map<'arena>(
label_to_offset: &HashMap<Label, u32>,
params: &[(Param<'arena>, Option<(Label, ast::Expr)>)],
body: &InstrSeq<'arena>,
) -> (HashSet<Label>, HashMap<u32, Label>) {
let mut label_gen = LabelGen::new();
let mut used = HashSet::default();
let mut offset_to_label = HashMap::default();
let mut process_ref = |target: &Label| {
let offset = label_to_offset[target];
offset_to_label.entry(offset).or_insert_with(|| {
used.insert(*target);
label_gen.next_regular()
});
};
// Process the function body.
for instr in body.iter() {
for target in instr.targets().iter() {
process_ref(target);
}
}
// Process params
for (_param, dv) in params {
if let Some((target, _)) = dv {
process_ref(target);
}
}
(used, offset_to_label)
}
fn rewrite_params_and_body<'arena>(
alloc: &'arena bumpalo::Bump,
label_to_offset: &HashMap<Label, u32>,
used: &HashSet<Label>,
offset_to_label: &HashMap<u32, Label>,
params: &mut [(Param<'arena>, Option<(Label, ast::Expr)>)],
body: &mut InstrSeq<'arena>,
) {
let relabel = |id: Label| {
if id == Label::INVALID {
Label::INVALID
} else {
offset_to_label[&label_to_offset[&id]]
}
};
for (_, dv) in params.iter_mut() {
if let Some((l, _)) = dv {
*l = relabel(*l);
}
}
body.retain_mut(|instr| {
if let Instruct::Pseudo(Pseudo::Label(l)) = instr {
if used.contains(l) {
*l = relabel(*l);
true
} else {
false
}
} else {
rewrite_labels(alloc, instr, relabel);
true
}
});
}
pub fn relabel_function<'arena>(
alloc: &'arena bumpalo::Bump,
params: &mut [(Param<'arena>, Option<(Label, ast::Expr)>)],
body: &mut InstrSeq<'arena>,
) {
let label_to_offset = create_label_to_offset_map(body);
let (used, offset_to_label) = create_label_ref_map(&label_to_offset, params, body);
rewrite_params_and_body(
alloc,
&label_to_offset,
&used,
&offset_to_label,
params,
body,
)
}
pub fn rewrite_with_fresh_regular_labels<'arena, 'decl>(
emitter: &mut Emitter<'arena, 'decl>,
block: &mut InstrSeq<'arena>,
) {
let mut old_to_new = HashMap::default();
for instr in block.iter() {
if let Instruct::Pseudo(Pseudo::Label(label)) = instr {
old_to_new.insert(*label, emitter.label_gen_mut().next_regular());
}
}
if !old_to_new.is_empty() {
let relabel = |target: Label| old_to_new.get(&target).copied().unwrap_or(target);
for instr in block.iter_mut() {
rewrite_labels(emitter.alloc, instr, relabel);
}
}
}
/// Apply the given function to every Label in the Instruct.
///
/// If this turns out to be needed elsewhere it should probably be moved into the
/// Targets trait.
fn rewrite_labels<'a, F>(alloc: &'a bumpalo::Bump, instr: &mut Instruct<'a>, f: F)
where
F: Fn(Label) -> Label,
{
match instr {
Instruct::Pseudo(Pseudo::Label(label))
| Instruct::Opcode(
Opcode::Enter(label)
| Opcode::IterInit(_, label)
| Opcode::IterNext(_, label)
| Opcode::Jmp(label)
| Opcode::JmpNZ(label)
| Opcode::JmpZ(label)
| Opcode::LIterInit(_, _, label)
| Opcode::LIterNext(_, _, label)
| Opcode::MemoGet(label, _),
) => {
*label = f(*label);
}
Instruct::Opcode(
Opcode::FCallClsMethod(fca, _, _)
| Opcode::FCallClsMethodD(fca, _, _)
| Opcode::FCallClsMethodM(fca, _, _, _)
| Opcode::FCallClsMethodS(fca, _, _)
| Opcode::FCallClsMethodSD(fca, _, _, _)
| Opcode::FCallCtor(fca, _)
| Opcode::FCallFunc(fca)
| Opcode::FCallFuncD(fca, _)
| Opcode::FCallObjMethod(fca, _, _)
| Opcode::FCallObjMethodD(fca, _, _, _),
) => {
fca.async_eager_target = f(fca.async_eager_target);
}
Instruct::Opcode(Opcode::MemoGetEager([label1, label2], _, _)) => {
*label1 = f(*label1);
*label2 = f(*label2);
}
Instruct::Opcode(Opcode::Switch(_, _, labels)) => {
*labels = ffi::Slice::fill_iter(alloc, labels.into_iter().copied().map(f));
}
Instruct::Opcode(Opcode::SSwitch { targets, .. }) => {
*targets = ffi::Slice::fill_iter(alloc, targets.into_iter().copied().map(f));
}
Instruct::Pseudo(
Pseudo::Break
| Pseudo::Comment(..)
| Pseudo::Continue
| Pseudo::SrcLoc(..)
| Pseudo::TryCatchBegin
| Pseudo::TryCatchEnd
| Pseudo::TryCatchMiddle
| Pseudo::TypedValue(..),
)
| Instruct::Opcode(
Opcode::AKExists
| Opcode::AddElemC
| Opcode::AddNewElemC
| Opcode::Add
| Opcode::ArrayIdx
| Opcode::ArrayMarkLegacy
| Opcode::ArrayUnmarkLegacy
| Opcode::AssertRATL(..)
| Opcode::AssertRATStk(..)
| Opcode::AwaitAll(..)
| Opcode::Await
| Opcode::BareThis(..)
| Opcode::BaseC(..)
| Opcode::BaseGC(..)
| Opcode::BaseGL(..)
| Opcode::BaseH
| Opcode::BaseL(..)
| Opcode::BaseSC(..)
| Opcode::BitAnd
| Opcode::BitNot
| Opcode::BitOr
| Opcode::BitXor
| Opcode::BreakTraceHint
| Opcode::CGetCUNop
| Opcode::CGetG
| Opcode::CGetL(..)
| Opcode::CGetL2(..)
| Opcode::CGetQuietL(..)
| Opcode::CGetS(..)
| Opcode::CUGetL(..)
| Opcode::CastBool
| Opcode::CastDict
| Opcode::CastDouble
| Opcode::CastInt
| Opcode::CastKeyset
| Opcode::CastString
| Opcode::CastVec
| Opcode::ChainFaults
| Opcode::CheckClsReifiedGenericMismatch
| Opcode::CheckClsRGSoft
| Opcode::CheckProp(..)
| Opcode::CheckThis
| Opcode::ClassGetC
| Opcode::ClassGetTS
| Opcode::ClassHasReifiedGenerics
| Opcode::ClassName
| Opcode::Clone
| Opcode::ClsCns(..)
| Opcode::ClsCnsD(..)
| Opcode::ClsCnsL(..)
| Opcode::Cmp
| Opcode::CnsE(..)
| Opcode::ColFromArray(..)
| Opcode::CombineAndResolveTypeStruct(..)
| Opcode::ConcatN(..)
| Opcode::Concat
| Opcode::ContCheck(..)
| Opcode::ContCurrent
| Opcode::ContEnter
| Opcode::ContGetReturn
| Opcode::ContKey
| Opcode::ContRaise
| Opcode::ContValid
| Opcode::CreateCl(..)
| Opcode::CreateCont
| Opcode::CreateSpecialImplicitContext
| Opcode::DblAsBits
| Opcode::Dict(..)
| Opcode::Dim(..)
| Opcode::Dir
| Opcode::Div
| Opcode::Double(..)
| Opcode::Dup
| Opcode::Eq
| Opcode::Eval
| Opcode::Exit
| Opcode::False
| Opcode::Fatal(..)
| Opcode::File
| Opcode::FuncCred
| Opcode::GetClsRGProp
| Opcode::GetMemoKeyL(..)
| Opcode::Gte
| Opcode::Gt
| Opcode::HasReifiedParent
| Opcode::Idx
| Opcode::IncDecG(..)
| Opcode::IncDecL(..)
| Opcode::IncDecM(..)
| Opcode::IncDecS(..)
| Opcode::InclOnce
| Opcode::Incl
| Opcode::InitProp(..)
| Opcode::InstanceOfD(..)
| Opcode::InstanceOf
| Opcode::Int(..)
| Opcode::IsLateBoundCls
| Opcode::IsTypeC(..)
| Opcode::IsTypeL(..)
| Opcode::IsTypeStructC(..)
| Opcode::IsUnsetL(..)
| Opcode::IssetG
| Opcode::IssetL(..)
| Opcode::IssetS
| Opcode::IterFree(..)
| Opcode::Keyset(..)
| Opcode::LIterFree(..)
| Opcode::LateBoundCls
| Opcode::LazyClass(..)
| Opcode::LazyClassFromClass
| Opcode::LockObj
| Opcode::Lte
| Opcode::Lt
| Opcode::MemoSet(..)
| Opcode::MemoSetEager(..)
| Opcode::Method
| Opcode::Mod
| Opcode::Mul
| Opcode::NSame
| Opcode::NativeImpl
| Opcode::Neq
| Opcode::NewCol(..)
| Opcode::NewDictArray(..)
| Opcode::NewKeysetArray(..)
| Opcode::NewObjD(..)
| Opcode::NewObjS(..)
| Opcode::NewObj
| Opcode::NewPair
| Opcode::NewStructDict(..)
| Opcode::NewVec(..)
| Opcode::Nop
| Opcode::Not
| Opcode::NullUninit
| Opcode::Null
| Opcode::OODeclExists(..)
| Opcode::ParentCls
| Opcode::PopC
| Opcode::PopL(..)
| Opcode::PopU2
| Opcode::PopU
| Opcode::Pow
| Opcode::Print
| Opcode::PushL(..)
| Opcode::QueryM(..)
| Opcode::RaiseClassStringConversionWarning
| Opcode::RecordReifiedGeneric
| Opcode::ReqDoc
| Opcode::ReqOnce
| Opcode::Req
| Opcode::ResolveClass(..)
| Opcode::ResolveClsMethod(..)
| Opcode::ResolveClsMethodD(..)
| Opcode::ResolveClsMethodS(..)
| Opcode::ResolveFunc(..)
| Opcode::ResolveMethCaller(..)
| Opcode::ResolveRClsMethod(..)
| Opcode::ResolveRClsMethodD(..)
| Opcode::ResolveRClsMethodS(..)
| Opcode::ResolveRFunc(..)
| Opcode::RetCSuspended
| Opcode::RetC
| Opcode::RetM(..)
| Opcode::Same
| Opcode::Select
| Opcode::SelfCls
| Opcode::SetG
| Opcode::SetImplicitContextByValue
| Opcode::SetL(..)
| Opcode::SetM(..)
| Opcode::SetOpG(..)
| Opcode::SetOpL(..)
| Opcode::SetOpM(..)
| Opcode::SetOpS(..)
| Opcode::SetRangeM(..)
| Opcode::SetS(..)
| Opcode::Shl
| Opcode::Shr
| Opcode::Silence(..)
| Opcode::String(..)
| Opcode::Sub
| Opcode::This
| Opcode::ThrowAsTypeStructException
| Opcode::ThrowNonExhaustiveSwitch
| Opcode::Throw
| Opcode::True
| Opcode::UGetCUNop
| Opcode::UnsetG
| Opcode::UnsetL(..)
| Opcode::UnsetM(..)
| Opcode::Vec(..)
| Opcode::VerifyImplicitContextState
| Opcode::VerifyOutType(..)
| Opcode::VerifyParamType(..)
| Opcode::VerifyParamTypeTS(..)
| Opcode::VerifyRetNonNullC
| Opcode::VerifyRetTypeC
| Opcode::VerifyRetTypeTS
| Opcode::WHResult
| Opcode::YieldK
| Opcode::Yield,
) => {
debug_assert!(
instr.targets().is_empty(),
"bad instr {instr:?} shouldn't have targets"
);
}
}
} |
Rust | hhvm/hphp/hack/src/hackc/emitter/local.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 hhbc::Local;
#[derive(Debug)]
pub struct LocalGen {
pub counter: Counter,
pub dedicated: Dedicated,
}
impl LocalGen {
pub fn new() -> Self {
Self {
counter: Counter::new(),
dedicated: Dedicated::default(),
}
}
pub fn get_unnamed(&mut self) -> Local {
self.counter.next_unnamed(&self.dedicated)
}
pub fn get_unnamed_for_tempname(&self, s: &str) -> &Local {
naming_special_names_rust::special_idents::assert_tmp_var(s);
self.dedicated
.temp_map
.get(s)
.expect("Unnamed local never init'ed")
}
pub fn init_unnamed_for_tempname(&mut self, s: &str) -> &Local {
use indexmap::map::Entry::*;
naming_special_names_rust::special_idents::assert_tmp_var(s);
let new_local = self.get_unnamed();
match self.dedicated.temp_map.map.entry(s.to_owned()) {
Occupied(_) => panic!("Attempted to double init: {}", s),
Vacant(e) => e.insert(new_local),
}
}
pub fn get_label(&mut self) -> &Local {
let mut counter = self.counter;
let mut new_counter = self.counter;
let new_local = new_counter.next_unnamed(&self.dedicated);
let ret = self.dedicated.label.get_or_insert_with(|| {
counter = new_counter;
new_local
});
self.counter = counter;
ret
}
pub fn get_retval(&mut self) -> &Local {
// This and above body cannot be factored out because of nasty
// aliasing of `&self.dedicated` and `&mut
// self.dedicated.field`.
let mut counter = self.counter;
let mut new_counter = self.counter;
let new_local = new_counter.next_unnamed(&self.dedicated);
let ret = self.dedicated.retval.get_or_insert_with(|| {
counter = new_counter;
new_local
});
self.counter = counter;
ret
}
pub fn reserve_retval_and_label_id_locals(&mut self) {
// Values are ignored because we care only about reserving
// them in the dedicated table.
self.get_label();
self.get_retval();
}
pub fn reset(&mut self, next: Local) {
*self = Self {
counter: Counter { next },
dedicated: Dedicated::default(),
}
}
}
#[derive(Debug, Default)]
pub struct TempMap {
stack: Vec<usize>,
map: indexmap::IndexMap<String, Local>,
}
impl TempMap {
pub fn get(&self, temp: impl AsRef<str>) -> Option<&Local> {
self.map.get(temp.as_ref())
}
pub fn insert(&mut self, temp: impl Into<String>, local: Local) -> Option<Local> {
self.map.insert(temp.into(), local)
}
pub fn push(&mut self) {
self.stack.push(self.map.len())
}
pub fn pop(&mut self) {
if let Some(j) = self.stack.pop() {
while self.map.len() > j {
self.map.pop();
}
}
}
}
// implementation details
#[derive(Default, Debug)]
pub struct Dedicated {
label: Option<Local>,
retval: Option<Local>,
pub temp_map: TempMap,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Counter {
pub next: Local,
}
impl Counter {
fn new() -> Self {
Self { next: Local::ZERO }
}
fn next_unnamed(&mut self, dedicated: &Dedicated) -> Local {
loop {
let curr = self.next;
self.next.idx += 1;
// make sure that newly allocated local don't stomp on dedicated locals
match dedicated.label {
Some(id) if curr == id => continue,
_ => match dedicated.retval {
Some(id) if curr == id => continue,
_ => return curr,
},
}
}
}
} |
Rust | hhvm/hphp/hack/src/hackc/emitter/reified_generics_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 decl_provider::TypeDecl;
use env::emitter::Emitter;
use env::Env;
use error::Result;
use hash::HashSet;
use instruction_sequence::instr;
use instruction_sequence::InstrSeq;
use naming_special_names_rust as sn;
use oxidized::aast;
use oxidized::ast_defs::Id;
use oxidized::pos::Pos;
use crate::emit_expression::emit_reified_arg;
use crate::emit_expression::is_reified_tparam;
#[derive(Debug, Clone)]
pub enum ReificationLevel {
/// There is a reified generic
Definitely,
/// There is no function or class reified generics, but there may be an inferred one
Maybe,
Not,
Unconstrained,
}
impl ReificationLevel {
fn combine(v1: &Self, v2: &Self) -> Self {
match (v1, v2) {
(Self::Definitely, _) | (_, Self::Definitely) => Self::Definitely,
(Self::Maybe, _) | (_, Self::Maybe) => Self::Maybe,
_ => Self::Not,
}
}
}
pub(crate) fn get_erased_tparams<'a, 'arena>(
env: &'a Env<'a, 'arena>,
) -> impl Iterator<Item = String> + 'a {
env.scope.get_tparams().into_iter().filter_map(|tp| {
if tp.reified != aast::ReifyKind::Reified {
Some(tp.name.1.clone()) // TODO(hrust) figure out how to return &str
} else {
None
}
})
}
pub(crate) fn has_reified_type_constraint<'a, 'arena>(
env: &Env<'a, 'arena>,
h: &aast::Hint,
) -> ReificationLevel {
use aast::Hint_;
fn is_all_erased<'a>(
env: &'a Env<'_, '_>,
mut h_iter: impl Iterator<Item = &'a aast::Hint>,
) -> bool {
let erased_tparams: HashSet<String> = get_erased_tparams(env).collect();
h_iter.all(|h| match &*h.1 {
Hint_::Hwildcard => true,
Hint_::Happly(Id(_, ref id), ref apply_hints) => {
apply_hints.is_empty() && erased_tparams.contains(id)
}
_ => false,
})
}
match &*h.1 {
Hint_::Happly(Id(_, id), hs) => {
if is_reified_tparam(env, true, id).is_some()
|| is_reified_tparam(env, false, id).is_some()
{
ReificationLevel::Definitely
} else if hs.is_empty() || is_all_erased(env, hs.iter()) {
ReificationLevel::Not
} else {
hs.iter().rev().fold(ReificationLevel::Maybe, |v, h| {
ReificationLevel::combine(&v, &has_reified_type_constraint(env, h))
})
}
}
Hint_::Hsoft(h) | Hint_::Hlike(h) | Hint_::Hoption(h) => {
has_reified_type_constraint(env, h)
}
Hint_::Hprim(_)
| Hint_::Hmixed
| Hint_::Hwildcard
| Hint_::Hnonnull
| Hint_::HvecOrDict(_, _)
| Hint_::Hthis
| Hint_::Hnothing
| Hint_::Hdynamic
| Hint_::Htuple(_)
| Hint_::Hunion(_)
| Hint_::Hintersection(_)
| Hint_::Hshape(_)
| Hint_::Hfun(_)
| Hint_::Haccess(_, _)
| Hint_::Hrefinement(_, _)
| Hint_::HfunContext(_)
| Hint_::Hvar(_) => ReificationLevel::Not,
// Not found in the original AST
Hint_::Herr | Hint_::Hany => panic!("Should be a naming error"),
Hint_::Habstr(_, _) => panic!("TODO Unimplemented: Not in the original AST"),
}
}
fn remove_awaitable(aast::Hint(pos, hint): aast::Hint) -> aast::Hint {
use aast::Hint;
use aast::Hint_;
match *hint {
Hint_::Happly(sid, mut hs)
if hs.len() == 1 && sid.1.eq_ignore_ascii_case(sn::classes::AWAITABLE) =>
{
hs.pop().unwrap()
}
// For @Awaitable<T>, the soft type hint is moved to the inner type, i.e @T
Hint_::Hsoft(h) => Hint(pos, Box::new(Hint_::Hsoft(remove_awaitable(h)))),
// For ~Awaitable<T>, the like-type hint is moved to the inner type, i.e ~T
Hint_::Hlike(h) => Hint(pos, Box::new(Hint_::Hlike(remove_awaitable(h)))),
// For ?Awaitable<T>, the optional is dropped
Hint_::Hoption(h) => remove_awaitable(h),
Hint_::Htuple(_)
| Hint_::Hunion(_)
| Hint_::Hintersection(_)
| Hint_::Hshape(_)
| Hint_::Hfun(_)
| Hint_::Haccess(_, _)
| Hint_::Hrefinement(_, _)
| Hint_::Happly(_, _)
| Hint_::HfunContext(_)
| Hint_::Hvar(_)
| Hint_::Hwildcard => Hint(pos, hint),
Hint_::Herr
| Hint_::Hany
| Hint_::Hmixed
| Hint_::Hnonnull
| Hint_::Habstr(_, _)
| Hint_::HvecOrDict(_, _)
| Hint_::Hprim(_)
| Hint_::Hthis
| Hint_::Hnothing
| Hint_::Hdynamic => panic!("TODO Unimplemented Did not exist on legacy AST"),
}
}
pub(crate) fn convert_awaitable<'a, 'arena>(env: &Env<'a, 'arena>, h: aast::Hint) -> aast::Hint {
if env.scope.is_in_async() {
remove_awaitable(h)
} else {
h
}
}
pub(crate) fn simplify_verify_type<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
pos: &Pos,
check: InstrSeq<'arena>,
hint: &aast::Hint,
verify_instr: InstrSeq<'arena>,
) -> Result<InstrSeq<'arena>> {
let get_ts = |e, hint| Ok(emit_reified_arg(e, env, pos, false, hint)?.0);
let aast::Hint(_, hint_) = hint;
if let aast::Hint_::Hoption(ref hint) = **hint_ {
let label_gen = e.label_gen_mut();
let done_label = label_gen.next_regular();
Ok(InstrSeq::gather(vec![
check,
instr::jmp_nz(done_label),
get_ts(e, hint)?,
verify_instr,
instr::label(done_label),
]))
} else {
Ok(InstrSeq::gather(vec![get_ts(e, hint)?, verify_instr]))
}
}
pub(crate) fn remove_erased_generics<'a, 'arena>(
env: &Env<'a, 'arena>,
h: aast::Hint,
) -> aast::Hint {
use aast::Hint;
use aast::Hint_;
use aast::NastShapeInfo;
use aast::ShapeFieldInfo;
fn rec<'a, 'arena>(env: &Env<'a, 'arena>, Hint(pos, h_): Hint) -> Hint {
let h_ = match *h_ {
Hint_::Happly(Id(pos, id), hs) => {
if get_erased_tparams(env).any(|p| p == id) {
Hint_::Hwildcard
} else {
Hint_::Happly(Id(pos, id), hs.into_iter().map(|h| rec(env, h)).collect())
}
}
Hint_::Hsoft(h) => Hint_::Hsoft(rec(env, h)),
Hint_::Hlike(h) => Hint_::Hlike(rec(env, h)),
Hint_::Hoption(h) => Hint_::Hoption(rec(env, h)),
Hint_::Htuple(hs) => Hint_::Htuple(hs.into_iter().map(|h| rec(env, h)).collect()),
Hint_::Hunion(hs) => Hint_::Hunion(hs.into_iter().map(|h| rec(env, h)).collect()),
Hint_::Hintersection(hs) => {
Hint_::Hintersection(hs.into_iter().map(|h| rec(env, h)).collect())
}
Hint_::Hshape(NastShapeInfo {
allows_unknown_fields,
field_map,
}) => {
let field_map = field_map
.into_iter()
.map(|sfi: ShapeFieldInfo| ShapeFieldInfo {
hint: rec(env, sfi.hint),
..sfi
})
.collect();
Hint_::Hshape(NastShapeInfo {
allows_unknown_fields,
field_map,
})
}
h_ @ Hint_::Hfun(_)
| h_ @ Hint_::Haccess(_, _)
| h_ @ Hint_::Hrefinement(_, _)
| h_ @ Hint_::Hwildcard => h_,
Hint_::Herr
| Hint_::Hany
| Hint_::Hmixed
| Hint_::Hnonnull
| Hint_::Habstr(_, _)
| Hint_::HvecOrDict(_, _)
| Hint_::Hprim(_)
| Hint_::Hthis
| Hint_::Hnothing
| Hint_::Hdynamic => panic!("TODO Unimplemented Did not exist on legacy AST"),
Hint_::HfunContext(_) | Hint_::Hvar(_) => {
panic!("Coeffects are currently erased during compilation")
}
};
Hint(pos, Box::new(h_))
}
rec(env, h)
}
/// Warning: Experimental usage of decl-directed bytecode compilation.
/// Given a hint, if the hint is an Happly(id, _), checks if the id is a class
/// that has reified generics.
pub(crate) fn happly_decl_has_reified_generics<'a, 'arena, 'decl>(
env: &Env<'a, 'arena>,
emitter: &mut Emitter<'arena, 'decl>,
aast::Hint(_, hint): &aast::Hint,
) -> bool {
use aast::Hint_;
use aast::ReifyKind;
match hint.as_ref() {
Hint_::Happly(Id(_, id), _) => {
// If the parameter itself is a reified type parameter, then we want to do the
// tparam check
if is_reified_tparam(env, true, id).is_some()
|| is_reified_tparam(env, false, id).is_some()
{
return true;
}
// If the parameter is an erased type parameter, then no check is necessary
if get_erased_tparams(env).any(|tparam| &tparam == id) {
return false;
}
// Otherwise, we have a class or typedef name that we want to look up
let provider = match emitter.decl_provider.as_ref() {
Some(p) if emitter.options().hhbc.optimize_reified_param_checks => p,
Some(_) | None => {
// If we don't have a `DeclProvider` available, or this specific optimization
// has been turned off, assume that this may be a refied generic class.
return true;
}
};
match provider.type_decl(id, 0) {
Ok(TypeDecl::Class(class_decl)) => {
// Found a class with a matching name. Does it's shallow decl have
// any reified tparams?
class_decl
.tparams
.iter()
.any(|tparam| tparam.reified != ReifyKind::Erased)
}
Ok(TypeDecl::Typedef(_)) => {
// TODO: `id` could be an alias for something without reified generics,
// but conservatively assume it has at least one, for now.
true
}
Err(decl_provider::Error::NotFound) => {
// The DeclProvider has no idea what `id` is.
true
}
Err(decl_provider::Error::Bincode(_)) => {
// Infra error while handling serialized decls
true
}
}
}
Hint_::Hoption(_)
| Hint_::Hlike(_)
| Hint_::Hfun(_)
| Hint_::Htuple(_)
| Hint_::Hshape(_)
| Hint_::Haccess(_, _)
| Hint_::Hsoft(_) => {
// Assume any of these types could have reified generics.
true
}
x => {
// Other AST nodes are impossible here, must be a bug.
unreachable!("unexpected AST node: {:#?}", x)
}
}
} |
Rust | hhvm/hphp/hack/src/hackc/emitter/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.
use env::emitter::Emitter;
use env::LabelGen;
use error::Result;
use hhbc::Instruct;
use hhbc::IterId;
use hhbc::Label;
use hhbc::Local;
use hhbc::Opcode;
use hhbc::Pseudo;
use instruction_sequence::instr;
use instruction_sequence::InstrSeq;
/// Run emit () in a new unnamed local scope, which produces three instruction
/// blocks -- before, inner, after. If emit () registered any unnamed locals, the
/// inner block will be wrapped in a try/catch that will unset these unnamed
/// locals upon exception.
pub fn with_unnamed_locals<'arena, 'decl, F>(
e: &mut Emitter<'arena, 'decl>,
emit: F,
) -> Result<InstrSeq<'arena>>
where
F: FnOnce(
&mut Emitter<'arena, 'decl>,
) -> Result<(InstrSeq<'arena>, InstrSeq<'arena>, InstrSeq<'arena>)>,
{
let local_counter = e.local_gen().counter;
e.local_gen_mut().dedicated.temp_map.push();
let (before, inner, after) = emit(e)?;
e.local_gen_mut().dedicated.temp_map.pop();
if local_counter == e.local_gen().counter {
Ok(InstrSeq::gather(vec![before, inner, after]))
} else {
let unset_locals = unset_unnamed_locals(local_counter.next, e.local_gen().counter.next);
e.local_gen_mut().counter = local_counter;
Ok(wrap_inner_in_try_catch(
e.label_gen_mut(),
(before, inner, after),
unset_locals,
))
}
}
/// Run emit () in a new unnamed local and iterator scope, which produces three
/// instruction blocks -- before, inner, after. If emit () registered any unnamed
/// locals or iterators, the inner block will be wrapped in a try/catch that will
/// unset these unnamed locals and free these iterators upon exception.
pub fn with_unnamed_locals_and_iterators<'arena, 'decl, F>(
e: &mut Emitter<'arena, 'decl>,
emit: F,
) -> Result<InstrSeq<'arena>>
where
F: FnOnce(
&mut Emitter<'arena, 'decl>,
) -> Result<(InstrSeq<'arena>, InstrSeq<'arena>, InstrSeq<'arena>)>,
{
let local_counter = e.local_gen().counter;
e.local_gen_mut().dedicated.temp_map.push();
let next_iterator = e.iterator().next;
let (before, inner, after) = emit(e)?;
e.local_gen_mut().dedicated.temp_map.pop();
if local_counter == e.local_gen().counter && next_iterator == e.iterator().next {
Ok(InstrSeq::gather(vec![before, inner, after]))
} else {
let unset_locals = unset_unnamed_locals(local_counter.next, e.local_gen().counter.next);
e.local_gen_mut().counter = local_counter;
let free_iters = free_iterators(next_iterator, e.iterator().next);
e.iterator_mut().next = next_iterator;
Ok(wrap_inner_in_try_catch(
e.label_gen_mut(),
(before, inner, after),
InstrSeq::gather(vec![unset_locals, free_iters]),
))
}
}
/// An equivalent of with_unnamed_locals that allocates a single local and
/// passes it to emit
pub fn with_unnamed_local<'arena, 'decl, F>(
e: &mut Emitter<'arena, 'decl>,
emit: F,
) -> Result<InstrSeq<'arena>>
where
F: FnOnce(
&mut Emitter<'arena, 'decl>,
Local,
) -> Result<(InstrSeq<'arena>, InstrSeq<'arena>, InstrSeq<'arena>)>,
{
with_unnamed_locals(e, |e| {
let tmp = e.local_gen_mut().get_unnamed();
emit(e, tmp)
})
}
pub fn stash_top_in_unnamed_local<'arena, 'decl, F>(
e: &mut Emitter<'arena, 'decl>,
emit: F,
) -> Result<InstrSeq<'arena>>
where
F: FnOnce(&mut Emitter<'arena, 'decl>) -> Result<InstrSeq<'arena>>,
{
with_unnamed_locals(e, |e| {
let tmp = e.local_gen_mut().get_unnamed();
Ok((instr::pop_l(tmp.clone()), emit(e)?, instr::push_l(tmp)))
})
}
fn unset_unnamed_locals<'arena>(start: Local, end: Local) -> InstrSeq<'arena> {
InstrSeq::gather(
(start.idx..end.idx)
.map(|idx| instr::unset_l(Local::new(idx as usize)))
.collect(),
)
}
fn free_iterators<'arena>(start: IterId, end: IterId) -> InstrSeq<'arena> {
InstrSeq::gather(
(start.idx..end.idx)
.map(|idx| instr::iter_free(IterId { idx }))
.collect(),
)
}
fn wrap_inner_in_try_catch<'arena>(
label_gen: &mut LabelGen,
(before, inner, after): (InstrSeq<'arena>, InstrSeq<'arena>, InstrSeq<'arena>),
catch_instrs: InstrSeq<'arena>,
) -> InstrSeq<'arena> {
InstrSeq::gather(vec![
before,
create_try_catch(label_gen, None, false, inner, catch_instrs),
after,
])
}
pub fn create_try_catch<'a>(
label_gen: &mut LabelGen,
opt_done_label: Option<Label>,
skip_throw: bool,
try_instrs: InstrSeq<'a>,
catch_instrs: InstrSeq<'a>,
) -> InstrSeq<'a> {
let done_label = match opt_done_label {
Some(l) => l,
None => label_gen.next_regular(),
};
InstrSeq::gather(vec![
instr::instr(Instruct::Pseudo(Pseudo::TryCatchBegin)),
try_instrs,
instr::jmp(done_label),
instr::instr(Instruct::Pseudo(Pseudo::TryCatchMiddle)),
catch_instrs,
if skip_throw {
instr::empty()
} else {
instr::instr(Instruct::Opcode(Opcode::Throw))
},
instr::instr(Instruct::Pseudo(Pseudo::TryCatchEnd)),
instr::label(done_label),
])
} |
Rust | hhvm/hphp/hack/src/hackc/emitter/statement_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 instruction_sequence::instr;
use instruction_sequence::InstrSeq;
use oxidized::aast;
use oxidized::pos::Pos;
#[derive(Debug)]
pub struct StatementState<'arena> {
pub verify_return: Option<aast::Hint>,
pub default_return_value: InstrSeq<'arena>,
pub default_dropthrough: Option<InstrSeq<'arena>>,
pub verify_out: InstrSeq<'arena>,
pub function_pos: Pos,
pub num_out: usize,
}
impl<'arena> StatementState<'arena> {
pub fn init() -> Self {
StatementState {
verify_return: None,
default_return_value: instr::null(),
default_dropthrough: None,
verify_out: instr::empty(),
num_out: 0,
function_pos: Pos::NONE,
}
}
} |
Rust | hhvm/hphp/hack/src/hackc/emitter/try_finally_rewriter.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 bitflags::bitflags;
use emit_pos::emit_pos;
use env::emitter::Emitter;
use env::jump_targets as jt;
use env::Env;
use env::LocalGen;
use error::Result;
use hhbc::Instruct;
use hhbc::IsTypeOp;
use hhbc::IterId;
use hhbc::Label;
use hhbc::Opcode;
use hhbc::Pseudo;
use indexmap::IndexSet;
use instruction_sequence::instr;
use instruction_sequence::InstrSeq;
use oxidized::pos::Pos;
use super::TypeRefinementInHint;
use crate::emit_expression;
use crate::emit_fatal;
use crate::reified_generics_helpers as reified;
type LabelMap<'a, 'arena> = BTreeMap<jt::StateId, &'a Instruct<'arena>>;
pub(super) struct JumpInstructions<'a, 'arena>(LabelMap<'a, 'arena>);
impl<'a, 'arena> JumpInstructions<'a, 'arena> {
pub(super) fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Collects list of Ret* and non rewritten Break/Continue instructions inside try body.
pub(super) fn collect(
instr_seq: &'a InstrSeq<'arena>,
jt_gen: &mut jt::Gen,
) -> JumpInstructions<'a, 'arena> {
fn get_label_id(jt_gen: &mut jt::Gen, is_break: bool) -> jt::StateId {
use jt::ResolvedJumpTarget;
match jt_gen.jump_targets().get_target(is_break) {
ResolvedJumpTarget::ResolvedRegular(target_label, _)
| ResolvedJumpTarget::ResolvedTryFinally(jt::ResolvedTryFinally {
target_label,
..
}) => jt_gen.get_id_for_label(target_label),
ResolvedJumpTarget::NotFound => unreachable!(),
}
}
JumpInstructions(instr_seq.iter().fold(LabelMap::new(), |mut acc, instr| {
match *instr {
Instruct::Pseudo(Pseudo::Break) => {
acc.insert(get_label_id(jt_gen, true), instr);
}
Instruct::Pseudo(Pseudo::Continue) => {
acc.insert(get_label_id(jt_gen, false), instr);
}
Instruct::Opcode(Opcode::RetC | Opcode::RetCSuspended | Opcode::RetM(_)) => {
acc.insert(jt_gen.get_id_for_return(), instr);
}
_ => {}
};
acc
}))
}
}
/// Delete Ret*, Break, and Continue instructions from the try body
pub(super) fn cleanup_try_body<'arena>(mut is: InstrSeq<'arena>) -> InstrSeq<'arena> {
is.retain(|instr| {
!matches!(
instr,
Instruct::Pseudo(Pseudo::Continue | Pseudo::Break)
| Instruct::Opcode(Opcode::RetC | Opcode::RetCSuspended | Opcode::RetM(_))
)
});
is
}
pub(super) fn emit_jump_to_label<'arena>(l: Label, iters: Vec<IterId>) -> InstrSeq<'arena> {
if iters.is_empty() {
instr::jmp(l)
} else {
instr::iter_break(l, iters)
}
}
pub(super) fn emit_save_label_id<'arena>(
local_gen: &mut LocalGen,
id: jt::StateId,
) -> InstrSeq<'arena> {
InstrSeq::gather(vec![
instr::int(id.0.into()),
instr::set_l(*local_gen.get_label()),
instr::pop_c(),
])
}
pub(super) fn emit_return<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
in_finally_epilogue: bool,
env: &mut Env<'a, 'arena>,
) -> Result<InstrSeq<'arena>> {
// check if there are try/finally region
let jt_gen = &env.jump_targets_gen;
match jt_gen.jump_targets().get_closest_enclosing_finally_label() {
None => {
// no finally blocks, but there might be some iterators that should be
// released before exit - do it
let ctx = e.statement_state();
let num_out = ctx.num_out;
let verify_out = ctx.verify_out.clone();
let verify_return = ctx.verify_return.clone();
let release_iterators_instr = InstrSeq::gather(
jt_gen
.jump_targets()
.iterators()
.map(instr::iter_free)
.collect(),
);
let mut instrs = Vec::with_capacity(5);
if in_finally_epilogue {
let load_retval_instr = instr::c_get_l(e.local_gen_mut().get_retval().clone());
instrs.push(load_retval_instr);
}
let verify_return_instr = verify_return.map_or_else(
|| Ok(instr::empty()),
|h| {
use reified::ReificationLevel;
let h = reified::convert_awaitable(env, h);
let h = reified::remove_erased_generics(env, h);
match reified::has_reified_type_constraint(env, &h) {
ReificationLevel::Unconstrained => Ok(instr::empty()),
ReificationLevel::Not => Ok(instr::verify_ret_type_c()),
ReificationLevel::Maybe => Ok(InstrSeq::gather(vec![
emit_expression::get_type_structure_for_hint(
e,
&[],
&IndexSet::new(),
TypeRefinementInHint::Allowed,
&h,
)?,
instr::verify_ret_type_ts(),
])),
ReificationLevel::Definitely => {
let check = InstrSeq::gather(vec![
instr::dup(),
instr::is_type_c(IsTypeOp::Null),
]);
reified::simplify_verify_type(
e,
env,
&Pos::NONE,
check,
&h,
instr::verify_ret_type_ts(),
)
}
}
},
)?;
instrs.extend(vec![
verify_return_instr,
verify_out,
release_iterators_instr,
if num_out != 0 {
instr::ret_m(num_out as u32 + 1)
} else {
instr::ret_c()
},
]);
Ok(InstrSeq::gather(instrs))
}
// ret is in finally block and there might be iterators to release -
// jump to finally block via Jmp
Some((target_label, iterators_to_release)) => {
let preamble = if in_finally_epilogue {
instr::empty()
} else {
let jt_gen = &mut env.jump_targets_gen;
let save_state = emit_save_label_id(e.local_gen_mut(), jt_gen.get_id_for_return());
let save_retval = InstrSeq::gather(vec![
instr::set_l(e.local_gen_mut().get_retval().clone()),
instr::pop_c(),
]);
InstrSeq::gather(vec![save_state, save_retval])
};
Ok(InstrSeq::gather(vec![
preamble,
emit_jump_to_label(target_label, iterators_to_release),
// emit ret instr as an indicator for try/finally rewriter to generate
// finally epilogue, try/finally rewriter will remove it.
instr::ret_c(),
]))
}
}
}
bitflags! {
pub(super) struct EmitBreakOrContinueFlags: u8 {
const IS_BREAK = 0b01;
const IN_FINALLY_EPILOGUE = 0b10;
}
}
pub(super) fn emit_break_or_continue<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
flags: EmitBreakOrContinueFlags,
env: &mut Env<'a, 'arena>,
pos: &Pos,
) -> InstrSeq<'arena> {
let alloc = env.arena;
let jt_gen = &mut env.jump_targets_gen;
let in_finally_epilogue = flags.contains(EmitBreakOrContinueFlags::IN_FINALLY_EPILOGUE);
let is_break = flags.contains(EmitBreakOrContinueFlags::IS_BREAK);
match jt_gen.jump_targets().get_target(is_break) {
jt::ResolvedJumpTarget::NotFound => emit_fatal::emit_fatal_for_break_continue(alloc, pos),
jt::ResolvedJumpTarget::ResolvedRegular(target_label, iterators_to_release) => {
let preamble = if in_finally_epilogue {
instr::unset_l(e.local_gen_mut().get_label().clone())
} else {
instr::empty()
};
InstrSeq::gather(vec![
preamble,
emit_pos(pos),
emit_jump_to_label(target_label, iterators_to_release),
])
}
jt::ResolvedJumpTarget::ResolvedTryFinally(jt::ResolvedTryFinally {
target_label,
finally_label,
iterators_to_release,
}) => {
let preamble = if !in_finally_epilogue {
let label_id = jt_gen.get_id_for_label(target_label.clone());
emit_save_label_id(e.local_gen_mut(), label_id)
} else {
instr::empty()
};
InstrSeq::gather(vec![
preamble,
emit_jump_to_label(finally_label, iterators_to_release),
emit_pos(pos),
// emit break/continue instr as an indicator for try/finally rewriter
// to generate finally epilogue - try/finally rewriter will remove it.
if is_break {
instr::break_()
} else {
instr::continue_()
},
])
}
}
}
pub(super) fn emit_finally_epilogue<'a, 'b, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
pos: &Pos,
jump_instrs: JumpInstructions<'b, 'arena>,
finally_end: Label,
) -> Result<InstrSeq<'arena>> {
fn emit_instr<'a, 'arena, 'decl>(
e: &mut Emitter<'arena, 'decl>,
env: &mut Env<'a, 'arena>,
pos: &Pos,
i: &Instruct<'arena>,
) -> Result<InstrSeq<'arena>> {
let fail = || {
panic!("unexpected instruction: only Ret* or Break/Continue/Jmp(Named) are expected")
};
match *i {
Instruct::Opcode(Opcode::RetC | Opcode::RetCSuspended | Opcode::RetM(_)) => {
emit_return(e, true, env)
}
Instruct::Pseudo(Pseudo::Break) => Ok(emit_break_or_continue(
e,
EmitBreakOrContinueFlags::IS_BREAK | EmitBreakOrContinueFlags::IN_FINALLY_EPILOGUE,
env,
pos,
)),
Instruct::Pseudo(Pseudo::Continue) => Ok(emit_break_or_continue(
e,
EmitBreakOrContinueFlags::IN_FINALLY_EPILOGUE,
env,
pos,
)),
_ => fail(),
}
}
let alloc = env.arena;
Ok(if jump_instrs.0.is_empty() {
instr::empty()
} else if jump_instrs.0.len() == 1 {
let (_, instr) = jump_instrs.0.iter().next().unwrap();
InstrSeq::gather(vec![
emit_pos(pos),
instr::isset_l(e.local_gen_mut().get_label().clone()),
instr::jmp_z(finally_end),
emit_instr(e, env, pos, instr)?,
])
} else {
// mimic HHVM behavior:
// in some cases ids can be non-consequtive - this might happen i.e. return statement
// appear in the block and it was assigned a high id before.
// ((3, Return), (1, Break), (0, Continue))
// In thid case generate switch as
// switch (id) {
// L0 -> handler for continue
// L1 -> handler for break
// FinallyEnd -> empty
// L3 -> handler for return
// }
//
// This function builds a list of labels and jump targets for switch.
// It is possible that cases ids are not consequtive
// [L1,L2,L4]. Vector of labels in switch should be dense so we need to
// fill holes with a label that points to the end of finally block
// [End, L1, L2, End, L4]
let (max_id, _) = jump_instrs.0.iter().next_back().unwrap();
let (mut labels, mut bodies) = (vec![], vec![]);
let mut limit = max_id.0 + 1;
// jump_instrs is already sorted - BTreeMap/IMap bindings took care of it
// TODO: add is_sorted assert to make sure this behavior is preserved for labels
for (id, instr) in jump_instrs.0.into_iter().rev() {
loop {
limit -= 1;
// Looping is equivalent to recursing without consuming instr
if id.0 == limit {
let label = e.label_gen_mut().next_regular();
let body = InstrSeq::gather(vec![
instr::label(label.clone()),
emit_instr(e, env, pos, instr)?,
]);
labels.push(label);
bodies.push(body);
break;
} else {
labels.push(finally_end);
};
}
}
// Base case when empty and limit > 0
for _ in 0..limit {
labels.push(finally_end);
}
InstrSeq::gather(vec![
emit_pos(pos),
instr::isset_l(e.local_gen_mut().get_label().clone()),
instr::jmp_z(finally_end),
instr::c_get_l(e.local_gen_mut().get_label().clone()),
instr::switch(bumpalo::collections::Vec::from_iter_in(
labels.into_iter().rev(),
alloc,
)),
InstrSeq::gather(bodies.into_iter().rev().collect()),
])
})
}
// TODO: This codegen is unnecessarily complex. Basically we are generating
//
// IsSetL temp
// JmpZ finally_end
// CGetL temp
// Switch Unbounded 0 <L4 L5>
// L5:
// UnsetL temp
// Jmp LContinue
// L4:
// UnsetL temp
// Jmp LBreak
//
// Two problems immediately come to mind. First, why is the unset in every case,
// instead of after the CGetL? Surely the unset doesn't modify the stack.
// Second, now we have a jump-to-jump situation.
//
// Would it not make more sense to instead say
//
// IsSetL temp
// JmpZ finally_end
// CGetL temp
// UnsetL temp
// Switch Unbounded 0 <LBreak LContinue>
//
// ? |
Rust | hhvm/hphp/hack/src/hackc/emitter/xhp_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 oxidized::ast;
use oxidized::pos::Pos;
#[derive(Debug)]
pub struct XhpAttribute<'a> {
pub type_: Option<&'a ast::Hint>,
pub class_var: &'a ast::ClassVar,
pub tag: Option<ast::XhpAttrTag>,
pub maybe_enum: Option<&'a (Pos, Vec<ast::Expr>)>,
}
impl<'a> XhpAttribute<'a> {
pub fn is_required(&self) -> bool {
matches!(
self.tag,
Some(ast::XhpAttrTag::Required) | Some(ast::XhpAttrTag::LateInit)
)
}
} |
TOML | hhvm/hphp/hack/src/hackc/emitter/cargo/ast_scope/Cargo.toml | # @generated by autocargo
[package]
name = "ast_scope"
version = "0.0.0"
edition = "2021"
[lib]
path = "../../ast_scope.rs"
[dependencies]
bumpalo = { version = "3.11.1", features = ["collections"] }
hhbc = { version = "0.0.0", path = "../../../hhbc/cargo/hhbc" }
oxidized = { version = "0.0.0", path = "../../../../oxidized" } |
TOML | hhvm/hphp/hack/src/hackc/emitter/cargo/constant_folder/Cargo.toml | # @generated by autocargo
[package]
name = "constant_folder"
version = "0.0.0"
edition = "2021"
[lib]
path = "../../constant_folder.rs"
[dependencies]
ast_scope = { version = "0.0.0", path = "../ast_scope" }
bumpalo = { version = "3.11.1", features = ["collections"] }
env = { version = "0.0.0", path = "../env" }
ffi = { version = "0.0.0", path = "../../../../utils/ffi" }
hhbc = { version = "0.0.0", path = "../../../hhbc/cargo/hhbc" }
hhbc_string_utils = { version = "0.0.0", path = "../../../utils/cargo/hhbc_string_utils" }
indexmap = { version = "1.9.2", features = ["arbitrary", "rayon", "serde-1"] }
itertools = "0.10.3"
naming_special_names_rust = { version = "0.0.0", path = "../../../../naming" }
oxidized = { version = "0.0.0", path = "../../../../oxidized" }
stack_limit = { version = "0.0.0", path = "../../../../utils/stack_limit" } |
TOML | hhvm/hphp/hack/src/hackc/emitter/cargo/emit_pos/Cargo.toml | # @generated by autocargo
[package]
name = "emit_pos"
version = "0.0.0"
edition = "2021"
[lib]
path = "../../emit_pos.rs"
[dependencies]
instruction_sequence = { version = "0.0.0", path = "../instruction_sequence" }
oxidized = { version = "0.0.0", path = "../../../../oxidized" } |
TOML | hhvm/hphp/hack/src/hackc/emitter/cargo/emit_type_hint/Cargo.toml | # @generated by autocargo
[package]
name = "emit_type_hint"
version = "0.0.0"
edition = "2021"
[lib]
path = "../../emit_type_hint.rs"
[dependencies]
bumpalo = { version = "3.11.1", features = ["collections"] }
error = { version = "0.0.0", path = "../../../error/cargo/error" }
ffi = { version = "0.0.0", path = "../../../../utils/ffi" }
hhbc = { version = "0.0.0", path = "../../../hhbc/cargo/hhbc" }
hhbc_string_utils = { version = "0.0.0", path = "../../../utils/cargo/hhbc_string_utils" }
hhvm_types_ffi = { version = "0.0.0", path = "../../../hhvm_cxx/hhvm_types" }
naming_special_names_rust = { version = "0.0.0", path = "../../../../naming" }
oxidized = { version = "0.0.0", path = "../../../../oxidized" } |
TOML | hhvm/hphp/hack/src/hackc/emitter/cargo/emit_unit/Cargo.toml | # @generated by autocargo
[package]
name = "emit_unit"
version = "0.0.0"
edition = "2021"
[lib]
path = "../../emit_unit.rs"
[dependencies]
ast_scope = { version = "0.0.0", path = "../ast_scope" }
bitflags = "1.3"
bstr = { version = "1.4.0", features = ["serde", "std", "unicode"] }
bumpalo = { version = "3.11.1", features = ["collections"] }
constant_folder = { version = "0.0.0", path = "../constant_folder" }
core_utils_rust = { version = "0.0.0", path = "../../../../utils/core" }
decl_provider = { version = "0.0.0", path = "../../../decl_provider" }
emit_pos = { version = "0.0.0", path = "../emit_pos" }
emit_type_hint = { version = "0.0.0", path = "../emit_type_hint" }
env = { version = "0.0.0", path = "../env" }
error = { version = "0.0.0", path = "../../../error/cargo/error" }
ffi = { version = "0.0.0", path = "../../../../utils/ffi" }
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" }
hhvm_types_ffi = { version = "0.0.0", path = "../../../hhvm_cxx/hhvm_types" }
indexmap = { version = "1.9.2", features = ["arbitrary", "rayon", "serde-1"] }
instruction_sequence = { version = "0.0.0", path = "../instruction_sequence" }
itertools = "0.10.3"
label_rewriter = { version = "0.0.0", path = "../label_rewriter" }
lazy_static = "1.4"
naming_special_names_rust = { version = "0.0.0", path = "../../../../naming" }
options = { version = "0.0.0", path = "../../../compile/cargo/options" }
oxidized = { version = "0.0.0", path = "../../../../oxidized" }
oxidized_by_ref = { version = "0.0.0", path = "../../../../oxidized_by_ref" }
print_expr = { version = "0.0.0", path = "../../../print_expr" }
regex = "1.9.2"
scope = { version = "0.0.0", path = "../scope" }
serde_json = { version = "1.0.100", features = ["float_roundtrip", "unbounded_depth"] }
stack_depth = { version = "0.0.0", path = "../../../utils/cargo/stack_depth" }
stack_limit = { version = "0.0.0", path = "../../../../utils/stack_limit" }
statement_state = { version = "0.0.0", path = "../statement_state" } |
TOML | hhvm/hphp/hack/src/hackc/emitter/cargo/env/Cargo.toml | # @generated by autocargo
[package]
name = "env"
version = "0.0.0"
edition = "2021"
[lib]
path = "../../env.rs"
[dependencies]
ast_scope = { version = "0.0.0", path = "../ast_scope" }
bitflags = "1.3"
bumpalo = { version = "3.11.1", features = ["collections"] }
decl_provider = { version = "0.0.0", path = "../../../decl_provider" }
ffi = { version = "0.0.0", path = "../../../../utils/ffi" }
global_state = { version = "0.0.0", path = "../global_state" }
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" }
indexmap = { version = "1.9.2", features = ["arbitrary", "rayon", "serde-1"] }
instruction_sequence = { version = "0.0.0", path = "../instruction_sequence" }
naming_special_names_rust = { version = "0.0.0", path = "../../../../naming" }
options = { version = "0.0.0", path = "../../../compile/cargo/options" }
oxidized = { version = "0.0.0", path = "../../../../oxidized" }
print_expr = { version = "0.0.0", path = "../../../print_expr" }
relative_path = { version = "0.0.0", path = "../../../../utils/rust/relative_path" }
statement_state = { version = "0.0.0", path = "../statement_state" } |
TOML | hhvm/hphp/hack/src/hackc/emitter/cargo/global_state/Cargo.toml | # @generated by autocargo
[package]
name = "global_state"
version = "0.0.0"
edition = "2021"
[lib]
path = "../../global_state.rs"
[dependencies]
hhbc = { version = "0.0.0", path = "../../../hhbc/cargo/hhbc" }
oxidized = { version = "0.0.0", path = "../../../../oxidized" }
unique_id_builder = { version = "0.0.0", path = "../../../utils/cargo/unique_id_builder" } |
TOML | hhvm/hphp/hack/src/hackc/emitter/cargo/instruction_sequence/Cargo.toml | # @generated by autocargo
[package]
name = "instruction_sequence"
version = "0.0.0"
edition = "2021"
[lib]
path = "../../instruction_sequence.rs"
[dependencies]
bumpalo = { version = "3.11.1", features = ["collections"] }
emit_opcodes_macro = { version = "0.0.0", path = "../../../hhbc/cargo/emit_opcodes_macro" }
ffi = { version = "0.0.0", path = "../../../../utils/ffi" }
hhbc = { version = "0.0.0", path = "../../../hhbc/cargo/hhbc" }
[dev-dependencies]
pretty_assertions = { version = "1.2", features = ["alloc"], default-features = false } |
TOML | hhvm/hphp/hack/src/hackc/emitter/cargo/label_rewriter/Cargo.toml | # @generated by autocargo
[package]
name = "label_rewriter"
version = "0.0.0"
edition = "2021"
[lib]
path = "../../label_rewriter.rs"
[dependencies]
bumpalo = { version = "3.11.1", features = ["collections"] }
env = { version = "0.0.0", path = "../env" }
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" }
instruction_sequence = { version = "0.0.0", path = "../instruction_sequence" }
oxidized = { version = "0.0.0", path = "../../../../oxidized" } |
TOML | hhvm/hphp/hack/src/hackc/emitter/cargo/scope/Cargo.toml | # @generated by autocargo
[package]
name = "scope"
version = "0.0.0"
edition = "2021"
[lib]
path = "../../scope.rs"
[dependencies]
env = { version = "0.0.0", path = "../env" }
error = { version = "0.0.0", path = "../../../error/cargo/error" }
hhbc = { version = "0.0.0", path = "../../../hhbc/cargo/hhbc" }
instruction_sequence = { version = "0.0.0", path = "../instruction_sequence" } |
TOML | hhvm/hphp/hack/src/hackc/emitter/cargo/statement_state/Cargo.toml | # @generated by autocargo
[package]
name = "statement_state"
version = "0.0.0"
edition = "2021"
[lib]
path = "../../statement_state.rs"
[dependencies]
instruction_sequence = { version = "0.0.0", path = "../instruction_sequence" }
oxidized = { version = "0.0.0", path = "../../../../oxidized" } |
Rust | hhvm/hphp/hack/src/hackc/error/assertion_utils.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 oxidized::ast;
use oxidized::ast_defs::ParamKind;
use crate::Error;
use crate::Result;
pub fn expect_normal_paramkind(arg: &(ParamKind, ast::Expr)) -> Result<&ast::Expr> {
match arg {
(ParamKind::Pnormal, e) => Ok(e),
(ParamKind::Pinout(pk_pos), _) => {
Err(Error::fatal_parse(pk_pos, "Unexpected `inout` annotation"))
}
}
}
pub fn ensure_normal_paramkind(pk: &ParamKind) -> Result<()> {
match pk {
ParamKind::Pnormal => Ok(()),
ParamKind::Pinout(p) => Err(Error::fatal_parse(p, "Unexpected `inout` annotation")),
}
} |
Rust | hhvm/hphp/hack/src/hackc/error/error.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 assertion_utils;
pub use assertion_utils::*;
use hhvm_hhbc_defs_ffi::ffi::FatalOp;
use oxidized::ast_defs::Pos;
use thiserror::Error;
pub type Result<T, E = Error> = std::result::Result<T, E>;
#[derive(Error, Debug)]
#[error(transparent)]
pub struct Error(Box<ErrorKind>);
impl Error {
pub fn unrecoverable(msg: impl Into<String>) -> Self {
Self(Box::new(ErrorKind::Unrecoverable(msg.into())))
}
pub fn fatal_runtime(pos: &Pos, msg: impl Into<String>) -> Self {
Self(Box::new(ErrorKind::IncludeTimeFatalException(
FatalOp::Runtime,
pos.clone(),
msg.into(),
)))
}
pub fn fatal_parse(pos: &Pos, msg: impl Into<String>) -> Self {
Self(Box::new(ErrorKind::IncludeTimeFatalException(
FatalOp::Parse,
pos.clone(),
msg.into(),
)))
}
pub fn kind(&self) -> &ErrorKind {
&self.0
}
pub fn into_kind(self) -> ErrorKind {
*self.0
}
pub fn from_error(e: impl std::error::Error) -> Self {
Self::unrecoverable(e.to_string())
}
}
#[derive(Error, Debug)]
pub enum ErrorKind {
#[error("IncludeTimeFatalException: FatalOp={0:?}, {1}")]
IncludeTimeFatalException(FatalOp, Pos, std::string::String),
#[error("Unrecoverable: {0}")]
Unrecoverable(std::string::String),
} |
TOML | hhvm/hphp/hack/src/hackc/error/cargo/error/Cargo.toml | # @generated by autocargo
[package]
name = "error"
version = "0.0.0"
edition = "2021"
[lib]
path = "../../error.rs"
[dependencies]
hhvm_hhbc_defs_ffi = { version = "0.0.0", path = "../../../hhvm_cxx/hhvm_hhbc_defs" }
oxidized = { version = "0.0.0", path = "../../../../oxidized" }
thiserror = "1.0.43" |
Rust | hhvm/hphp/hack/src/hackc/facts/facts.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 hhbc_string_utils::mangle_xhp_id;
use hhbc_string_utils::strip_global_ns;
use naming_special_names_rust::user_attributes;
use oxidized_by_ref::ast_defs::Abstraction;
use oxidized_by_ref::ast_defs::ClassishKind;
use oxidized_by_ref::direct_decl_parser::ParsedFile;
use oxidized_by_ref::shallow_decl_defs::ClassDecl;
use oxidized_by_ref::shallow_decl_defs::TypedefDecl;
use oxidized_by_ref::typing_defs::Ty;
use oxidized_by_ref::typing_defs::Ty_;
use oxidized_by_ref::typing_defs::UserAttribute;
use oxidized_by_ref::typing_defs::UserAttributeParam;
use serde::de::SeqAccess;
use serde::de::Visitor;
use serde::ser::SerializeSeq;
use serde::Deserializer;
use serde::Serializer;
use serde_derive::Deserialize;
use serde_derive::Serialize;
use serde_json::json;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum TypeKind {
Class,
Interface,
Enum,
Trait,
TypeAlias,
Unknown,
Mixed,
}
impl Default for TypeKind {
fn default() -> Self {
Self::Unknown
}
}
pub type StringSet = BTreeSet<String>;
pub type Attributes = BTreeMap<String, Vec<serde_json::Value>>;
pub type Methods = BTreeMap<String, MethodFacts>;
pub type TypeFactsByName = BTreeMap<String, TypeFacts>;
#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct MethodFacts {
#[serde(default, skip_serializing_if = "Attributes::is_empty")]
pub attributes: Attributes,
}
#[derive(Debug, PartialEq, Serialize, Deserialize, Default, Clone)]
#[serde(rename_all = "camelCase")]
pub struct TypeFacts {
#[serde(default, skip_serializing_if = "StringSet::is_empty")]
pub base_types: StringSet,
#[serde(rename = "kindOf")]
pub kind: TypeKind,
#[serde(default)]
pub attributes: Attributes,
pub flags: Flags,
#[serde(default, skip_serializing_if = "StringSet::is_empty")]
pub require_extends: StringSet,
#[serde(default, skip_serializing_if = "StringSet::is_empty")]
pub require_implements: StringSet,
#[serde(default, skip_serializing_if = "StringSet::is_empty")]
pub require_class: StringSet,
#[serde(default, skip_serializing_if = "Methods::is_empty")]
pub methods: Methods,
}
// Currently module facts are empty, but added for backward compatibility
#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ModuleFacts {}
pub type ModuleFactsByName = BTreeMap<String, ModuleFacts>;
#[derive(Default, Debug, PartialEq, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Facts {
#[serde(
default,
skip_serializing_if = "TypeFactsByName::is_empty",
serialize_with = "types_to_json",
deserialize_with = "json_to_types"
)]
pub types: TypeFactsByName,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub functions: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub constants: Vec<String>,
#[serde(default, skip_serializing_if = "Attributes::is_empty")]
pub file_attributes: Attributes,
#[serde(
default,
skip_serializing_if = "ModuleFactsByName::is_empty",
serialize_with = "modules_to_json",
deserialize_with = "json_to_modules"
)]
pub modules: ModuleFactsByName,
}
impl Facts {
pub fn to_json(&self, pretty: bool, sha1sum: &str) -> String {
let mut json = json!(&self);
if let Some(m) = json.as_object_mut() {
m.insert("sha1sum".into(), json!(sha1sum));
};
if pretty {
serde_json::to_string_pretty(&json).expect("Could not serialize facts to JSON")
} else {
serde_json::to_string(&json).expect("Could not serialize facts to JSON")
}
}
pub fn from_decls(parsed_file: &ParsedFile<'_>) -> Facts {
let mut types = TypeFactsByName::new();
parsed_file.decls.classes().for_each(|(class_name, decl)| {
let mut name = format(class_name);
if !parsed_file.disable_xhp_element_mangling && decl.is_xhp {
// strips the namespace and mangles the class id
if let Some(id) = name.rsplit('\\').next() {
name = id.to_string();
}
}
let type_fact = TypeFacts::of_class_decl(decl);
add_or_update_classish_decl(name, type_fact, &mut types);
});
for (name, decl) in parsed_file.decls.typedefs().filter(|(_, decl)| {
// Ignore context aliases
!decl.is_ctx
}) {
let type_fact = TypeFacts::of_typedef_decl(decl);
add_or_update_classish_decl(format(name), type_fact, &mut types);
}
let mut functions = parsed_file
.decls
.funs()
.filter_map(|(name, _)| {
let name = format(name);
if name.eq("__construct") {
None
} else {
Some(name)
}
})
.collect::<Vec<String>>();
let mut constants = parsed_file
.decls
.consts()
.map(|(name, _)| format(name))
.collect::<Vec<String>>();
let mut modules = ModuleFactsByName::new();
parsed_file
.decls
.modules()
.for_each(|(module_name, _decl)| {
let name = format(module_name);
add_or_update_module_decl(name, ModuleFacts {}, &mut modules);
});
functions.reverse();
constants.reverse();
let file_attributes = to_facts_attributes(parsed_file.file_attributes);
Facts {
types,
functions,
constants,
file_attributes,
modules,
}
}
}
pub type Flags = u8;
#[derive(Clone, Copy)]
pub enum Flag {
Abstract = 1,
Final = 2,
MultipleDeclarations = 4,
}
impl Flag {
pub fn as_flags(&self) -> Flags {
*self as Flags
}
pub fn zero() -> Flags {
0
}
pub fn is_set(&self, flags: Flags) -> bool {
(flags & (*self as Flags)) != 0
}
pub fn set(self, flags: Flags) -> Flags {
flags | (self as Flags)
}
pub fn combine(flags1: Flags, flags2: Flags) -> Flags {
flags1 | flags2
}
}
// implementation details
fn modules_to_json<S: Serializer>(
modules_by_name: &ModuleFactsByName,
s: S,
) -> Result<S::Ok, S::Error> {
let mut seq = s.serialize_seq(None)?;
for (name, modules) in modules_by_name.iter() {
let mut modules_json = json!(modules);
if let Some(m) = modules_json.as_object_mut() {
m.insert("name".to_owned(), json!(name));
};
seq.serialize_element(&modules_json)?;
}
seq.end()
}
/// Serialize the Map<Name, TypeFacts> as a sequence of JSON objects with `name`
/// as one of the fields.
fn types_to_json<S: Serializer>(types_by_name: &TypeFactsByName, s: S) -> Result<S::Ok, S::Error> {
let mut seq = s.serialize_seq(None)?;
for (name, types) in types_by_name.iter() {
// pull the "name" key into the associated json object, then append to list
let mut types_json = json!(types);
if let Some(m) = types_json.as_object_mut() {
m.insert("name".to_owned(), json!(name));
};
// possibly skip non-empty attributes/require*, depending on the kind
if types.skip_attributes() {
types_json.as_object_mut().map(|m| m.remove("attributes"));
}
if types.skip_require_extends() {
types_json
.as_object_mut()
.map(|m| m.remove("requireExtends"));
}
if types.skip_require_implements() {
types_json
.as_object_mut()
.map(|m| m.remove("requireImplements"));
}
if types.skip_require_class() {
types_json.as_object_mut().map(|m| m.remove("requireClass"));
}
seq.serialize_element(&types_json)?;
}
seq.end()
}
/// Deserialize a sequence of TypeFacts with `name` fields as a Map by hoisting
/// the name as the map key.
fn json_to_types<'de, D: Deserializer<'de>>(d: D) -> Result<TypeFactsByName, D::Error> {
struct TypeFactsSeqVisitor;
impl<'de> Visitor<'de> for TypeFactsSeqVisitor {
type Value = TypeFactsByName;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "a sequence of TypeFacts")
}
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
let mut types = TypeFactsByName::new();
while let Some(mut v) = seq.next_element::<serde_json::Value>()? {
let obj = v
.as_object_mut()
.ok_or_else(|| serde::de::Error::custom("Expected TypeFacts JSON Object"))?;
let name = obj
.remove("name")
.ok_or_else(|| serde::de::Error::missing_field("name"))?;
let name = name
.as_str()
.ok_or_else(|| serde::de::Error::custom("Expected name JSON String"))?;
types.insert(
name.into(),
serde_json::from_value(v).map_err(serde::de::Error::custom)?,
);
}
Ok(types)
}
}
d.deserialize_seq(TypeFactsSeqVisitor)
}
/// Deserialize a sequence of TypeFacts with `name` fields as a Map by hoisting
/// the name as the map key.
fn json_to_modules<'de, D: Deserializer<'de>>(d: D) -> Result<ModuleFactsByName, D::Error> {
struct ModuleFactsSeqVisitor;
impl<'de> Visitor<'de> for ModuleFactsSeqVisitor {
type Value = ModuleFactsByName;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "a sequence of ModuleFacts")
}
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
let mut modules = ModuleFactsByName::new();
while let Some(mut v) = seq.next_element::<serde_json::Value>()? {
let obj = v
.as_object_mut()
.ok_or_else(|| serde::de::Error::custom("Expected ModuleFacts JSON Object"))?;
let name = obj
.remove("name")
.ok_or_else(|| serde::de::Error::missing_field("name"))?;
let name = name
.as_str()
.ok_or_else(|| serde::de::Error::custom("Expected name JSON String"))?;
modules.insert(
name.into(),
serde_json::from_value(v).map_err(serde::de::Error::custom)?,
);
}
Ok(modules)
}
}
d.deserialize_seq(ModuleFactsSeqVisitor)
}
impl TypeFacts {
fn skip_require_extends(&self) -> bool {
match self.kind {
TypeKind::Trait | TypeKind::Interface => false,
_ => self.require_extends.is_empty(),
}
}
fn skip_require_implements(&self) -> bool {
match self.kind {
TypeKind::Trait => false,
_ => self.require_implements.is_empty(),
}
}
fn skip_require_class(&self) -> bool {
match self.kind {
TypeKind::Trait => false,
_ => self.require_class.is_empty(),
}
}
fn skip_attributes(&self) -> bool {
self.attributes.is_empty()
}
fn of_class_decl<'a>(decl: &'a ClassDecl<'a>) -> TypeFacts {
let ClassDecl {
kind,
final_,
req_implements,
req_extends,
req_class,
uses,
extends,
implements,
user_attributes,
methods,
static_methods,
enum_type,
..
} = decl;
// Collect base types from uses, extends, and implements
let mut base_types = StringSet::new();
uses.iter().for_each(|ty| {
base_types.insert(extract_type_name(ty));
});
extends.iter().for_each(|ty| {
base_types.insert(extract_type_name(ty));
});
implements.iter().for_each(|ty| {
base_types.insert(extract_type_name(ty));
});
// Set flags according to modifiers - abstract, final, static (abstract + final)
let mut flags = Flags::default();
let typekind = match kind {
ClassishKind::Cclass(abstraction) => {
flags = modifiers_to_flags(flags, *final_, *abstraction);
TypeKind::Class
}
ClassishKind::Cinterface => {
flags = Flag::Abstract.as_flags();
TypeKind::Interface
}
ClassishKind::Ctrait => {
flags = Flag::Abstract.as_flags();
TypeKind::Trait
}
ClassishKind::Cenum => {
if let Some(et) = enum_type {
et.includes.iter().for_each(|ty| {
base_types.insert(extract_type_name(ty));
});
}
TypeKind::Enum
}
ClassishKind::CenumClass(abstraction) => {
flags = modifiers_to_flags(flags, *final_, *abstraction);
TypeKind::Enum
}
};
let check_require = match typekind {
TypeKind::Interface | TypeKind::Trait => true,
_ => false,
};
// Collect the requires
let require_extends = req_extends
.iter()
.filter_map(|&ty| {
if check_require {
Some(extract_type_name(ty))
} else {
None
}
})
.collect::<StringSet>();
let require_implements = req_implements
.iter()
.filter_map(|&ty| {
if check_require {
Some(extract_type_name(ty))
} else {
None
}
})
.collect::<StringSet>();
let require_class = req_class
.iter()
.filter_map(|&ty| {
if check_require {
Some(extract_type_name(ty))
} else {
None
}
})
.collect::<StringSet>();
// TODO(T101762617): modify the direct decl parser to
// preserve the attribute params that facts expects
let attributes = to_facts_attributes(user_attributes);
let methods = methods
.iter()
.chain(static_methods.iter())
.filter_map(|m| {
let attributes = to_facts_attributes(m.attributes);
// Add this method to the output iff it's
// decorated with non-builtin attributes
if attributes.is_empty() {
None
} else {
Some((format(m.name.1), MethodFacts { attributes }))
}
})
.collect::<Methods>();
TypeFacts {
base_types,
kind: typekind,
require_extends,
flags,
require_implements,
require_class,
attributes,
methods,
}
}
fn of_typedef_decl<'a>(decl: &'a TypedefDecl<'a>) -> TypeFacts {
TypeFacts {
base_types: StringSet::new(),
kind: TypeKind::TypeAlias,
attributes: to_facts_attributes(decl.attributes),
require_extends: StringSet::new(),
flags: Flags::default(),
require_implements: StringSet::new(),
require_class: StringSet::new(),
methods: BTreeMap::new(),
}
}
}
fn add_or_update_classish_decl(name: String, mut delta: TypeFacts, types: &mut TypeFactsByName) {
types
.entry(name)
.and_modify(|tf| {
if tf.kind != delta.kind {
tf.kind = TypeKind::Mixed;
}
tf.flags = Flag::MultipleDeclarations.set(tf.flags);
tf.flags = Flag::combine(tf.flags, delta.flags);
tf.base_types.append(&mut delta.base_types);
tf.attributes.append(&mut delta.attributes);
tf.require_extends.append(&mut delta.require_extends);
tf.require_implements.append(&mut delta.require_implements);
tf.require_class.append(&mut delta.require_class)
})
.or_insert(delta);
}
fn add_or_update_module_decl(name: String, delta: ModuleFacts, types: &mut ModuleFactsByName) {
types
.entry(name)
// .and_modify(|mf| {}) (to be added when modules have actual bodies)
.or_insert(delta);
}
// TODO: move to typing_defs_core_impl.rs once completed
fn extract_type_name<'a>(ty: &Ty<'a>) -> String {
match ty.get_node() {
Ty_::Tapply(((_, id), _)) => format(id),
Ty_::Tgeneric((id, _)) => format(id),
_ => unimplemented!("{:?}", ty),
}
}
fn format(original_name: &str) -> String {
let unqualified = strip_global_ns(original_name);
match unqualified.rsplit('\\').next() {
Some(id) if original_name.starts_with('\\') && id.starts_with(':') => {
// only mangle already qualified xhp ids - avoid mangling string literals
// containing an xhp name, for example an attribute param ':foo:bar'
mangle_xhp_id(id.to_string())
}
_ => String::from(unqualified),
}
}
fn modifiers_to_flags(flags: Flags, is_final: bool, abstraction: Abstraction) -> Flags {
let flags = match abstraction {
Abstraction::Abstract => Flag::Abstract.set(flags),
Abstraction::Concrete => flags,
};
if is_final {
Flag::Final.set(flags)
} else {
flags
}
}
fn to_facts_attributes<'a>(attributes: &'a [&'a UserAttribute<'a>]) -> Attributes {
use serde_json::Value;
attributes
.iter()
.filter_map(|ua| {
let params = (ua.params.iter())
.filter_map(|p| match *p {
UserAttributeParam::Classname(cn) => Some(Value::String(format(cn))),
UserAttributeParam::String(s) => Some(Value::String(s.to_string())),
UserAttributeParam::Int(i) => Some(Value::String(i.to_owned())),
_ => None,
})
.collect();
let attr_name = format(ua.name.1);
if user_attributes::is_reserved(&attr_name) {
// skip builtins
None
} else {
Some((attr_name, params))
}
})
.collect::<Attributes>()
}
// inline tests (so stuff can remain hidden) - compiled only when tests are run (no overhead)
#[cfg(test)]
mod tests {
use pretty_assertions::assert_eq;
use super::*; // make assert_eq print huge diffs more human-readable
fn sha1(text: &[u8]) -> String {
use digest::Digest;
let mut digest = sha1::Sha1::new();
digest.update(text);
hex::encode(digest.finalize())
}
#[test]
fn type_kind_to_json() {
assert_eq!(json!(TypeKind::Unknown).to_string(), "\"unknown\"");
assert_eq!(json!(TypeKind::Interface).to_string(), "\"interface\"");
}
#[test]
fn sha1_some_text() {
let text = b"some text";
assert_eq!(
sha1(text),
String::from("37aa63c77398d954473262e1a0057c1e632eda77"),
);
}
#[test]
fn string_set_to_json() {
let mut ss = StringSet::new();
ss.insert("foo".into());
ss.insert("bar".into());
assert_eq!(
r#"[
"bar",
"foo"
]"#,
serde_json::to_string_pretty(&ss).unwrap(),
);
}
fn fake_facts() -> (Facts, String) {
let mut types = TypeFactsByName::new();
let mut base_types = StringSet::new();
base_types.insert("bt3".into());
base_types.insert("bt1".into());
base_types.insert("bt2".into());
types.insert(
String::from("include_empty_both_when_trait_kind"),
TypeFacts {
kind: TypeKind::Trait,
base_types,
flags: 6,
..Default::default()
},
);
// verify requireImplements, requireExtends and requireClass are skipped if empty and Class kind
types.insert(
String::from("include_empty_neither_when_class_kind"),
TypeFacts {
kind: TypeKind::Class,
flags: 0,
..Default::default()
},
);
// verify only requireImplements is skipped if empty and Interface kind
types.insert(
String::from("include_empty_req_extends_when_interface_kind"),
TypeFacts {
kind: TypeKind::Interface,
flags: 1,
..Default::default()
},
);
// verify non-empty require* is included
types.insert(
String::from("include_nonempty_always"),
TypeFacts {
kind: TypeKind::Unknown,
flags: 9,
attributes: {
let mut map = Attributes::new();
map.insert("A".into(), vec!["'B'".into()]);
map.insert("C".into(), Vec::new());
map
},
require_extends: {
let mut set = StringSet::new();
set.insert("extends1".into());
set
},
require_implements: {
let mut set = StringSet::new();
set.insert("impl1".into());
set
},
require_class: {
let mut set = StringSet::new();
set.insert("class1".into());
set
},
..Default::default()
},
);
types.insert(
String::from("include_method_attrs"),
TypeFacts {
kind: TypeKind::Class,
flags: 6,
methods: vec![
(
String::from("no_attrs"),
MethodFacts {
attributes: Attributes::new(),
},
),
(
String::from("one_attr_with_arg"),
MethodFacts {
attributes: vec![(String::from("attr_with_arg"), vec!["arg".into()])]
.into_iter()
.collect(),
},
),
]
.into_iter()
.collect(),
..Default::default()
},
);
types.insert(
String::from("my_type_alias"),
TypeFacts {
kind: TypeKind::TypeAlias,
..Default::default()
},
);
let mut modules = ModuleFactsByName::new();
modules.insert(String::from("foo"), ModuleFacts {});
let facts = Facts {
constants: vec!["c1".into(), "c2".into()],
file_attributes: BTreeMap::new(),
functions: vec![],
modules,
types,
};
(facts, sha1(b"fake source text"))
}
#[test]
fn round_trip_json() -> serde_json::Result<()> {
let (f1, sha1) = fake_facts();
let ugly = f1.to_json(false, &sha1);
let f2 = serde_json::from_str(&ugly)?;
assert_eq!(f1, f2);
let pretty = f1.to_json(true, &sha1);
let f2 = serde_json::from_str(&pretty)?;
assert_eq!(f1, f2);
Ok(())
}
#[test]
fn to_json() {
// test to_string_pretty()
let (facts, sha1) = fake_facts();
assert_eq!(
facts.to_json(true, &sha1),
r#"{
"constants": [
"c1",
"c2"
],
"modules": [
{
"name": "foo"
}
],
"sha1sum": "883c01f3eb209c249f88908675c8632a04a817cf",
"types": [
{
"baseTypes": [
"bt1",
"bt2",
"bt3"
],
"flags": 6,
"kindOf": "trait",
"name": "include_empty_both_when_trait_kind"
},
{
"flags": 0,
"kindOf": "class",
"name": "include_empty_neither_when_class_kind"
},
{
"flags": 1,
"kindOf": "interface",
"name": "include_empty_req_extends_when_interface_kind"
},
{
"flags": 6,
"kindOf": "class",
"methods": {
"no_attrs": {},
"one_attr_with_arg": {
"attributes": {
"attr_with_arg": [
"arg"
]
}
}
},
"name": "include_method_attrs"
},
{
"attributes": {
"A": [
"'B'"
],
"C": []
},
"flags": 9,
"kindOf": "unknown",
"name": "include_nonempty_always",
"requireClass": [
"class1"
],
"requireExtends": [
"extends1"
],
"requireImplements": [
"impl1"
]
},
{
"flags": 0,
"kindOf": "typeAlias",
"name": "my_type_alias"
}
]
}"#,
)
}
#[test]
fn test_flags() {
let flags = Flag::zero();
assert!(!Flag::Final.is_set(flags));
let flags = Flag::Final.set(flags);
let flags = Flag::Abstract.set(flags);
assert!(Flag::Final.is_set(flags));
assert!(Flag::Abstract.is_set(flags));
}
} |
TOML | hhvm/hphp/hack/src/hackc/facts/cargo/facts_rust/Cargo.toml | # @generated by autocargo
[package]
name = "facts"
version = "0.0.0"
edition = "2021"
[lib]
path = "../../facts.rs"
[dependencies]
hhbc_string_utils = { version = "0.0.0", path = "../../../utils/cargo/hhbc_string_utils" }
naming_special_names_rust = { version = "0.0.0", path = "../../../../naming" }
oxidized_by_ref = { version = "0.0.0", path = "../../../../oxidized_by_ref" }
serde = { version = "1.0.176", features = ["derive", "rc"] }
serde_derive = "1.0.176"
serde_json = { version = "1.0.100", features = ["float_roundtrip", "unbounded_depth"] }
[dev-dependencies]
digest = "0.10"
hex = "0.4.3"
pretty_assertions = { version = "1.2", features = ["alloc"], default-features = false }
sha1 = "0.10.5" |
TOML | hhvm/hphp/hack/src/hackc/ffi_bridge/Cargo.toml | # @generated by autocargo
[package]
name = "compiler_ffi"
version = "0.0.0"
edition = "2021"
[lib]
path = "compiler_ffi.rs"
crate-type = ["lib", "staticlib"]
[dependencies]
anyhow = "1.0.71"
bincode = "1.3.3"
bumpalo = { version = "3.11.1", features = ["collections"] }
compile = { version = "0.0.0", path = "../compile/cargo/compile" }
cxx = "1.0.100"
decl_provider = { version = "0.0.0", path = "../decl_provider" }
direct_decl_parser = { version = "0.0.0", path = "../../parser/api/cargo/direct_decl_parser" }
facts = { version = "0.0.0", path = "../facts/cargo/facts_rust" }
hash = { version = "0.0.0", path = "../../utils/hash" }
hhbc = { version = "0.0.0", path = "../hhbc/cargo/hhbc" }
itertools = "0.10.3"
libc = "0.2.139"
options = { version = "0.0.0", path = "../compile/cargo/options" }
parser_core_types = { version = "0.0.0", path = "../../parser/cargo/core_types" }
relative_path = { version = "0.0.0", path = "../../utils/rust/relative_path" }
serde_json = { version = "1.0.100", features = ["float_roundtrip", "unbounded_depth"] }
sha1 = "0.10.5"
thiserror = "1.0.43"
[build-dependencies]
cxx-build = "1.0.100" |
Rust | hhvm/hphp/hack/src/hackc/ffi_bridge/compiler_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.
// Module containing conversion methods between the Rust Facts and
// Rust/C++ shared Facts (in the compile_ffi module)
mod compiler_ffi_impl;
pub mod external_decl_provider;
use std::ffi::c_void;
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
use std::path::PathBuf;
use std::sync::Arc;
use anyhow::Result;
use compile::EnvFlags;
use cxx::CxxString;
use decl_provider::DeclProvider;
use decl_provider::SelfProvider;
use direct_decl_parser::DeclParserOptions;
use direct_decl_parser::ParsedFile;
use external_decl_provider::ExternalDeclProvider;
use hhbc::Unit;
use options::HhbcFlags;
use options::Hhvm;
use options::ParserOptions;
use parser_core_types::source_text::SourceText;
use relative_path::Prefix;
use relative_path::RelativePath;
use sha1::Digest;
use sha1::Sha1;
#[allow(clippy::derivable_impls)]
#[cxx::bridge(namespace = "HPHP::hackc")]
pub mod compile_ffi {
enum JitEnableRenameFunction {
Disable,
Enable,
RestrictedEnable,
}
struct NativeEnv {
/// Pointer to decl_provider opaque object, cast to usize. 0 means null.
decl_provider: usize,
filepath: String,
aliased_namespaces: Vec<StringMapEntry>,
include_roots: Vec<StringMapEntry>,
renamable_functions: Vec<String>,
non_interceptable_functions: Vec<String>,
jit_enable_rename_function: JitEnableRenameFunction,
hhbc_flags: HhbcFlags,
parser_flags: ParserFlags,
flags: EnvFlags,
}
struct StringMapEntry {
key: String,
value: String,
}
/// compiler::EnvFlags exposed to C++
struct EnvFlags {
is_systemlib: bool,
for_debugger_eval: bool,
disable_toplevel_elaboration: bool,
enable_ir: bool,
}
/// compiler::HhbcFlags exposed to C++
struct HhbcFlags {
ltr_assign: bool,
uvs: bool,
log_extern_compiler_perf: bool,
enable_intrinsics_extension: bool,
emit_cls_meth_pointers: bool,
emit_meth_caller_func_pointers: bool,
fold_lazy_class_keys: bool,
readonly_nonlocal_infer: bool,
optimize_reified_param_checks: bool,
stress_shallow_decl_deps: bool,
stress_folded_decl_deps: bool,
}
struct ParserFlags {
abstract_static_props: bool,
allow_new_attribute_syntax: bool,
allow_unstable_features: bool,
const_default_func_args: bool,
const_static_props: bool,
disable_lval_as_an_expression: bool,
disallow_inst_meth: bool,
disable_xhp_element_mangling: bool,
disallow_func_ptrs_in_constants: bool,
enable_xhp_class_modifier: bool,
enable_class_level_where_clauses: bool,
disallow_static_constants_in_default_func_args: bool,
}
struct DeclParserConfig {
aliased_namespaces: Vec<StringMapEntry>,
disable_xhp_element_mangling: bool,
interpret_soft_types_as_like_types: bool,
allow_new_attribute_syntax: bool,
enable_xhp_class_modifier: bool,
php5_compat_mode: bool,
hhvm_compat_mode: bool,
}
pub struct DeclsAndBlob {
serialized: Vec<u8>,
decls: Box<DeclsHolder>,
has_errors: bool,
}
#[derive(Debug)]
enum TypeKind {
Class,
Interface,
Enum,
Trait,
TypeAlias,
Unknown,
Mixed,
}
#[derive(Debug, PartialEq)]
struct Attribute {
name: String,
/// Values are Hack values encoded as JSON
args: Vec<String>,
}
#[derive(Debug, PartialEq)]
struct MethodDetails {
name: String,
attributes: Vec<Attribute>,
}
#[derive(Debug, PartialEq)]
pub struct TypeDetails {
name: String,
kind: TypeKind,
flags: u8,
/// List of types which this `extends`, `implements`, or `use`s
base_types: Vec<String>,
// List of attributes and their arguments
attributes: Vec<Attribute>,
/// List of classes which this `require class`
require_class: Vec<String>,
/// List of classes or interfaces which this `require extends`
require_extends: Vec<String>,
/// List of interfaces which this `require implements`
require_implements: Vec<String>,
methods: Vec<MethodDetails>,
}
#[derive(Debug, PartialEq)]
struct ModuleDetails {
name: String,
}
#[derive(Debug, Default, PartialEq)]
pub struct FileFacts {
types: Vec<TypeDetails>,
functions: Vec<String>,
constants: Vec<String>,
modules: Vec<ModuleDetails>,
attributes: Vec<Attribute>,
sha1hex: String,
}
extern "Rust" {
type DeclsHolder;
type UnitWrapper;
/// Compile Hack source code to a Unit or an error.
unsafe fn compile_unit_from_text(
env: &NativeEnv,
source_text: &[u8],
) -> Result<Box<UnitWrapper>>;
/// Compile Hack source code to either HHAS or an error.
fn compile_from_text(env: &NativeEnv, source_text: &[u8]) -> Result<Vec<u8>>;
/// Invoke the hackc direct decl parser and return every shallow decl in the file,
/// as well as a serialized blob holding the same content.
fn direct_decl_parse_and_serialize(
config: &DeclParserConfig,
filename: &CxxString,
text: &[u8],
) -> DeclsAndBlob;
/// Invoke the hackc direct decl parser and return every shallow decl in the file.
/// Return Err(_) if there were decl parsing errors, which will translate to
/// throwing an exception to the C++ caller.
fn parse_decls(
config: &DeclParserConfig,
filename: &CxxString,
text: &[u8],
) -> Result<Box<DeclsHolder>>;
fn hash_unit(unit: &UnitWrapper) -> [u8; 20];
/// Return true if this type (class or alias) is in the given Decls.
fn type_exists(decls: &DeclsHolder, symbol: &str) -> bool;
/// For testing: return true if deserializing produces the expected Decls.
fn verify_deserialization(decls: &DeclsAndBlob) -> bool;
/// Extract Facts from Decls, passing along the source text hash.
fn decls_to_facts(decls: &DeclsHolder, sha1sum: &CxxString) -> FileFacts;
/// Extract Facts in condensed JSON format from Decls, including the source text hash.
fn decls_to_facts_json(decls: &DeclsHolder, sha1sum: &CxxString) -> String;
}
}
// Opaque to C++, so we don't need repr(C).
#[derive(Debug)]
pub struct DeclsHolder {
_arena: bumpalo::Bump,
parsed_file: ParsedFile<'static>,
}
// This is accessed in test_ffi.cpp; hence repr(C)
#[derive(Debug)]
#[repr(C)]
pub struct UnitWrapper(Unit<'static>, bumpalo::Bump);
///////////////////////////////////////////////////////////////////////////////////
impl From<compile_ffi::JitEnableRenameFunction> for options::JitEnableRenameFunction {
fn from(other: compile_ffi::JitEnableRenameFunction) -> Self {
match other {
compile_ffi::JitEnableRenameFunction::Enable => Self::Enable,
compile_ffi::JitEnableRenameFunction::Disable => Self::Disable,
compile_ffi::JitEnableRenameFunction::RestrictedEnable => Self::RestrictedEnable,
_ => panic!("Enum value does not match one of listed variants"),
}
}
}
///////////////////////////////////////////////////////////////////////////////////
impl compile_ffi::NativeEnv {
fn to_compile_env(&self) -> Option<compile::NativeEnv> {
Some(compile::NativeEnv {
filepath: RelativePath::make(
Prefix::Dummy,
PathBuf::from(OsStr::from_bytes(self.filepath.as_bytes())),
),
hhvm: Hhvm {
include_roots: (self.include_roots.iter())
.map(|e| (e.key.clone().into(), e.value.clone().into()))
.collect(),
renamable_functions: self
.renamable_functions
.iter()
.map(|e| e.clone().into())
.collect(),
jit_enable_rename_function: self.jit_enable_rename_function.into(),
non_interceptable_functions: self
.non_interceptable_functions
.iter()
.map(|e| e.clone().into())
.collect(),
parser_options: ParserOptions {
po_auto_namespace_map: (self.aliased_namespaces.iter())
.map(|e| (e.key.clone(), e.value.clone()))
.collect(),
po_abstract_static_props: self.parser_flags.abstract_static_props,
po_allow_new_attribute_syntax: self.parser_flags.allow_new_attribute_syntax,
po_allow_unstable_features: self.parser_flags.allow_unstable_features,
po_const_default_func_args: self.parser_flags.const_default_func_args,
tco_const_static_props: self.parser_flags.const_static_props,
po_disable_lval_as_an_expression: self
.parser_flags
.disable_lval_as_an_expression,
po_disable_xhp_element_mangling: self.parser_flags.disable_xhp_element_mangling,
po_disallow_func_ptrs_in_constants: self
.parser_flags
.disallow_func_ptrs_in_constants,
po_enable_xhp_class_modifier: self.parser_flags.enable_xhp_class_modifier,
po_enable_class_level_where_clauses: self
.parser_flags
.enable_class_level_where_clauses,
po_disallow_static_constants_in_default_func_args: self
.parser_flags
.disallow_static_constants_in_default_func_args,
..Default::default()
},
},
hhbc_flags: HhbcFlags {
ltr_assign: self.hhbc_flags.ltr_assign,
uvs: self.hhbc_flags.uvs,
log_extern_compiler_perf: self.hhbc_flags.log_extern_compiler_perf,
enable_intrinsics_extension: self.hhbc_flags.enable_intrinsics_extension,
emit_cls_meth_pointers: self.hhbc_flags.emit_cls_meth_pointers,
emit_meth_caller_func_pointers: self.hhbc_flags.emit_meth_caller_func_pointers,
fold_lazy_class_keys: self.hhbc_flags.fold_lazy_class_keys,
readonly_nonlocal_infer: self.hhbc_flags.readonly_nonlocal_infer,
optimize_reified_param_checks: self.hhbc_flags.optimize_reified_param_checks,
stress_shallow_decl_deps: self.hhbc_flags.stress_shallow_decl_deps,
stress_folded_decl_deps: self.hhbc_flags.stress_folded_decl_deps,
..Default::default()
},
flags: EnvFlags {
is_systemlib: self.flags.is_systemlib,
for_debugger_eval: self.flags.for_debugger_eval,
disable_toplevel_elaboration: self.flags.disable_toplevel_elaboration,
enable_ir: self.flags.enable_ir,
..Default::default()
},
})
}
}
fn hash_unit(UnitWrapper(unit, _): &UnitWrapper) -> [u8; 20] {
let mut hasher = Sha1::new();
let w = std::io::BufWriter::new(&mut hasher);
bincode::serialize_into(w, unit).unwrap();
hasher.finalize().into()
}
fn compile_from_text(env: &compile_ffi::NativeEnv, source_text: &[u8]) -> Result<Vec<u8>, String> {
let native_env = env.to_compile_env().unwrap();
let text = SourceText::make(
std::sync::Arc::new(native_env.filepath.clone()),
source_text,
);
let decl_allocator = bumpalo::Bump::new();
let external_decl_provider: Option<Arc<dyn DeclProvider<'_> + '_>> = if env.decl_provider != 0 {
Some(Arc::new(ExternalDeclProvider::new(
env.decl_provider as *const c_void,
&decl_allocator,
)))
} else {
None
};
let decl_provider = SelfProvider::wrap_existing_provider(
external_decl_provider,
native_env.to_decl_parser_options(),
text.clone(),
&decl_allocator,
);
let mut output = Vec::new();
compile::from_text(
&mut output,
text,
&native_env,
decl_provider,
&mut Default::default(),
)
.map_err(|e| e.to_string())?;
Ok(output)
}
fn type_exists(holder: &DeclsHolder, symbol: &str) -> bool {
// TODO T123158488: fix case insensitive lookups
holder
.parsed_file
.decls
.types()
.any(|(sym, _)| *sym == symbol)
}
pub fn direct_decl_parse_and_serialize(
config: &compile_ffi::DeclParserConfig,
filename: &CxxString,
text: &[u8],
) -> compile_ffi::DeclsAndBlob {
match parse_decls(config, filename, text) {
Ok(decls) | Err(DeclsError(decls, _)) => compile_ffi::DeclsAndBlob {
serialized: decl_provider::serialize_decls(&decls.parsed_file.decls).unwrap(),
has_errors: decls.parsed_file.has_first_pass_parse_errors,
decls,
},
}
}
pub fn parse_decls(
config: &compile_ffi::DeclParserConfig,
filename: &CxxString,
text: &[u8],
) -> Result<Box<DeclsHolder>, DeclsError> {
let decl_opts = DeclParserOptions {
auto_namespace_map: (config.aliased_namespaces.iter())
.map(|e| (e.key.clone(), e.value.clone()))
.collect(),
disable_xhp_element_mangling: config.disable_xhp_element_mangling,
interpret_soft_types_as_like_types: config.interpret_soft_types_as_like_types,
allow_new_attribute_syntax: config.allow_new_attribute_syntax,
enable_xhp_class_modifier: config.enable_xhp_class_modifier,
php5_compat_mode: config.php5_compat_mode,
hhvm_compat_mode: config.hhvm_compat_mode,
keep_user_attributes: true,
..Default::default()
};
let path = PathBuf::from(OsStr::from_bytes(filename.as_bytes()));
let relpath = RelativePath::make(Prefix::Root, path);
let arena = bumpalo::Bump::new();
let alloc: &'static bumpalo::Bump =
unsafe { std::mem::transmute::<&'_ bumpalo::Bump, &'static bumpalo::Bump>(&arena) };
let parsed_file: ParsedFile<'static> =
direct_decl_parser::parse_decls_for_bytecode(&decl_opts, relpath, text, alloc);
let holder = Box::new(DeclsHolder {
parsed_file,
_arena: arena,
});
match holder.parsed_file.has_first_pass_parse_errors {
false => Ok(holder),
true => Err(DeclsError(
holder,
PathBuf::from(OsStr::from_bytes(filename.as_bytes())),
)),
}
}
#[derive(thiserror::Error, Debug)]
#[error("{}: File contained first-pass parse errors", .1.display())]
pub struct DeclsError(Box<DeclsHolder>, PathBuf);
fn verify_deserialization(result: &compile_ffi::DeclsAndBlob) -> bool {
let arena = bumpalo::Bump::new();
let decls = decl_provider::deserialize_decls(&arena, &result.serialized).unwrap();
decls == result.decls.parsed_file.decls
}
fn compile_unit_from_text(
env: &compile_ffi::NativeEnv,
source_text: &[u8],
) -> Result<Box<UnitWrapper>, String> {
let bump = bumpalo::Bump::new();
let alloc: &'static bumpalo::Bump =
unsafe { std::mem::transmute::<&'_ bumpalo::Bump, &'static bumpalo::Bump>(&bump) };
let native_env = env.to_compile_env().unwrap();
let text = SourceText::make(
std::sync::Arc::new(native_env.filepath.clone()),
source_text,
);
let decl_allocator = bumpalo::Bump::new();
let external_decl_provider: Option<Arc<dyn DeclProvider<'_> + '_>> = if env.decl_provider != 0 {
Some(Arc::new(ExternalDeclProvider::new(
env.decl_provider as *const c_void,
&decl_allocator,
)))
} else {
None
};
let decl_provider = SelfProvider::wrap_existing_provider(
external_decl_provider,
native_env.to_decl_parser_options(),
text.clone(),
&decl_allocator,
);
compile::unit_from_text(
alloc,
text,
&native_env,
decl_provider,
&mut Default::default(),
)
.map(|unit| Box::new(UnitWrapper(unit, bump)))
.map_err(|e| e.to_string())
}
fn decls_to_facts(holder: &DeclsHolder, sha1sum: &CxxString) -> compile_ffi::FileFacts {
let facts = facts::Facts::from_decls(&holder.parsed_file);
compile_ffi::FileFacts {
sha1hex: sha1sum.to_string_lossy().into_owned(),
..facts.into()
}
}
fn decls_to_facts_json(decls: &DeclsHolder, sha1sum: &CxxString) -> String {
let facts = facts::Facts::from_decls(&decls.parsed_file);
facts.to_json(false, &sha1sum.to_string_lossy())
} |
Rust | hhvm/hphp/hack/src/hackc/ffi_bridge/compiler_ffi_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 std::collections::BTreeMap;
use std::collections::BTreeSet;
use itertools::Itertools;
use super::*;
impl From<compile_ffi::TypeKind> for facts::TypeKind {
fn from(type_kind: compile_ffi::TypeKind) -> Self {
match type_kind {
compile_ffi::TypeKind::Class => Self::Class,
compile_ffi::TypeKind::Interface => Self::Interface,
compile_ffi::TypeKind::Enum => Self::Enum,
compile_ffi::TypeKind::Trait => Self::Trait,
compile_ffi::TypeKind::TypeAlias => Self::TypeAlias,
compile_ffi::TypeKind::Unknown => Self::Unknown,
compile_ffi::TypeKind::Mixed => Self::Mixed,
_ => panic!("impossible"),
}
}
}
impl From<facts::TypeKind> for compile_ffi::TypeKind {
fn from(typekind: facts::TypeKind) -> Self {
match typekind {
facts::TypeKind::Class => Self::Class,
facts::TypeKind::Interface => Self::Interface,
facts::TypeKind::Enum => Self::Enum,
facts::TypeKind::Trait => Self::Trait,
facts::TypeKind::TypeAlias => Self::TypeAlias,
facts::TypeKind::Unknown => Self::Unknown,
facts::TypeKind::Mixed => Self::Mixed,
}
}
}
impl IntoKeyValue<String, Vec<serde_json::Value>> for compile_ffi::Attribute {
fn into_key_value(self) -> (String, Vec<serde_json::Value>) {
let args = (self.args.into_iter())
.map(|s| serde_json::from_str(&s).unwrap())
.collect();
(self.name, args)
}
}
impl FromKeyValue<String, Vec<serde_json::Value>> for compile_ffi::Attribute {
fn from_key_value(name: String, args: Vec<serde_json::Value>) -> Self {
let args = (args.into_iter())
.map(|v| serde_json::to_string(&v).unwrap())
.collect();
Self { name, args }
}
}
impl IntoKeyValue<String, facts::MethodFacts> for compile_ffi::MethodDetails {
fn into_key_value(mut self) -> (String, facts::MethodFacts) {
let name = std::mem::take(&mut self.name);
(name, self.into())
}
}
impl FromKeyValue<String, facts::MethodFacts> for compile_ffi::MethodDetails {
fn from_key_value(name: String, methfacts: facts::MethodFacts) -> Self {
Self {
name,
..methfacts.into()
}
}
}
impl From<compile_ffi::MethodDetails> for facts::MethodFacts {
fn from(md: compile_ffi::MethodDetails) -> Self {
Self {
attributes: vec_to_map(md.attributes),
}
}
}
impl From<facts::MethodFacts> for compile_ffi::MethodDetails {
fn from(method_facts: facts::MethodFacts) -> Self {
Self {
name: String::default(),
attributes: map_to_vec(method_facts.attributes),
}
}
}
impl From<compile_ffi::TypeDetails> for facts::TypeFacts {
fn from(facts: compile_ffi::TypeDetails) -> Self {
Self {
base_types: vec_to_set(facts.base_types),
kind: facts.kind.into(),
attributes: vec_to_map(facts.attributes),
flags: facts.flags,
require_extends: vec_to_set(facts.require_extends),
require_implements: vec_to_set(facts.require_implements),
require_class: vec_to_set(facts.require_class),
methods: vec_to_map(facts.methods),
}
}
}
impl From<facts::TypeFacts> for compile_ffi::TypeDetails {
fn from(facts: facts::TypeFacts) -> Self {
Self {
name: String::default(),
base_types: set_to_vec(facts.base_types),
kind: facts.kind.into(),
attributes: map_to_vec(facts.attributes),
flags: facts.flags,
require_extends: set_to_vec(facts.require_extends),
require_implements: set_to_vec(facts.require_implements),
require_class: set_to_vec(facts.require_class),
methods: map_to_vec(facts.methods),
}
}
}
impl IntoKeyValue<String, facts::TypeFacts> for compile_ffi::TypeDetails {
fn into_key_value(mut self) -> (String, facts::TypeFacts) {
let name = std::mem::take(&mut self.name);
(name, self.into())
}
}
impl FromKeyValue<String, facts::TypeFacts> for compile_ffi::TypeDetails {
fn from_key_value(name: String, typefacts: facts::TypeFacts) -> Self {
Self {
name,
..typefacts.into()
}
}
}
impl From<compile_ffi::FileFacts> for facts::Facts {
fn from(facts: compile_ffi::FileFacts) -> Self {
Self {
types: vec_to_map(facts.types),
functions: facts.functions,
constants: facts.constants,
modules: facts
.modules
.into_iter()
.map(|x| (x.name, facts::ModuleFacts {}))
.collect(),
file_attributes: vec_to_map(facts.attributes),
}
}
}
impl From<facts::Facts> for compile_ffi::FileFacts {
fn from(facts: facts::Facts) -> Self {
Self {
types: map_to_vec(facts.types),
functions: facts.functions,
constants: facts.constants,
modules: facts
.modules
.into_keys()
.map(|name| compile_ffi::ModuleDetails { name })
.collect(),
attributes: map_to_vec(facts.file_attributes),
sha1hex: String::default(),
}
}
}
trait IntoKeyValue<K, V> {
fn into_key_value(self) -> (K, V);
}
trait FromKeyValue<K, V> {
fn from_key_value(k: K, v: V) -> Self;
}
fn vec_to_map<K, V, T>(v: Vec<T>) -> BTreeMap<K, V>
where
K: std::cmp::Ord,
T: IntoKeyValue<K, V>,
{
v.into_iter()
.map(|x| x.into_key_value())
.collect::<BTreeMap<K, V>>()
}
fn map_to_vec<K, V, T>(m: BTreeMap<K, V>) -> Vec<T>
where
T: FromKeyValue<K, V>,
{
m.into_iter()
.map(|(k, v)| T::from_key_value(k, v))
.collect_vec()
}
fn vec_to_set<T: std::cmp::Ord>(v: Vec<T>) -> BTreeSet<T> {
v.into_iter().collect()
}
fn set_to_vec<T>(s: BTreeSet<T>) -> Vec<T> {
s.into_iter().collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_method_facts_1() {
let (ffi_method_facts, rust_method_facts) = create_method_facts();
assert_eq!(
facts::MethodFacts::from(ffi_method_facts),
rust_method_facts
)
}
#[test]
fn test_method_facts_2() {
let (ffi_method_facts, mut rust_method_facts) = create_method_facts();
rust_method_facts.attributes.remove_entry("MyAttribute2");
assert_ne!(
compile_ffi::MethodDetails::from(rust_method_facts),
ffi_method_facts
)
}
#[test]
fn test_methods_1() {
let (ffi_methods, rust_methods) = create_methods();
assert_eq!(
map_to_vec::<String, facts::MethodFacts, compile_ffi::MethodDetails>(rust_methods),
ffi_methods
)
}
#[test]
fn test_methods_2() {
let (ffi_methods, mut rust_methods) = create_methods();
rust_methods.clear();
assert_ne!(vec_to_map(ffi_methods), rust_methods)
}
#[test]
fn test_type_facts() {
let (ffi_type_facts, rust_type_facts) = create_type_facts();
assert_eq!(
compile_ffi::TypeDetails::from(rust_type_facts),
ffi_type_facts
)
}
#[test]
fn test_type_facts_by_name() {
let (ffi_type_facts_by_name, rust_type_facts_by_name) = create_type_facts_by_name();
assert_eq!(
map_to_vec::<String, facts::TypeFacts, compile_ffi::TypeDetails>(
rust_type_facts_by_name
),
ffi_type_facts_by_name
)
}
#[test]
fn test_facts() {
let (ffi_type_facts_by_name, rust_type_facts_by_name) = create_type_facts_by_name();
let (ffi_module_facts_by_name, rust_module_facts_by_name) = create_module_facts_by_name();
let (ffi_attributes, rust_attributes) = create_attributes();
let ffi_facts = compile_ffi::FileFacts {
types: ffi_type_facts_by_name,
functions: vec!["f1".to_string(), "f2".to_string()],
constants: vec!["C".to_string()],
modules: ffi_module_facts_by_name,
attributes: ffi_attributes,
sha1hex: String::default(),
};
let rust_facts = facts::Facts {
types: rust_type_facts_by_name,
functions: vec!["f1".to_string(), "f2".to_string()],
constants: vec!["C".to_string()],
modules: rust_module_facts_by_name,
file_attributes: rust_attributes,
};
assert_eq!(facts::Facts::from(ffi_facts), rust_facts)
}
fn create_attributes() -> (Vec<compile_ffi::Attribute>, facts::Attributes) {
let ffi_attributes = vec![
compile_ffi::Attribute {
name: "MyAttribute1".to_string(),
args: vec!["\"arg1\"".into(), "\"arg2\"".into(), "\"arg3\"".into()],
},
compile_ffi::Attribute {
name: "MyAttribute2".to_string(),
args: vec![],
},
];
let mut rust_attributes = BTreeMap::new();
rust_attributes.insert(
"MyAttribute1".to_string(),
vec!["arg1".into(), "arg2".into(), "arg3".into()],
);
rust_attributes.insert("MyAttribute2".to_string(), vec![]);
(ffi_attributes, rust_attributes)
}
fn create_method_facts() -> (compile_ffi::MethodDetails, facts::MethodFacts) {
let (ffi_attributes, rust_attributes) = create_attributes();
let ffi_method_facts = compile_ffi::MethodDetails {
name: String::default(),
attributes: ffi_attributes,
};
let rust_method_facts = facts::MethodFacts {
attributes: rust_attributes,
};
(ffi_method_facts, rust_method_facts)
}
fn create_methods() -> (Vec<compile_ffi::MethodDetails>, facts::Methods) {
let (ffi_method_facts, rust_method_facts) = create_method_facts();
let ffi_methods = vec![compile_ffi::MethodDetails {
name: "m".to_string(),
..ffi_method_facts
}];
let mut rust_methods = BTreeMap::new();
rust_methods.insert("m".to_string(), rust_method_facts);
(ffi_methods, rust_methods)
}
fn create_type_facts() -> (compile_ffi::TypeDetails, facts::TypeFacts) {
let (ffi_attributes, rust_attributes) = create_attributes();
let (ffi_methods, rust_methods) = create_methods();
let base_types = vec!["int".to_string(), "string".to_string()];
let require_extends = vec!["A".to_string()];
let require_implements = vec!["B".to_string()];
let require_class = vec!["D".to_string()];
let rust_type_facts = facts::TypeFacts {
base_types: vec_to_set(base_types.clone()),
kind: facts::TypeKind::Class,
attributes: rust_attributes,
flags: 0,
require_extends: vec_to_set(require_extends.clone()),
require_implements: vec_to_set(require_implements.clone()),
require_class: vec_to_set(require_class.clone()),
methods: rust_methods,
};
let ffi_type_facts = compile_ffi::TypeDetails {
name: String::default(),
base_types,
kind: compile_ffi::TypeKind::Class,
attributes: ffi_attributes,
flags: 0,
require_extends,
require_implements,
require_class,
methods: ffi_methods,
};
(ffi_type_facts, rust_type_facts)
}
fn create_type_facts_by_name() -> (Vec<compile_ffi::TypeDetails>, facts::TypeFactsByName) {
let (ffi_type_facts, rust_type_facts) = create_type_facts();
let ffi_type_facts_by_name = vec![compile_ffi::TypeDetails {
name: "C".into(),
..ffi_type_facts
}];
let mut rust_type_facts_by_name = BTreeMap::new();
rust_type_facts_by_name.insert("C".to_string(), rust_type_facts);
(ffi_type_facts_by_name, rust_type_facts_by_name)
}
fn create_module_facts_by_name() -> (Vec<compile_ffi::ModuleDetails>, facts::ModuleFactsByName)
{
let ffi_module_facts_by_name = vec![compile_ffi::ModuleDetails {
name: "mfoo".to_string(),
}];
let mut rust_module_facts_by_name = BTreeMap::new();
rust_module_facts_by_name.insert("mfoo".to_string(), facts::ModuleFacts {});
(ffi_module_facts_by_name, rust_module_facts_by_name)
}
} |
C/C++ | hhvm/hphp/hack/src/hackc/ffi_bridge/decl_provider.h | // 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.
#pragma once
#include <string>
#include "hphp/hack/src/hackc/ffi_bridge/compiler_ffi.rs.h"
namespace HPHP {
namespace hackc {
// DeclProviders return pointers to data that must outlive the provider.
// This must be kept in sync with `enum ExternalDeclProviderResult` in
// 'hackc/decl_provider/external.rs' so they both are layout compatible.
struct ExternalDeclProviderResult {
enum class Tag {
Missing,
Decls,
RustVec,
CppString,
};
struct Decls_Body {
DeclsHolder const* _0;
};
struct RustVec_Body {
::rust::Vec<uint8_t> const* _0;
};
struct CppString_Body {
std::string const* _0;
};
Tag tag;
union {
Decls_Body decls;
RustVec_Body rust_vec;
CppString_Body cpp_string;
};
// Construct Missing
static ExternalDeclProviderResult missing() {
return ExternalDeclProviderResult{Tag::Missing, {}};
}
// Construct Decls from decls in a DeclsHolder
static ExternalDeclProviderResult from_decls(const DeclsHolder& holder) {
ExternalDeclProviderResult r;
r.tag = Tag::Decls;
r.decls._0 = &holder;
return r;
}
// Construct Bytes from DeclsAndBlob serialized bytes in a rust::Vec
static ExternalDeclProviderResult from_bytes(
const DeclsAndBlob& decl_result) {
ExternalDeclProviderResult r;
r.tag = Tag::RustVec;
r.rust_vec._0 = &decl_result.serialized;
return r;
}
// Construct Bytes from serialized bytes in a std::string
static ExternalDeclProviderResult from_string(const std::string& data) {
ExternalDeclProviderResult r;
r.tag = Tag::CppString;
r.cpp_string._0 = &data;
return r;
}
};
// Virtual base class for C++ DeclProviders. This is the C++ counterpart
// to trait DeclProvider in decl_provider.rs.
struct DeclProvider {
virtual ~DeclProvider() = default;
// Look up a type (class, type alias, etc) by name, and return all of the
// decls in the file that defines it. The resulting pointers must have at
// least this provider's lifetime.
virtual ExternalDeclProviderResult getType(
std::string_view symbol,
uint64_t depth) noexcept = 0;
// Look up a top level function by name, and return all of the decls in the
// file that defines it. The resulting pointers must have at least this
// provider's lifetime.
virtual ExternalDeclProviderResult getFunc(
std::string_view symbol) noexcept = 0;
// Look up a top level constant by name, and return all of the decls in the
// file that defines it. The resulting pointers must have at least this
// provider's lifetime.
virtual ExternalDeclProviderResult getConst(
std::string_view symbol) noexcept = 0;
// Look up a module by name, and return all of the decls in the file that
// defines it. The resulting pointers must have at least this provider's
// lifetime.
virtual ExternalDeclProviderResult getModule(
std::string_view symbol) noexcept = 0;
};
} // namespace hackc
} // namespace HPHP |
C++ | hhvm/hphp/hack/src/hackc/ffi_bridge/external_decl_provider.cpp | // 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.
#include "hphp/hack/src/hackc/ffi_bridge/decl_provider.h"
using namespace HPHP::hackc;
// These stubs perform C++ virtual method dispatch on behalf of
// hackc/decl_provider/external.rs
extern "C" {
ExternalDeclProviderResult provide_type(
const void* provider,
const char* symbol,
size_t symbol_len,
uint64_t depth) noexcept {
return ((DeclProvider*)provider)
->getType(std::string_view(symbol, symbol_len), depth);
}
ExternalDeclProviderResult provide_func(
const void* provider,
const char* symbol,
size_t symbol_len) noexcept {
return ((DeclProvider*)provider)
->getFunc(std::string_view(symbol, symbol_len));
}
ExternalDeclProviderResult provide_const(
const void* provider,
const char* symbol,
size_t symbol_len) noexcept {
return ((DeclProvider*)provider)
->getConst(std::string_view(symbol, symbol_len));
}
ExternalDeclProviderResult provide_module(
const void* provider,
const char* symbol,
size_t symbol_len) noexcept {
return ((DeclProvider*)provider)
->getModule(std::string_view(symbol, symbol_len));
}
} |
Rust | hhvm/hphp/hack/src/hackc/ffi_bridge/external_decl_provider.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::ffi::c_void;
use cxx::CxxString;
use decl_provider::ConstDecl;
use decl_provider::Error;
use decl_provider::FunDecl;
use decl_provider::ModuleDecl;
use decl_provider::Result;
use decl_provider::TypeDecl;
use direct_decl_parser::Decls;
use hash::HashMap;
use libc::c_char;
use crate::DeclProvider;
use crate::DeclsHolder;
/// Keep this in sync with struct ExternalDeclProviderResult in decl_provider.h
#[repr(C)]
pub enum ExternalDeclProviderResult {
Missing,
Decls(*const DeclsHolder),
RustVec(*const Vec<u8>),
CppString(*const CxxString),
}
// Bridge to C++ DeclProviders.
extern "C" {
// Safety: direct_decl_parser::Decls is a list of tuples, which cannot be repr(C)
// even if the contents are. But we never dereference Decls in C++.
#[allow(improper_ctypes)]
fn provide_type(
provider: *const c_void,
symbol: *const c_char,
symbol_len: usize,
depth: u64,
) -> ExternalDeclProviderResult;
#[allow(improper_ctypes)]
fn provide_func(
provider: *const c_void,
symbol: *const c_char,
symbol_len: usize,
) -> ExternalDeclProviderResult;
#[allow(improper_ctypes)]
fn provide_const(
provider: *const c_void,
symbol: *const c_char,
symbol_len: usize,
) -> ExternalDeclProviderResult;
#[allow(improper_ctypes)]
fn provide_module(
provider: *const c_void,
symbol: *const c_char,
symbol_len: usize,
) -> ExternalDeclProviderResult;
}
/// An ExternalDeclProvider implements the Rust DeclProvider trait, which
/// provides access to individual shallow_decl_defs::Decls, and the C++
/// DeclProvider interface, which provides the serialized decls for whole
/// source files, which are opaque to C++.
///
/// This class avoids repeatedly deserializing the same data by memoizing
/// deserialized decls, indexed by content hash of the serialized data.
pub struct ExternalDeclProvider<'a> {
pub provider: *const c_void,
pub arena: &'a bumpalo::Bump,
decls: RefCell<HashMap<Box<[u8]>, &'a Decls<'a>>>,
}
impl<'a> ExternalDeclProvider<'a> {
pub fn new(provider: *const c_void, arena: &'a bumpalo::Bump) -> Self {
Self {
provider,
arena,
decls: Default::default(),
}
}
}
impl<'a> std::fmt::Debug for ExternalDeclProvider<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("ExternalDeclProvider")
}
}
impl<'a> DeclProvider<'a> for ExternalDeclProvider<'a> {
fn type_decl(&self, symbol: &str, depth: u64) -> Result<TypeDecl<'a>> {
let result = unsafe {
// Invoke extern C/C++ provider implementation.
provide_type(self.provider, symbol.as_ptr() as _, symbol.len(), depth)
};
self.find_decl(result, |decls| decl_provider::find_type_decl(decls, symbol))
}
fn func_decl(&self, symbol: &str) -> Result<&'a FunDecl<'a>> {
let result = unsafe { provide_func(self.provider, symbol.as_ptr() as _, symbol.len()) };
self.find_decl(result, |decls| decl_provider::find_func_decl(decls, symbol))
}
fn const_decl(&self, symbol: &str) -> Result<&'a ConstDecl<'a>> {
let result = unsafe { provide_const(self.provider, symbol.as_ptr() as _, symbol.len()) };
self.find_decl(result, |decls| {
decl_provider::find_const_decl(decls, symbol)
})
}
fn module_decl(&self, symbol: &str) -> Result<&'a ModuleDecl<'a>> {
let result = unsafe { provide_module(self.provider, symbol.as_ptr() as _, symbol.len()) };
self.find_decl(result, |decls| {
decl_provider::find_module_decl(decls, symbol)
})
}
}
impl<'a> ExternalDeclProvider<'a> {
/// Search for the decl we asked for in the list of decls returned.
/// This is O(N) for now.
fn find_decl<T>(
&self,
result: ExternalDeclProviderResult,
mut find: impl FnMut(&Decls<'a>) -> Result<T>,
) -> Result<T> {
match result {
ExternalDeclProviderResult::Missing => Err(Error::NotFound),
ExternalDeclProviderResult::Decls(ptr) => {
let holder = unsafe { ptr.as_ref() }.unwrap();
find(&holder.parsed_file.decls)
}
ExternalDeclProviderResult::RustVec(p) => {
// turn raw pointer back into &Vec<u8>
let data = unsafe { p.as_ref().unwrap() };
find(self.deser(data)?)
}
ExternalDeclProviderResult::CppString(p) => {
// turn raw pointer back into &CxxString
let data = unsafe { p.as_ref().unwrap() };
find(self.deser(data.as_bytes())?)
}
}
}
/// Either deserialize the given data, or access a memoized copy of previously
/// deserialized decls from identical data. The memo key is a content hash
/// appended to data at serialization time.
fn deser(&self, data: &[u8]) -> Result<&'a Decls<'a>> {
use std::collections::hash_map::Entry::*;
let content_hash = decl_provider::decls_content_hash(data);
match self.decls.borrow_mut().entry(content_hash.into()) {
Occupied(e) => Ok(*e.get()),
Vacant(e) => {
let decls = decl_provider::deserialize_decls(self.arena, data)?;
Ok(*e.insert(self.arena.alloc(decls)))
}
}
}
} |
Rust | hhvm/hphp/hack/src/hackc/hhbc/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 serde::Serialize;
use crate::typed_value::TypedValue;
use crate::AdataId;
#[derive(Debug, Eq, PartialEq, Serialize)]
#[repr(C)]
pub struct Adata<'arena> {
pub id: AdataId<'arena>,
pub value: TypedValue<'arena>,
}
impl Adata<'_> {
pub const VEC_PREFIX: &'static str = "v";
pub const DICT_PREFIX: &'static str = "D";
pub const KEYSET_PREFIX: &'static str = "k";
} |
Rust | hhvm/hphp/hack/src/hackc/hhbc/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 ffi::Slice;
use ffi::Str;
use naming_special_names::user_attributes as ua;
use naming_special_names_rust as naming_special_names;
use serde::Serialize;
use crate::typed_value::TypedValue;
/// Attributes with a name from [naming_special_names::user_attributes] and
/// a series of arguments. Emitter code can match on an attribute as follows:
/// ```
/// use naming_special_names::user_attributes as ua;
/// fn is_memoized(attr: &Attribute) -> bool {
/// attr.is(ua::memoized)
/// }
/// fn has_dynamically_callable(attrs: &Vec<Attribute>) {
/// attrs.iter().any(|a| a.name == ua::DYNAMICALLY_CALLABLE)
/// }
/// ```
#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize)]
#[repr(C)]
pub struct Attribute<'arena> {
pub name: Str<'arena>,
pub arguments: Slice<'arena, TypedValue<'arena>>,
}
impl<'arena> Attribute<'arena> {
pub fn is<F: Fn(&str) -> bool>(&self, f: F) -> bool {
f(self.name.unsafe_as_str())
}
}
fn is<'arena>(s: &str, attr: &Attribute<'arena>) -> bool {
attr.is(|x| x == s)
}
fn has<'arena, F>(attrs: &[Attribute<'arena>], f: F) -> bool
where
F: Fn(&Attribute<'arena>) -> bool,
{
attrs.iter().any(f)
}
pub fn is_no_injection<'arena>(attrs: impl AsRef<[Attribute<'arena>]>) -> bool {
is_native_arg(native_arg::NO_INJECTION, attrs)
}
pub fn is_native_opcode_impl<'arena>(attrs: impl AsRef<[Attribute<'arena>]>) -> bool {
is_native_arg(native_arg::OP_CODE_IMPL, attrs)
}
fn is_native_arg<'arena>(s: &str, attrs: impl AsRef<[Attribute<'arena>]>) -> bool {
attrs.as_ref().iter().any(|attr| {
attr.is(ua::is_native)
&& attr.arguments.as_ref().iter().any(|tv| match *tv {
TypedValue::String(s0) => s0.unsafe_as_str() == s,
_ => false,
})
})
}
fn is_memoize_with<'arena>(attrs: impl AsRef<[Attribute<'arena>]>, arg: &str) -> bool {
attrs.as_ref().iter().any(|attr| {
ua::is_memoized(attr.name.unsafe_as_str())
&& attr.arguments.as_ref().iter().any(|tv| match *tv {
TypedValue::String(s0) => s0.unsafe_as_str() == arg,
_ => false,
})
})
}
pub fn is_keyed_by_ic_memoize<'arena>(attrs: impl AsRef<[Attribute<'arena>]>) -> bool {
is_memoize_with(attrs, "KeyedByIC")
}
pub fn is_make_ic_inaccessible_memoize<'arena>(attrs: impl AsRef<[Attribute<'arena>]>) -> bool {
is_memoize_with(attrs, "MakeICInaccessible")
}
pub fn is_soft_make_ic_inaccessible_memoize<'arena>(
attrs: impl AsRef<[Attribute<'arena>]>,
) -> bool {
is_memoize_with(attrs, "SoftMakeICInaccessible")
}
fn is_foldable<'arena>(attr: &Attribute<'arena>) -> bool {
is(ua::IS_FOLDABLE, attr)
}
fn is_dynamically_constructible<'arena>(attr: &Attribute<'arena>) -> bool {
is(ua::DYNAMICALLY_CONSTRUCTIBLE, attr)
}
fn is_sealed<'arena>(attr: &Attribute<'arena>) -> bool {
is(ua::SEALED, attr)
}
fn is_const<'arena>(attr: &Attribute<'arena>) -> bool {
is(ua::CONST, attr)
}
fn is_meth_caller<'arena>(attr: &Attribute<'arena>) -> bool {
is("__MethCaller", attr)
}
fn is_provenance_skip_frame<'arena>(attr: &Attribute<'arena>) -> bool {
is(ua::PROVENANCE_SKIP_FRAME, attr)
}
fn is_dynamically_callable<'arena>(attr: &Attribute<'arena>) -> bool {
is(ua::DYNAMICALLY_CALLABLE, attr)
}
fn is_native<'arena>(attr: &Attribute<'arena>) -> bool {
is(ua::NATIVE, attr)
}
fn is_enum_class<'arena>(attr: &Attribute<'arena>) -> bool {
is(ua::ENUM_CLASS, attr)
}
fn is_memoize<'arena>(attr: &Attribute<'arena>) -> bool {
ua::is_memoized(attr.name.unsafe_as_str())
}
fn is_memoize_lsb<'arena>(attr: &Attribute<'arena>) -> bool {
attr.name.unsafe_as_str() == ua::MEMOIZE_LSB
}
pub fn has_native<'arena>(attrs: &[Attribute<'arena>]) -> bool {
has(attrs, is_native)
}
pub fn has_enum_class<'arena>(attrs: &[Attribute<'arena>]) -> bool {
has(attrs, is_enum_class)
}
pub fn has_dynamically_constructible<'arena>(attrs: &[Attribute<'arena>]) -> bool {
has(attrs, is_dynamically_constructible)
}
pub fn has_foldable<'arena>(attrs: &[Attribute<'arena>]) -> bool {
has(attrs, is_foldable)
}
pub fn has_sealed<'arena>(attrs: &[Attribute<'arena>]) -> bool {
has(attrs, is_sealed)
}
pub fn has_const<'arena>(attrs: &[Attribute<'arena>]) -> bool {
has(attrs, is_const)
}
pub fn has_meth_caller<'arena>(attrs: &[Attribute<'arena>]) -> bool {
has(attrs, is_meth_caller)
}
pub fn has_provenance_skip_frame<'arena>(attrs: &[Attribute<'arena>]) -> bool {
has(attrs, is_provenance_skip_frame)
}
pub fn has_dynamically_callable<'arena>(attrs: &[Attribute<'arena>]) -> bool {
has(attrs, is_dynamically_callable)
}
pub fn has_is_memoize<'arena>(attrs: &[Attribute<'arena>]) -> bool {
has(attrs, is_memoize)
}
pub fn has_is_memoize_lsb<'arena>(attrs: &[Attribute<'arena>]) -> bool {
has(attrs, is_memoize_lsb)
}
pub fn deprecation_info<'a, 'arena>(
mut iter: impl Iterator<Item = &'a Attribute<'arena>>,
) -> Option<&'a [TypedValue<'arena>]> {
iter.find_map(|attr| {
if attr.name.unsafe_as_str() == ua::DEPRECATED {
Some(attr.arguments.as_ref())
} else {
None
}
})
}
pub mod native_arg {
pub const OP_CODE_IMPL: &str = "OpCodeImpl";
pub const NO_INJECTION: &str = "NoInjection";
}
#[cfg(test)]
mod tests {
use naming_special_names::user_attributes as ua;
use super::*;
#[test]
fn example_is_memoized_vs_eq_memoize() {
let attr = Attribute {
name: ua::MEMOIZE_LSB.into(),
arguments: ffi::Slice::empty(),
};
assert!(attr.is(ua::is_memoized));
assert!(!attr.is(|s| s == ua::MEMOIZE));
assert!(attr.is(|s| s == ua::MEMOIZE_LSB));
}
#[test]
fn example_has_dynamically_callable() {
let mk_attr = |name: &'static str| Attribute {
name: name.into(),
arguments: ffi::Slice::empty(),
};
let attrs = vec![mk_attr(ua::CONST), mk_attr(ua::DYNAMICALLY_CALLABLE)];
let has_result = attrs
.iter()
.any(|a| a.name.unsafe_as_str() == ua::DYNAMICALLY_CALLABLE);
assert!(has_result);
}
} |
Rust | hhvm/hphp/hack/src/hackc/hhbc/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 ffi::Maybe;
use ffi::Slice;
use ffi::Str;
use serde::Serialize;
use crate::Instruct;
use crate::Param;
use crate::TypeInfo;
use crate::UpperBound;
#[derive(Debug, Serialize)]
#[repr(C)]
pub struct Body<'arena> {
/// Must have been compacted with InstrSeq::compact_iter().
pub body_instrs: Slice<'arena, Instruct<'arena>>,
pub decl_vars: Slice<'arena, Str<'arena>>,
pub num_iters: usize,
pub is_memoize_wrapper: bool,
pub is_memoize_wrapper_lsb: bool,
pub upper_bounds: Slice<'arena, UpperBound<'arena>>,
pub shadowed_tparams: Slice<'arena, Str<'arena>>,
pub params: Slice<'arena, Param<'arena>>,
pub return_type_info: Maybe<TypeInfo<'arena>>,
pub doc_comment: Maybe<Str<'arena>>,
/// The statically computed stack depth for this Body. This can be computed
/// using the hhbc::compute_stack_depth() function.
pub stack_depth: usize,
} |
Rust | hhvm/hphp/hack/src/hackc/hhbc/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 ffi::Maybe;
use ffi::Slice;
use ffi::Str;
use hhvm_types_ffi::ffi::Attr;
use serde::Serialize;
use crate::Attribute;
use crate::ClassName;
use crate::Constant;
use crate::CtxConstant;
use crate::Method;
use crate::Property;
use crate::Span;
use crate::TypeConstant;
use crate::TypeInfo;
use crate::UpperBound;
#[derive(Copy, Clone, Debug, Eq, PartialEq, Serialize)]
#[repr(C)]
pub enum TraitReqKind {
MustExtend,
MustImplement,
MustBeClass,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[repr(C)]
pub struct Requirement<'arena> {
pub name: ClassName<'arena>,
pub kind: TraitReqKind,
}
#[derive(Debug, Serialize)]
#[repr(C)]
pub struct Class<'arena> {
pub attributes: Slice<'arena, Attribute<'arena>>,
pub base: Maybe<ClassName<'arena>>,
pub implements: Slice<'arena, ClassName<'arena>>,
pub enum_includes: Slice<'arena, ClassName<'arena>>,
pub name: ClassName<'arena>,
pub span: Span,
pub uses: Slice<'arena, ClassName<'arena>>,
pub enum_type: Maybe<TypeInfo<'arena>>,
pub methods: Slice<'arena, Method<'arena>>,
pub properties: Slice<'arena, Property<'arena>>,
pub constants: Slice<'arena, Constant<'arena>>,
pub type_constants: Slice<'arena, TypeConstant<'arena>>,
pub ctx_constants: Slice<'arena, CtxConstant<'arena>>, // TODO(SF, 2021-0811): CtxConstant is part of Steve's Coeffect work
pub requirements: Slice<'arena, Requirement<'arena>>,
pub upper_bounds: Slice<'arena, UpperBound<'arena>>,
pub doc_comment: Maybe<Str<'arena>>,
pub flags: Attr,
}
impl<'arena> Class<'arena> {
pub fn is_closure(&self) -> bool {
self.methods.as_ref().iter().any(|x| x.is_closure_body())
}
} |
Rust | hhvm/hphp/hack/src/hackc/hhbc/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 bumpalo::Bump;
use ffi::Slice;
use ffi::Str;
use hhbc_string_utils::strip_ns;
use naming_special_names_rust::coeffects as c;
use naming_special_names_rust::coeffects::Ctx;
use naming_special_names_rust::{self as sn};
use oxidized::aast as a;
use oxidized::aast_defs::Hint;
use oxidized::aast_defs::Hint_;
use oxidized::ast_defs::Id;
use serde::Serialize;
#[derive(Debug, Eq, PartialEq, Serialize)]
#[repr(C)]
pub struct CtxConstant<'arena> {
pub name: Str<'arena>,
pub recognized: Slice<'arena, Str<'arena>>,
pub unrecognized: Slice<'arena, Str<'arena>>,
pub is_abstract: bool,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize)]
#[repr(C)]
pub struct CcParam<'arena> {
pub index: u32,
pub ctx_name: Str<'arena>,
}
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize)]
#[repr(C)]
pub struct CcThis<'arena> {
pub types: Slice<'arena, Str<'arena>>,
}
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize)]
#[repr(C)]
pub struct CcReified<'arena> {
pub is_class: bool,
pub index: u32,
pub types: Slice<'arena, Str<'arena>>,
}
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize)]
#[repr(C)]
pub struct Coeffects<'arena> {
pub static_coeffects: Slice<'arena, Ctx>,
pub unenforced_static_coeffects: Slice<'arena, Str<'arena>>,
pub fun_param: Slice<'arena, u32>,
pub cc_param: Slice<'arena, CcParam<'arena>>,
pub cc_this: Slice<'arena, CcThis<'arena>>,
pub cc_reified: Slice<'arena, CcReified<'arena>>,
pub closure_parent_scope: bool,
pub generator_this: bool,
pub caller: bool,
}
impl<'arena> Coeffects<'arena> {
pub fn new(
static_coeffects: Slice<'arena, Ctx>,
unenforced_static_coeffects: Slice<'arena, Str<'arena>>,
fun_param: Slice<'arena, u32>,
cc_param: Slice<'arena, CcParam<'arena>>,
cc_this: Slice<'arena, CcThis<'arena>>,
cc_reified: Slice<'arena, CcReified<'arena>>,
closure_parent_scope: bool,
generator_this: bool,
caller: bool,
) -> Self {
Self {
static_coeffects,
unenforced_static_coeffects,
fun_param,
cc_param,
cc_this,
cc_reified,
closure_parent_scope,
generator_this,
caller,
}
}
pub fn from_static_coeffects(alloc: &'arena Bump, scs: Vec<Ctx>) -> Coeffects<'arena> {
Coeffects {
static_coeffects: Slice::from_vec(alloc, scs),
..Default::default()
}
}
fn from_type_static(hint: &Hint) -> Option<Ctx> {
let Hint(_, h) = hint;
match &**h {
Hint_::Happly(Id(_, id), _) => match strip_ns(id.as_str()) {
c::DEFAULTS => Some(Ctx::Defaults),
c::RX_LOCAL => Some(Ctx::RxLocal),
c::RX_SHALLOW => Some(Ctx::RxShallow),
c::RX => Some(Ctx::Rx),
c::WRITE_THIS_PROPS => Some(Ctx::WriteThisProps),
c::WRITE_PROPS => Some(Ctx::WriteProps),
c::ZONED_WITH => Some(Ctx::ZonedWith),
c::ZONED_LOCAL => Some(Ctx::ZonedLocal),
c::ZONED_SHALLOW => Some(Ctx::ZonedShallow),
c::ZONED => Some(Ctx::Zoned),
c::LEAK_SAFE_LOCAL => Some(Ctx::LeakSafeLocal),
c::LEAK_SAFE_SHALLOW => Some(Ctx::LeakSafeShallow),
c::LEAK_SAFE => Some(Ctx::LeakSafe),
c::GLOBALS => Some(Ctx::Globals),
c::READ_GLOBALS => Some(Ctx::ReadGlobals),
_ => None,
},
_ => None,
}
}
pub fn local_to_shallow(coeffects: &[Ctx]) -> Vec<Ctx> {
coeffects
.iter()
.map(|c| match c {
Ctx::RxLocal => Ctx::RxShallow,
Ctx::ZonedLocal => Ctx::ZonedShallow,
Ctx::LeakSafeLocal => Ctx::LeakSafeShallow,
_ => *c,
})
.collect()
}
pub fn from_ctx_constant(hint: &Hint) -> (Vec<Ctx>, Vec<String>) {
let mut static_coeffects = vec![];
let mut unenforced_static_coeffects = vec![];
let Hint(_, h) = hint;
match &**h {
Hint_::Hintersection(hl) if hl.is_empty() => static_coeffects.push(Ctx::Pure),
Hint_::Hintersection(hl) => {
for h in hl {
let Hint(_, h_inner) = h;
match &**h_inner {
Hint_::Happly(Id(_, id), _) => {
if let Some(c) = Coeffects::from_type_static(h) {
static_coeffects.push(c)
} else {
unenforced_static_coeffects.push(strip_ns(id.as_str()).to_string());
}
}
_ => {}
}
}
}
_ => {}
}
(static_coeffects, unenforced_static_coeffects)
}
pub fn from_ast<Ex, En>(
alloc: &'arena bumpalo::Bump,
ctxs_opt: Option<&a::Contexts>,
params: impl AsRef<[a::FunParam<Ex, En>]>,
fun_tparams: impl AsRef<[a::Tparam<Ex, En>]>,
cls_tparams: impl AsRef<[a::Tparam<Ex, En>]>,
) -> Self {
let mut static_coeffects = vec![];
let mut unenforced_static_coeffects: Vec<Str<'arena>> = vec![];
let mut fun_param = vec![];
let mut cc_param: Vec<CcParam<'arena>> = vec![];
let mut cc_this: Vec<CcThis<'arena>> = vec![];
let mut cc_reified: Vec<CcReified<'arena>> = vec![];
let get_arg_pos = |name: &String| -> u32 {
if let Some(pos) = params.as_ref().iter().position(|x| x.name == *name) {
pos as u32
} else {
panic!("Invalid context");
}
};
let is_reified_tparam = |name: &str, is_class: bool| -> Option<usize> {
let tparam = if is_class {
cls_tparams.as_ref()
} else {
fun_tparams.as_ref()
};
tparam
.iter()
.position(|tp| tp.reified == a::ReifyKind::Reified && tp.name.1 == name)
};
// From coeffect syntax
if let Some(ctxs) = ctxs_opt {
if ctxs.1.is_empty() {
static_coeffects.push(Ctx::Pure);
}
for ctx in &ctxs.1 {
let Hint(_, h) = ctx;
match &**h {
Hint_::Happly(Id(_, id), _) => {
if let Some(c) = Coeffects::from_type_static(ctx) {
static_coeffects.push(c)
} else {
unenforced_static_coeffects
.push(alloc.alloc_str(strip_ns(id.as_str())).into());
}
}
Hint_::HfunContext(name) => fun_param.push(get_arg_pos(name)),
Hint_::Haccess(Hint(_, hint), sids) => match &**hint {
Hint_::Happly(Id(_, id), _) if !sids.is_empty() => {
if strip_ns(id.as_str()) == sn::typehints::THIS {
cc_this.push(CcThis {
types: Slice::from_vec(
alloc,
sids.iter()
.map(|Id(_, id)| alloc.alloc_str(id).into())
.collect(),
),
});
} else if let Some(idx) = is_reified_tparam(id.as_str(), false) {
cc_reified.push(CcReified {
is_class: false,
index: idx as u32,
types: Slice::from_vec(
alloc,
sids.iter()
.map(|Id(_, id)| alloc.alloc_str(id).into())
.collect(),
),
});
} else if let Some(idx) = is_reified_tparam(id.as_str(), true) {
cc_reified.push(CcReified {
is_class: true,
index: idx as u32,
types: Slice::from_vec(
alloc,
sids.iter()
.map(|Id(_, id)| alloc.alloc_str(id).into())
.collect(),
),
});
}
}
Hint_::Hvar(name) if sids.len() == 1 => {
let index = get_arg_pos(name);
let Id(_, sid_name) = &sids[0];
let ctx_name = alloc.alloc_str(sid_name).into();
cc_param.push(CcParam { index, ctx_name });
}
_ => {}
},
_ => {}
}
}
}
// If there are no static coeffects but there are coeffect rules, then
// the static coeffects are pure
if static_coeffects.is_empty()
&& (!fun_param.is_empty()
|| !cc_param.is_empty()
|| !cc_this.is_empty()
|| !cc_reified.is_empty())
{
static_coeffects.push(Ctx::Pure);
}
Self {
static_coeffects: Slice::from_vec(alloc, static_coeffects),
unenforced_static_coeffects: Slice::from_vec(alloc, unenforced_static_coeffects),
fun_param: Slice::from_vec(alloc, fun_param),
cc_param: Slice::from_vec(alloc, cc_param),
cc_this: Slice::from_vec(alloc, cc_this),
cc_reified: Slice::from_vec(alloc, cc_reified),
..Coeffects::default()
}
}
pub fn pure(alloc: &'arena bumpalo::Bump) -> Self {
Self {
static_coeffects: Slice::from_vec(alloc, vec![Ctx::Pure]),
..Coeffects::default()
}
}
pub fn with_backdoor(&self, alloc: &'arena bumpalo::Bump) -> Self {
Self {
unenforced_static_coeffects: Slice::from_vec(alloc, vec![Str::from(c::BACKDOOR)]),
..self.clone()
}
}
pub fn with_backdoor_globals_leak_safe(&self, alloc: &'arena bumpalo::Bump) -> Self {
Self {
unenforced_static_coeffects: Slice::from_vec(
alloc,
vec![Str::from(c::BACKDOOR_GLOBALS_LEAK_SAFE)],
),
..self.clone()
}
}
pub fn inherit_to_child_closure(&self, alloc: &'arena bumpalo::Bump) -> Self {
let static_coeffects = Coeffects::local_to_shallow(self.get_static_coeffects());
if self.has_coeffect_rules() {
Self {
static_coeffects: Slice::from_vec(alloc, static_coeffects),
closure_parent_scope: true,
..Coeffects::default()
}
} else {
Self {
static_coeffects: Slice::from_vec(alloc, static_coeffects),
..self.clone()
}
}
}
pub fn with_gen_coeffect(&self) -> Self {
Self {
generator_this: true,
..self.clone()
}
}
pub fn with_caller(&self, alloc: &'arena bumpalo::Bump) -> Self {
Self {
static_coeffects: Slice::from_vec(alloc, vec![Ctx::Pure]),
unenforced_static_coeffects: Slice::empty(),
caller: true,
..self.clone()
}
}
/// Does not erase any static_coeffects or unenforced_static_coeffects
pub fn untouch_with_caller(&self) -> Self {
Self {
caller: true,
..self.clone()
}
}
pub fn get_static_coeffects(&self) -> &[Ctx] {
self.static_coeffects.as_ref()
}
pub fn get_unenforced_static_coeffects(&self) -> &[Str<'arena>] {
self.unenforced_static_coeffects.as_ref()
}
pub fn get_fun_param(&self) -> &[u32] {
self.fun_param.as_ref()
}
pub fn get_cc_param(&self) -> &[CcParam<'arena>] {
self.cc_param.as_ref()
}
pub fn get_cc_this(&self) -> &[CcThis<'arena>] {
self.cc_this.as_ref()
}
pub fn get_cc_reified(&self) -> &[CcReified<'arena>] {
self.cc_reified.as_ref()
}
pub fn generator_this(&self) -> bool {
self.generator_this
}
pub fn caller(&self) -> bool {
self.caller
}
fn has_coeffect_rules(&self) -> bool {
!self.fun_param.is_empty()
|| !self.cc_param.is_empty()
|| !self.cc_this.is_empty()
|| !self.cc_reified.is_empty()
|| self.closure_parent_scope
|| self.generator_this
|| self.caller
}
pub fn has_coeffects_local(&self) -> bool {
self.has_coeffect_rules() && !self.generator_this()
}
pub fn is_closure_parent_scope(&self) -> bool {
self.closure_parent_scope
}
pub fn is_86caller(&self) -> bool {
!self.has_coeffect_rules()
&& self.static_coeffects.is_empty()
&& self.unenforced_static_coeffects.len() == 1
&& self.unenforced_static_coeffects.as_ref()[0]
== hhbc_string_utils::coeffects::CALLER.into()
}
} |
Rust | hhvm/hphp/hack/src/hackc/hhbc/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.
// Interestingly, HHAS does not represent the declared types of constants,
// unlike formal parameters and return types. We might consider fixing this.
// Also interestingly, abstract constants are not emitted at all.
use ffi::Maybe;
use hhvm_types_ffi::ffi::Attr;
use serde::Serialize;
use crate::typed_value::TypedValue;
use crate::ConstName;
#[derive(Debug, Serialize)]
#[repr(C)]
pub struct Constant<'arena> {
pub name: ConstName<'arena>,
pub value: Maybe<TypedValue<'arena>>,
pub attrs: Attr,
} |
Rust | hhvm/hphp/hack/src/hackc/hhbc/decl_vars.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::Just;
use ffi::Maybe;
use hash::IndexSet;
use naming_special_names_rust::emitter_special_functions;
use naming_special_names_rust::special_idents;
use oxidized::aast;
use oxidized::aast::Binop;
use oxidized::aast_visitor::visit;
use oxidized::aast_visitor::AstParams;
use oxidized::aast_visitor::Node;
use oxidized::aast_visitor::Visitor;
use oxidized::ast::*;
use oxidized::ast_defs;
use crate::Label;
use crate::Param;
type SSet = std::collections::BTreeSet<String>;
struct DeclvarVisitorContext<'a> {
explicit_use_set_opt: Option<&'a SSet>,
capture_debugger_vars: bool,
}
struct DeclvarVisitor<'a> {
// set of locals used inside the functions
locals: IndexSet<String>,
context: DeclvarVisitorContext<'a>,
}
impl<'a> DeclvarVisitor<'a> {
fn new(explicit_use_set_opt: Option<&'a SSet>, capture_debugger_vars: bool) -> Self {
Self {
locals: Default::default(),
context: DeclvarVisitorContext {
explicit_use_set_opt,
capture_debugger_vars,
},
}
}
fn add_local<S: Into<String> + AsRef<str>>(&mut self, name: S) {
let name_ref = name.as_ref();
if name_ref == special_idents::DOLLAR_DOLLAR
|| special_idents::is_tmp_var(name_ref)
|| name_ref == special_idents::THIS
{
} else {
self.locals.insert(name.into());
}
}
fn on_class_get(&mut self, cid: &ClassId, cge: &ClassGetExpr) -> Result<(), String> {
use aast::ClassId_;
match &cid.2 {
ClassId_::CIparent | ClassId_::CIself | ClassId_::CIstatic | ClassId_::CI(_) => {
Err("Expects CIexpr as class_id on aast where expr was on ast".into())
}
ClassId_::CIexpr(e) => {
self.visit_expr(&mut (), e)?;
match cge {
ClassGetExpr::CGstring(pstr) => {
// TODO(thomasjiang): For this to match correctly, we need to adjust
// ast_to_nast because it does not make a distinction between ID and Lvar,
// which is needed here
self.add_local(&pstr.1);
Ok(())
}
ClassGetExpr::CGexpr(e2) => self.visit_expr(&mut (), e2),
}
}
}
}
}
impl<'ast, 'a> Visitor<'ast> for DeclvarVisitor<'a> {
type Params = AstParams<(), String>;
fn object(&mut self) -> &mut dyn Visitor<'ast, Params = Self::Params> {
self
}
fn visit_stmt_(&mut self, env: &mut (), s: &Stmt_) -> Result<(), String> {
match s {
Stmt_::Try(x) => {
let (body, catch_list, finally) = (&x.0, &x.1, &x.2);
visit(self, env, body)?;
for Catch(_, id, catch_body) in catch_list {
self.add_local(id.name());
visit(self, env, catch_body)?;
}
visit(self, env, finally)
}
Stmt_::DeclareLocal(box (id, _, expr)) => {
self.add_local(id.name());
visit(self, env, expr)
}
_ => s.recurse(env, self),
}
}
fn visit_expr_(&mut self, env: &mut (), e: &Expr_) -> Result<(), String> {
use aast::Expr_;
match e {
Expr_::Binop(box Binop { bop, lhs, rhs }) => {
match (bop, &rhs.2) {
(Bop::Eq(_), Expr_::Await(_)) | (Bop::Eq(_), Expr_::Yield(_)) => {
// Visit e2 before e1. The ordering of declvars in async
// expressions matters to HHVM. See D5674623.
self.visit_expr(env, rhs)?;
self.visit_expr(env, lhs)
}
_ => e.recurse(env, self.object()),
}
}
Expr_::Lvar(x) => {
self.add_local(x.name());
Ok(())
}
// For an Lfun, we don't want to recurse, because it's a separate scope.
Expr_::Lfun(box lfun) => {
if self.context.capture_debugger_vars {
visit(self, env, &lfun.0.body)?;
}
Ok(())
}
Expr_::Efun(box efun) => {
// at this point AST is already rewritten so use lists on EFun nodes
// contain list of captured variables. However if use list was initially absent
// it is not correct to traverse such nodes to collect locals because it will impact
// the order of locals in generated .declvars section:
// // .declvars $a, $c, $b
// $a = () => { $b = 1 };
// $c = 1;
// $b = 2;
// // .declvars $a, $b, $c
// $a = function () use ($b) => { $b = 1 };
// $c = 1;
// $b = 2;
//
// 'explicit_use_set' is used to in order to avoid synthesized use list
let use_list = &efun.use_;
let fn_name = &efun.closure_class_name.clone().unwrap_or_default();
let has_use_list = self
.context
.explicit_use_set_opt
.map_or(false, |s| s.contains(fn_name));
if self.context.capture_debugger_vars || has_use_list {
use_list.iter().for_each(|id| self.add_local(id.1.name()));
}
Ok(())
}
Expr_::Call(box aast::CallExpr {
func,
args,
unpacked_arg,
..
}) => {
match &func.2 {
Expr_::Id(box ast_defs::Id(_, call_name)) => {
if call_name == emitter_special_functions::SET_FRAME_METADATA {
self.add_local("$86metadata");
}
if call_name == emitter_special_functions::SET_PRODUCT_ATTRIBUTION_ID
|| call_name
== emitter_special_functions::SET_PRODUCT_ATTRIBUTION_ID_DEFERRED
{
self.add_local("$86productAttributionData");
}
}
Expr_::ClassGet(box (id, prop, pom)) if *pom == PropOrMethod::IsMethod => {
self.on_class_get(id, prop)?
}
_ => self.visit_expr(env, func)?,
}
// Calling convention doesn't matter here: we're just trying to figure out what
// variables are declared in this scope.
args.recurse(env, self.object())?;
if let Some(arg) = unpacked_arg {
arg.recurse(env, self.object())?;
}
Ok(())
}
e => e.recurse(env, self.object()),
}
}
fn visit_class_(&mut self, _: &mut (), _: &Class_) -> Result<(), String> {
Ok(())
}
fn visit_fun_(&mut self, _: &mut (), _: &Fun_) -> Result<(), String> {
Ok(())
}
}
fn uls_from_ast<P, F1, F2>(
params: &[P],
get_param_name: F1,
get_param_default_value: F2,
explicit_use_set_opt: Option<&SSet>,
body: &impl Node<AstParams<(), String>>,
capture_debugger_vars: bool,
) -> Result<impl Iterator<Item = String>, String>
where
F1: Fn(&P) -> &str,
F2: Fn(&P) -> Maybe<&Expr>,
{
let mut visitor = DeclvarVisitor::new(explicit_use_set_opt, capture_debugger_vars);
for p in params {
if let Just(e) = get_param_default_value(p) {
visitor.visit_expr(&mut (), e)?;
}
}
visit(&mut visitor, &mut (), body)?;
for param in params {
visitor.locals.shift_remove(get_param_name(param));
}
Ok(visitor.locals.into_iter())
}
pub fn from_ast<'arena>(
params: &[(Param<'arena>, Option<(Label, Expr)>)],
body: &[Stmt],
explicit_use_set: &SSet,
) -> Result<Vec<String>, String> {
let decl_vars = uls_from_ast(
params,
|(param, _)| param.name.unsafe_as_str(),
|(_, default_value)| Maybe::from(default_value.as_ref().map(|x| &x.1)),
Some(explicit_use_set),
&body,
false,
)?;
Ok(decl_vars.collect())
}
pub fn vars_from_ast(
params: &[FunParam],
body: &impl Node<AstParams<(), String>>,
capture_debugger_vars: bool,
) -> Result<IndexSet<String>, String> {
let decl_vars = uls_from_ast(
params,
|p| &p.name, // get_param_name
|p| Maybe::from(p.expr.as_ref()), // get_param_default_value
None, // explicit_use_set_opt
body,
capture_debugger_vars,
)?;
Ok(decl_vars.collect())
} |
Rust | hhvm/hphp/hack/src/hackc/hhbc/dump_opcodes.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::Write;
use std::path::PathBuf;
use std::process::Command;
use std::process::Stdio;
use anyhow::Result;
use clap::Parser;
use hhbc_gen::OpcodeData;
use quote::quote;
#[derive(Parser)]
struct Opts {
#[clap(short = 'o', long = "out")]
output: Option<PathBuf>,
#[clap(long)]
no_format: bool,
}
fn main() -> Result<()> {
let opts = Opts::parse();
let opcode_data: Vec<OpcodeData> = hhbc_gen::opcode_data().to_vec();
let input = quote!(
#[emit_opcodes_macro::emit_opcodes]
#[derive(Clone, Debug, Targets)]
#[repr(C)]
pub enum Opcode<'arena> {
// This is filled in by the emit_opcodes macro. It can be printed using the
// "//hphp/hack/src/hackc/hhbc:dump-opcodes" binary.
}
);
let opcodes = emit_opcodes::emit_opcodes(input.clone(), &opcode_data)?;
let targets = emit_opcodes::emit_impl_targets(input, &opcode_data)?;
let output = format!("{}\n\n{}", opcodes, targets);
if opts.no_format {
if let Some(out) = opts.output.as_ref() {
std::fs::write(out, output)?;
} else {
println!("{}", output);
}
return Ok(());
}
let mut child = Command::new("rustfmt");
child.args(["--emit", "stdout"]);
child.stdin(Stdio::piped());
if let Some(out) = opts.output.as_ref() {
use std::os::unix::io::FromRawFd;
use std::os::unix::io::IntoRawFd;
let file = File::create(out).expect("couldn't create output file");
child.stdout(unsafe { Stdio::from_raw_fd(file.into_raw_fd()) });
}
let mut child = child.spawn()?;
child.stdin.as_mut().unwrap().write_all(output.as_bytes())?;
child.wait()?;
Ok(())
} |
Rust | hhvm/hphp/hack/src/hackc/hhbc/emit_opcodes.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 hhbc_gen::ImmType;
use hhbc_gen::Inputs;
use hhbc_gen::InstrFlags;
use hhbc_gen::OpcodeData;
use hhbc_gen::Outputs;
use proc_macro2::Ident;
use proc_macro2::Punct;
use proc_macro2::Spacing;
use proc_macro2::Span;
use proc_macro2::TokenStream;
use quote::quote;
use quote::ToTokens;
use syn::punctuated::Punctuated;
use syn::token;
use syn::ItemEnum;
use syn::Lifetime;
use syn::Result;
use syn::Variant;
pub fn emit_opcodes(input: TokenStream, opcodes: &[OpcodeData]) -> Result<TokenStream> {
let mut enum_def = syn::parse2::<ItemEnum>(input)?;
let generics = &enum_def.generics;
let lifetime = &generics.lifetimes().next().unwrap().lifetime;
for opcode in opcodes {
let name = Ident::new(opcode.name, Span::call_site());
let mut body = Vec::new();
body.extend(name.to_token_stream());
if !opcode.immediates.is_empty() {
let is_struct = opcode.flags.contains(InstrFlags::AS_STRUCT);
let mut imms = Vec::new();
for (idx, (name, ty)) in opcode.immediates.iter().enumerate() {
if idx != 0 {
imms.push(Punct::new(',', Spacing::Alone).into());
}
let ty = convert_imm_type(ty, lifetime);
if is_struct {
let name = Ident::new(name, Span::call_site());
imms.extend(quote!( #name: #ty ));
} else {
imms.extend(ty);
}
}
if is_struct {
body.extend(quote!( { #(#imms)* } ));
} else {
body.extend(quote!( ( #(#imms)* ) ));
}
}
let variant = syn::parse2::<Variant>(quote!(#(#body)*))?;
enum_def.variants.push(variant);
}
// Silliness to match rustfmt...
if !enum_def.variants.trailing_punct() {
enum_def.variants.push_punct(Default::default());
}
let (impl_generics, impl_types, impl_where) = enum_def.generics.split_for_impl();
let enum_impl = {
let enum_name = &enum_def.ident;
let mut variant_names_matches = Vec::new();
let mut variant_index_matches = Vec::new();
let mut num_inputs_matches = Vec::new();
let mut num_outputs_matches = Vec::new();
for (idx, opcode) in opcodes.iter().enumerate() {
let name = Ident::new(opcode.name, Span::call_site());
let name_str = &opcode.name;
let is_struct = opcode.flags.contains(InstrFlags::AS_STRUCT);
let ignore_args = if opcode.immediates.is_empty() {
Default::default()
} else if is_struct {
quote!({ .. })
} else {
quote!((..))
};
variant_names_matches.push(quote!(#enum_name :: #name #ignore_args => #name_str,));
variant_index_matches.push(quote!(#enum_name :: #name #ignore_args => #idx,));
let num_inputs = match opcode.inputs {
Inputs::NOV => quote!(#enum_name :: #name #ignore_args => 0),
Inputs::Fixed(ref inputs) => {
let n = inputs.len();
quote!(#enum_name :: #name #ignore_args => #n)
}
Inputs::FCall { inp, .. } => {
quote!(#enum_name :: #name (fca, ..) => NUM_ACT_REC_CELLS + fca.num_inputs() + fca.num_inouts() + #inp as usize)
}
Inputs::CMany | Inputs::CUMany => {
quote!(#enum_name :: #name (n, ..) => *n as usize)
}
Inputs::SMany => {
quote!(#enum_name :: #name (n, ..) => n.len())
}
Inputs::MFinal => {
quote!(#enum_name :: #name (n, ..) => *n as usize)
}
Inputs::CMFinal(m) => {
quote!(#enum_name :: #name (n, ..) => *n as usize + #m as usize)
}
};
num_inputs_matches.push(num_inputs);
let num_outputs = match opcode.outputs {
Outputs::NOV => quote!(#enum_name :: #name #ignore_args => 0),
Outputs::Fixed(ref outputs) => {
let n = outputs.len();
quote!(#enum_name :: #name #ignore_args => #n)
}
Outputs::FCall => quote!(#enum_name :: #name #ignore_args => 0),
};
num_outputs_matches.push(num_outputs);
}
quote!(
impl #impl_generics #enum_name #impl_types #impl_where {
pub fn variant_name(&self) -> &'static str {
match self {
#(#variant_names_matches)*
}
}
pub fn variant_index(&self) -> usize {
match self {
#(#variant_index_matches)*
}
}
pub fn num_inputs(&self) -> usize {
match self {
#(#num_inputs_matches),*,
}
}
pub fn num_outputs(&self) -> usize {
match self {
#(#num_outputs_matches),*,
}
}
}
)
};
Ok(quote!(
#enum_def
#enum_impl
))
}
pub fn emit_impl_targets(input: TokenStream, opcodes: &[OpcodeData]) -> Result<TokenStream> {
// impl Targets for Instruct<'_> {
// pub fn targets(&self) -> &[Label] {
// match self {
// ..
// }
// }
// }
//
let item_enum = syn::parse2::<ItemEnum>(input)?;
let name = &item_enum.ident;
let (impl_generics, impl_types, impl_where) = item_enum.generics.split_for_impl();
let mut with_targets_ref: Vec<TokenStream> = Vec::new();
let mut without_targets: Punctuated<TokenStream, token::Or> = Punctuated::new();
for opcode in opcodes {
let variant_name = Ident::new(opcode.name, Span::call_site());
let variant_name = quote!(#name::#variant_name);
let is_struct = opcode.flags.contains(InstrFlags::AS_STRUCT);
fn is_label_type(imm_ty: &ImmType) -> bool {
match imm_ty {
ImmType::BA | ImmType::BA2 | ImmType::FCA | ImmType::BLA => true,
ImmType::ARR(subty) => is_label_type(subty),
ImmType::AA
| ImmType::DA
| ImmType::DUMMY
| ImmType::I64A
| ImmType::IA
| ImmType::ILA
| ImmType::ITA
| ImmType::IVA
| ImmType::KA
| ImmType::LA
| ImmType::LAR
| ImmType::NA
| ImmType::NLA
| ImmType::OA(_)
| ImmType::RATA
| ImmType::SA
| ImmType::SLA
| ImmType::VSA
| ImmType::OAL(_) => false,
}
}
fn ident_with_ref_or_mut(id: &str, is_ref: bool) -> Ident {
let ext = if is_ref { "_ref" } else { "_mut" };
Ident::new(&format!("{}{}", id, ext), Span::call_site())
}
fn ident_with_mut(id: &str, is_ref: bool) -> Ident {
if is_ref {
Ident::new(id, Span::call_site())
} else {
Ident::new(&format!("{}_mut", id), Span::call_site())
}
}
fn compute_label(
opcode_name: &str,
imm_name: &Ident,
imm_ty: &ImmType,
is_ref: bool,
) -> TokenStream {
match imm_ty {
ImmType::BA => {
let call = ident_with_ref_or_mut("from", is_ref);
quote!(std::slice::#call(#imm_name))
}
ImmType::BA2 => quote!(#imm_name),
ImmType::BLA => {
let call = ident_with_ref_or_mut("as", is_ref);
quote!(#imm_name.#call())
}
ImmType::FCA => {
let call = ident_with_mut("targets", is_ref);
quote!(#imm_name.#call())
}
_ => todo!("unhandled {:?} for {:?}", imm_ty, opcode_name),
}
}
if let Some(idx) = opcode
.immediates
.iter()
.position(|(_, imm_ty)| is_label_type(imm_ty))
{
// Label opcodes.
let mut match_parts: Punctuated<TokenStream, token::Comma> = Punctuated::new();
let mut result = None;
for (i, (imm_name, imm_ty)) in opcode.immediates.iter().enumerate() {
let imm_name = Ident::new(imm_name, Span::call_site());
if i == idx {
match_parts.push(imm_name.to_token_stream());
let result_ref = compute_label(opcode.name, &imm_name, imm_ty, true);
let old = result.replace(result_ref);
if old.is_some() {
panic!("Unable to build targets for opcode with multiple labels");
}
} else if is_struct {
match_parts.push(quote!(#imm_name: _));
} else {
match_parts.push(quote!(_));
}
}
let result_ref = result.unwrap();
if is_struct {
with_targets_ref.push(quote!(#variant_name { #match_parts } => #result_ref, ));
} else {
with_targets_ref.push(quote!(#variant_name ( #match_parts ) => #result_ref, ));
}
} else {
// Non-label opcodes.
if opcode.immediates.is_empty() {
without_targets.push(quote!(#variant_name));
} else if is_struct {
without_targets.push(quote!(#variant_name { .. }));
} else {
without_targets.push(quote!(#variant_name ( .. )));
}
}
}
Ok(
quote!(impl #impl_generics Targets for #name #impl_types #impl_where {
fn targets(&self) -> &[Label] {
match self {
#(#with_targets_ref)*
#without_targets => &[],
}
}
}),
)
}
fn convert_imm_type(imm: &ImmType, lifetime: &Lifetime) -> TokenStream {
match imm {
ImmType::AA => quote!(AdataId<#lifetime>),
ImmType::ARR(sub) => {
let sub_ty = convert_imm_type(sub, lifetime);
quote!(Slice<#lifetime, #sub_ty>)
}
ImmType::BA => quote!(Label),
ImmType::BA2 => quote!([Label; 2]),
ImmType::BLA => quote!(Slice<#lifetime, Label>),
ImmType::DA => quote!(FloatBits),
ImmType::DUMMY => quote!(Dummy),
ImmType::FCA => quote!(FCallArgs<#lifetime>),
ImmType::I64A => quote!(i64),
ImmType::IA => quote!(IterId),
ImmType::ILA => quote!(Local),
ImmType::ITA => quote!(IterArgs),
ImmType::IVA => quote!(u32),
ImmType::KA => quote!(MemberKey<#lifetime>),
ImmType::LA => quote!(Local),
ImmType::LAR => quote!(LocalRange),
ImmType::NA => panic!("NA is not expected"),
ImmType::NLA => quote!(Local),
ImmType::OA(ty) => {
let ty = Ident::new(ty, Span::call_site());
quote!(#ty)
}
ImmType::OAL(ty) => {
let ty = Ident::new(ty, Span::call_site());
quote!(#ty<#lifetime>)
}
ImmType::RATA => quote!(RepoAuthType<#lifetime>),
ImmType::SA => quote!(Str<#lifetime>),
ImmType::SLA => quote!(Slice<#lifetime, SwitchLabel>),
ImmType::VSA => quote!(Slice<#lifetime, Str<#lifetime>>),
}
}
/// Build construction helpers for InstrSeq. Each line in the input is either
/// (a) a list of opcodes and the keyword 'default':
/// `A | B => default`
/// which means to generate helpers for those opcodes with default snake-case names
/// (b) a single opcode and a single name:
/// `A => my_a`
/// which means to generate a helper for that opcode with the given name.
/// (c) a list of opcodes and an empty block:
/// `A | B => {}`
/// which means to skip generating helpers for those opcodes.
///
/// The parameters to the function are based on the expected immediates for the
/// opcode.
///
/// define_instr_seq_helpers! {
/// MyA | MyB => default
/// MyC => myc
/// MyD => {}
/// }
///
/// Expands into:
///
/// pub fn my_a<'a>() -> InstrSeq<'a> {
/// instr(Instruct::Opcode(Opcode::MyA))
/// }
///
/// pub fn my_b<'a>(arg1: i64) -> InstrSeq<'a> {
/// instr(Instruct::Opcode(Opcode::MyB(arg1)))
/// }
///
/// pub fn myc<'a>(arg1: i64, arg2: i64) -> InstrSeq<'a> {
/// instr(Instruct::Opcode(Opcode::MyC(arg1, arg2)))
/// }
///
pub fn define_instr_seq_helpers(input: TokenStream, opcodes: &[OpcodeData]) -> Result<TokenStream> {
// Foo => bar
// Foo | Bar | Baz => default
// Foo | Bar | Baz => {}
use std::collections::HashMap;
use convert_case::Case;
use convert_case::Casing;
use proc_macro2::TokenTree;
use syn::parse::ParseStream;
use syn::parse::Parser;
use syn::Error;
use syn::Token;
#[derive(Debug)]
struct Helper<'a> {
opcode_name: Ident,
fn_name: Ident,
opcode_data: &'a OpcodeData,
}
let mut opcodes: HashMap<&str, &OpcodeData> =
opcodes.iter().map(|data| (data.name, data)).collect();
// Foo => bar
// Foo | Bar | Baz => default
// Foo | Bar | Baz => {}
let macro_input = |input: ParseStream<'_>| -> Result<Vec<Helper<'_>>> {
let mut helpers: Vec<Helper<'_>> = Vec::new();
let mut same_as_default: Vec<Ident> = Vec::new();
while !input.is_empty() {
let mut opcode_names: Vec<(Ident, &OpcodeData)> = {
let names =
syn::punctuated::Punctuated::<Ident, Token![|]>::parse_separated_nonempty(
input,
)?;
let mut opcode_names: Vec<(Ident, &OpcodeData)> = Vec::new();
for name in names {
if let Some(opcode_data) = opcodes.remove(name.to_string().as_str()) {
opcode_names.push((name, opcode_data));
} else {
return Err(Error::new(
name.span(),
format!("Unknown opcode '{}'", name),
));
}
}
opcode_names
};
let _arrow: Token![=>] = input.parse()?;
let tt: TokenTree = input.parse()?;
match tt {
TokenTree::Ident(fn_name) => {
// Foo => bar
let (opcode_name, opcode_data) = opcode_names.pop().unwrap();
if let Some((unexpected, _)) = opcode_names.pop() {
return Err(Error::new(
unexpected.span(),
format!(
"Only a single Opcode is allowed when a function name ('{}') is provided",
fn_name
),
));
}
// If the 'alias' name is what we would have picked as a default
// then complain.
let default_name = opcode_data.name.to_case(Case::Snake);
if fn_name == default_name {
same_as_default.push(opcode_name.clone());
}
helpers.push(Helper {
opcode_name,
fn_name,
opcode_data,
});
if input.is_empty() {
break;
}
input.parse::<Token![,]>()?;
}
TokenTree::Group(grp) => {
// Foo | Bar | Baz => {}
let stream = grp.stream();
let mut iter = stream.into_iter();
if let Some(tt) = iter.next() {
return Err(Error::new(tt.span(), "Block must be empty"));
}
// do nothing
// allow an unnecessary comma
if input.peek(Token![,]) {
input.parse::<Token![,]>()?;
}
}
TokenTree::Punct(_) | TokenTree::Literal(_) => {
return Err(Error::new(tt.span(), "identifier or '{}' expected"));
}
}
}
if let Some(opcode_name) = same_as_default.pop() {
let span = opcode_name.span();
let msg = if same_as_default.is_empty() {
format!(
"Opcode '{}' was given an alias which is the same name it would have gotten with default - please omit it instead.",
opcode_name,
)
} else {
format!(
"Opcodes {} were given aliases which are the same name they would have gotten with default - please omit it instead.",
std::iter::once(opcode_name)
.chain(same_as_default.into_iter())
.map(|s| format!("'{}'", s))
.collect::<Vec<_>>()
.join(", ")
)
};
return Err(Error::new(span, msg));
}
for opcode_data in opcodes.values() {
let opcode_name = Ident::new(opcode_data.name, Span::call_site());
let fn_name = Ident::new(&opcode_data.name.to_case(Case::Snake), opcode_name.span());
helpers.push(Helper {
opcode_name,
fn_name,
opcode_data,
});
}
helpers.sort_by(|a, b| a.fn_name.cmp(&b.fn_name));
Ok(helpers)
};
let input: Vec<Helper<'_>> = macro_input.parse2(input)?;
let vis = quote!(pub);
let enum_name = quote!(Opcode);
let lifetime: Lifetime = syn::parse2::<Lifetime>(quote!('a))?;
let mut res: Vec<TokenStream> = Vec::new();
for Helper {
opcode_name,
fn_name,
opcode_data,
} in input
{
let params: Vec<TokenStream> = opcode_data
.immediates
.iter()
.map(|(imm_name, imm_ty)| {
let imm_name = Ident::new(imm_name, Span::call_site());
let ty = convert_imm_type(imm_ty, &lifetime);
quote!(#imm_name: #ty)
})
.collect();
let args = {
let args: Vec<TokenStream> = opcode_data
.immediates
.iter()
.map(|(imm_name, _)| {
let imm_name = Ident::new(imm_name, Span::call_site());
quote!(#imm_name)
})
.collect();
if args.is_empty() {
quote!()
} else {
quote!(( #(#args),* ))
}
};
let func = quote!(
#vis fn #fn_name<#lifetime>(#(#params),*) -> InstrSeq<#lifetime> {
instr(Instruct::#enum_name(#enum_name::#opcode_name #args))
}
);
res.push(func);
}
Ok(quote!(#(#res)*))
}
#[cfg(test)]
mod tests {
use hhbc_gen as _;
use macro_test_util::assert_pat_eq;
use quote::quote;
use super::*;
#[test]
fn test_basic() {
assert_pat_eq(
emit_opcodes(
quote!(
enum MyOps<'a> {}
),
&opcode_test_data::test_opcodes(),
),
quote!(
enum MyOps<'a> {
TestZeroImm,
TestOneImm(Str<'a>),
TestTwoImm(Str<'a>, Str<'a>),
TestThreeImm(Str<'a>, Str<'a>, Str<'a>),
// --------------------
TestAsStruct { str1: Str<'a>, str2: Str<'a> },
// --------------------
TestAA(AdataId<'a>),
TestARR(Slice<'a, Str<'a>>),
TestBA(Label),
TestBA2([Label; 2]),
TestBLA(Slice<'a, Label>),
TestDA(FloatBits),
TestFCA(FCallArgs<'a>),
TestI64A(i64),
TestIA(IterId),
TestILA(Local),
TestITA(IterArgs),
TestIVA(u32),
TestKA(MemberKey<'a>),
TestLA(Local),
TestLAR(LocalRange),
TestNLA(Local),
TestOA(OaSubType),
TestOAL(OaSubType<'a>),
TestRATA(RepoAuthType<'a>),
TestSA(Str<'a>),
TestSLA(Slice<'a, SwitchLabel>),
TestVSA(Slice<'a, Str<'a>>),
}
impl<'a> MyOps<'a> {
pub fn variant_name(&self) -> &'static str {
match self {
MyOps::TestZeroImm => "TestZeroImm",
MyOps::TestOneImm(..) => "TestOneImm",
MyOps::TestTwoImm(..) => "TestTwoImm",
MyOps::TestThreeImm(..) => "TestThreeImm",
MyOps::TestAsStruct { .. } => "TestAsStruct",
MyOps::TestAA(..) => "TestAA",
MyOps::TestARR(..) => "TestARR",
MyOps::TestBA(..) => "TestBA",
MyOps::TestBA2(..) => "TestBA2",
MyOps::TestBLA(..) => "TestBLA",
MyOps::TestDA(..) => "TestDA",
MyOps::TestFCA(..) => "TestFCA",
MyOps::TestI64A(..) => "TestI64A",
MyOps::TestIA(..) => "TestIA",
MyOps::TestILA(..) => "TestILA",
MyOps::TestITA(..) => "TestITA",
MyOps::TestIVA(..) => "TestIVA",
MyOps::TestKA(..) => "TestKA",
MyOps::TestLA(..) => "TestLA",
MyOps::TestLAR(..) => "TestLAR",
MyOps::TestNLA(..) => "TestNLA",
MyOps::TestOA(..) => "TestOA",
MyOps::TestOAL(..) => "TestOAL",
MyOps::TestRATA(..) => "TestRATA",
MyOps::TestSA(..) => "TestSA",
MyOps::TestSLA(..) => "TestSLA",
MyOps::TestVSA(..) => "TestVSA",
}
}
pub fn variant_index(&self) -> usize {
match self {
MyOps::TestZeroImm => 0usize,
MyOps::TestOneImm(..) => 1usize,
MyOps::TestTwoImm(..) => 2usize,
MyOps::TestThreeImm(..) => 3usize,
MyOps::TestAsStruct { .. } => 4usize,
MyOps::TestAA(..) => 5usize,
MyOps::TestARR(..) => 6usize,
MyOps::TestBA(..) => 7usize,
MyOps::TestBA2(..) => 8usize,
MyOps::TestBLA(..) => 9usize,
MyOps::TestDA(..) => 10usize,
MyOps::TestFCA(..) => 11usize,
MyOps::TestI64A(..) => 12usize,
MyOps::TestIA(..) => 13usize,
MyOps::TestILA(..) => 14usize,
MyOps::TestITA(..) => 15usize,
MyOps::TestIVA(..) => 16usize,
MyOps::TestKA(..) => 17usize,
MyOps::TestLA(..) => 18usize,
MyOps::TestLAR(..) => 19usize,
MyOps::TestNLA(..) => 20usize,
MyOps::TestOA(..) => 21usize,
MyOps::TestOAL(..) => 22usize,
MyOps::TestRATA(..) => 23usize,
MyOps::TestSA(..) => 24usize,
MyOps::TestSLA(..) => 25usize,
MyOps::TestVSA(..) => 26usize,
}
}
pub fn num_inputs(&self) -> usize {
match self {
MyOps::TestZeroImm => 0,
MyOps::TestOneImm(..) => 0,
MyOps::TestTwoImm(..) => 0,
MyOps::TestThreeImm(..) => 0,
MyOps::TestAsStruct { .. } => 0,
MyOps::TestAA(..) => 0,
MyOps::TestARR(..) => 0,
MyOps::TestBA(..) => 0,
MyOps::TestBA2(..) => 0,
MyOps::TestBLA(..) => 0,
MyOps::TestDA(..) => 0,
MyOps::TestFCA(..) => 0,
MyOps::TestI64A(..) => 0,
MyOps::TestIA(..) => 0,
MyOps::TestILA(..) => 0,
MyOps::TestITA(..) => 0,
MyOps::TestIVA(..) => 0,
MyOps::TestKA(..) => 0,
MyOps::TestLA(..) => 0,
MyOps::TestLAR(..) => 0,
MyOps::TestNLA(..) => 0,
MyOps::TestOA(..) => 0,
MyOps::TestOAL(..) => 0,
MyOps::TestRATA(..) => 0,
MyOps::TestSA(..) => 0,
MyOps::TestSLA(..) => 0,
MyOps::TestVSA(..) => 0,
}
}
pub fn num_outputs(&self) -> usize {
match self {
MyOps::TestZeroImm => 0,
MyOps::TestOneImm(..) => 0,
MyOps::TestTwoImm(..) => 0,
MyOps::TestThreeImm(..) => 0,
MyOps::TestAsStruct { .. } => 0,
MyOps::TestAA(..) => 0,
MyOps::TestARR(..) => 0,
MyOps::TestBA(..) => 0,
MyOps::TestBA2(..) => 0,
MyOps::TestBLA(..) => 0,
MyOps::TestDA(..) => 0,
MyOps::TestFCA(..) => 0,
MyOps::TestI64A(..) => 0,
MyOps::TestIA(..) => 0,
MyOps::TestILA(..) => 0,
MyOps::TestITA(..) => 0,
MyOps::TestIVA(..) => 0,
MyOps::TestKA(..) => 0,
MyOps::TestLA(..) => 0,
MyOps::TestLAR(..) => 0,
MyOps::TestNLA(..) => 0,
MyOps::TestOA(..) => 0,
MyOps::TestOAL(..) => 0,
MyOps::TestRATA(..) => 0,
MyOps::TestSA(..) => 0,
MyOps::TestSLA(..) => 0,
MyOps::TestVSA(..) => 0,
}
}
}
),
);
}
#[test]
fn test_instr_seq() {
assert_pat_eq(
define_instr_seq_helpers(
quote!(
TestOneImm => test_oneimm,
TestTwoImm => test_twoimm,
TestBLA | TestFCA | TestARR | TestDA | TestBA2 | TestBA |
TestIA | TestITA | TestNLA | TestOAL | TestLA | TestRATA |
TestSLA | TestILA | TestIVA | TestKA | TestI64A | TestSA |
TestOA | TestVSA | TestThreeImm => {}
),
&opcode_test_data::test_opcodes(),
),
quote!(
pub fn test_aa<'a>(arr1: AdataId<'a>) -> InstrSeq<'a> {
instr(Instruct::Opcode(Opcode::TestAA(arr1)))
}
pub fn test_as_struct<'a>(str1: Str<'a>, str2: Str<'a>) -> InstrSeq<'a> {
instr(Instruct::Opcode(Opcode::TestAsStruct(str1, str2)))
}
pub fn test_lar<'a>(locrange: LocalRange) -> InstrSeq<'a> {
instr(Instruct::Opcode(Opcode::TestLAR(locrange)))
}
pub fn test_oneimm<'a>(str1: Str<'a>) -> InstrSeq<'a> {
instr(Instruct::Opcode(Opcode::TestOneImm(str1)))
}
pub fn test_twoimm<'a>(str1: Str<'a>, str2: Str<'a>) -> InstrSeq<'a> {
instr(Instruct::Opcode(Opcode::TestTwoImm(str1, str2)))
}
pub fn test_zero_imm<'a>() -> InstrSeq<'a> {
instr(Instruct::Opcode(Opcode::TestZeroImm))
}
),
);
}
} |
Rust | hhvm/hphp/hack/src/hackc/hhbc/emit_opcodes_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 the opcodes enum. Given input that looks like this:
///
/// ```
/// #[macros::emit_opcodes]
/// enum MyCrazyOpcodes<'lifetime> { }
/// ```
///
/// The result will look something like this:
///
/// ```
/// enum MyCrazyOpcodes<'lifetime> {
/// Jmp(Label),
/// Nop,
/// PopL(Local<'lifetime>),
/// }
/// ```
///
/// If the 'Targets' derive is used then the Targets trait will be implemented
/// as well.
///
/// See emit_opcodes::tests::test_basic() for a more detailed example output.
///
#[proc_macro_attribute]
pub fn emit_opcodes(
_attrs: proc_macro::TokenStream,
input: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
match emit_opcodes::emit_opcodes(input.into(), hhbc_gen::opcode_data()) {
Ok(res) => res.into(),
Err(err) => err.into_compile_error().into(),
}
}
#[proc_macro_derive(Targets)]
pub fn emit_targets(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
match emit_opcodes::emit_impl_targets(input.into(), hhbc_gen::opcode_data()) {
Ok(res) => res.into(),
Err(err) => err.into_compile_error().into(),
}
}
#[proc_macro]
pub fn define_instr_seq_helpers(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
match emit_opcodes::define_instr_seq_helpers(input.into(), hhbc_gen::opcode_data()) {
Ok(res) => res.into(),
Err(err) => err.into_compile_error().into(),
}
} |
Rust | hhvm/hphp/hack/src/hackc/hhbc/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 bitflags::bitflags;
use ffi::Slice;
use hhvm_types_ffi::ffi::Attr;
use serde::Serialize;
use crate::Attribute;
use crate::Body;
use crate::Coeffects;
use crate::FunctionName;
use crate::Param;
use crate::Span;
#[derive(Debug, Serialize)]
#[repr(C)]
pub struct Function<'arena> {
pub attributes: Slice<'arena, Attribute<'arena>>,
pub name: FunctionName<'arena>,
pub body: Body<'arena>,
pub span: Span,
pub coeffects: Coeffects<'arena>,
pub flags: FunctionFlags,
pub attrs: Attr,
}
bitflags! {
#[derive(Default, Serialize)]
#[repr(C)]
pub struct FunctionFlags: u8 {
const ASYNC = 1 << 0;
const GENERATOR = 1 << 1;
const PAIR_GENERATOR = 1 << 2;
const MEMOIZE_IMPL = 1 << 3;
}
}
impl<'arena> Function<'arena> {
pub fn is_async(&self) -> bool {
self.flags.contains(FunctionFlags::ASYNC)
}
pub fn is_generator(&self) -> bool {
self.flags.contains(FunctionFlags::GENERATOR)
}
pub fn is_pair_generator(&self) -> bool {
self.flags.contains(FunctionFlags::PAIR_GENERATOR)
}
pub fn is_memoize_impl(&self) -> bool {
self.flags.contains(FunctionFlags::MEMOIZE_IMPL)
}
pub fn with_body<F, T>(&mut self, body: Body<'arena>, f: F) -> T
where
F: FnOnce() -> T,
{
let old_body = std::mem::replace(&mut self.body, body);
let ret = f();
self.body = old_body;
ret
}
pub fn params(&self) -> &[Param<'arena>] {
self.body.params.as_ref()
}
} |
Rust | hhvm/hphp/hack/src/hackc/hhbc/id.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.
// Note: `$type<'arena>` is a newtype over a `&'arena str`
// (`class::Type<'arena>`, `function::Type<'arena>`, ...). We intend that these
// types borrow strings stored in `InstrSeq` arenas.
use bstr::BStr;
use bstr::ByteSlice;
use ffi::Str;
use serde::Serialize;
macro_rules! impl_id {
($type: ident) => {
impl<'arena> $type<'arena> {
pub const fn new(s: ffi::Str<'arena>) -> Self {
Self(s)
}
pub fn empty() -> Self {
Self(ffi::Slice::new(b""))
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn unsafe_into_string(self) -> std::string::String {
self.0.unsafe_as_str().into()
}
pub fn unsafe_as_str(&self) -> &'arena str {
self.0.unsafe_as_str()
}
pub fn as_ffi_str(&self) -> ffi::Str<'arena> {
self.0
}
pub fn as_bstr(&self) -> &'arena BStr {
self.0.as_bstr()
}
pub fn as_bytes(&self) -> &'arena [u8] {
self.0.as_bstr().as_bytes()
}
pub fn from_bytes(alloc: &'arena bumpalo::Bump, s: &[u8]) -> $type<'arena> {
$type(Str::new_slice(alloc, s))
}
pub fn from_raw_string(alloc: &'arena bumpalo::Bump, s: &str) -> $type<'arena> {
$type(Str::new_str(alloc, s))
}
}
impl write_bytes::DisplayBytes for $type<'_> {
fn fmt(&self, f: &mut write_bytes::BytesFormatter<'_>) -> std::io::Result<()> {
self.0.fmt(f)
}
}
impl<'arena> std::fmt::Debug for $type<'arena> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}({})", module_path!(), self.unsafe_as_str())
}
}
};
}
macro_rules! impl_add_suffix {
($type: ident) => {
impl<'arena> $type<'arena> {
fn from_raw_string_with_suffix(
alloc: &'arena bumpalo::Bump,
s: &str,
suffix: &str,
) -> $type<'arena> {
let mut r = bumpalo::collections::String::<'arena>::with_capacity_in(
s.len() + suffix.len(),
alloc,
);
r.push_str(s);
r.push_str(suffix);
$type(ffi::Slice::new(r.into_bump_str().as_bytes()))
}
pub fn add_suffix(alloc: &'arena bumpalo::Bump, id: &Self, suffix: &str) -> Self {
$type::from_raw_string_with_suffix(alloc, id.0.unsafe_as_str(), suffix)
}
}
};
}
/// Conventionally this is "A_" followed by an integer
#[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, Serialize)]
#[repr(C)]
pub struct AdataId<'arena>(Str<'arena>);
impl_id!(AdataId);
#[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, Serialize)]
#[repr(C)]
pub struct ClassName<'arena>(Str<'arena>);
impl_id!(ClassName);
impl<'arena> ClassName<'arena> {
pub fn from_ast_name_and_mangle(
alloc: &'arena bumpalo::Bump,
s: impl std::convert::Into<std::string::String>,
) -> Self {
ClassName(Str::new_str(
alloc,
hhbc_string_utils::strip_global_ns(&hhbc_string_utils::mangle(s.into())),
))
}
pub fn from_ast_name_and_mangle_for_module(
alloc: &'arena bumpalo::Bump,
s: impl std::convert::Into<std::string::String>,
) -> Self {
ClassName(Str::new_str(
alloc,
&format!(
"__module_{}",
hhbc_string_utils::strip_global_ns(&hhbc_string_utils::mangle(s.into()))
),
))
}
pub fn unsafe_to_unmangled_str(&self) -> std::borrow::Cow<'arena, str> {
std::borrow::Cow::from(hhbc_string_utils::unmangle(self.unsafe_as_str().into()))
}
}
#[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, Serialize)]
#[repr(C)]
pub struct PropName<'arena>(Str<'arena>);
impl_id!(PropName);
impl_add_suffix!(PropName);
impl<'arena> PropName<'arena> {
pub fn from_ast_name(alloc: &'arena bumpalo::Bump, s: &str) -> PropName<'arena> {
PropName(Str::new_str(alloc, hhbc_string_utils::strip_global_ns(s)))
}
}
#[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, Serialize)]
#[repr(C)]
pub struct MethodName<'arena>(Str<'arena>);
impl_id!(MethodName);
impl_add_suffix!(MethodName);
impl<'arena> MethodName<'arena> {
pub fn from_ast_name(alloc: &'arena bumpalo::Bump, s: &str) -> MethodName<'arena> {
MethodName(Str::new_str(alloc, hhbc_string_utils::strip_global_ns(s)))
}
pub fn from_ast_name_and_suffix(alloc: &'arena bumpalo::Bump, s: &str, suffix: &str) -> Self {
MethodName::from_raw_string_with_suffix(
alloc,
hhbc_string_utils::strip_global_ns(s),
suffix,
)
}
}
#[derive(Copy, Clone, Eq, Hash, Serialize)]
#[repr(C)]
pub struct FunctionName<'arena>(Str<'arena>);
impl_id!(FunctionName);
impl_add_suffix!(FunctionName);
impl<'arena> FunctionName<'arena> {
pub fn from_ast_name(alloc: &'arena bumpalo::Bump, s: &str) -> FunctionName<'arena> {
FunctionName(Str::new_str(alloc, hhbc_string_utils::strip_global_ns(s)))
}
}
impl<'arena> PartialEq for FunctionName<'arena> {
fn eq(&self, other: &Self) -> bool {
self.as_bytes().eq_ignore_ascii_case(other.as_bytes())
}
}
impl<'arena> Ord for FunctionName<'arena> {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
if self.eq(other) {
return std::cmp::Ordering::Equal;
}
self.0.cmp(&other.0)
}
}
impl<'arena> PartialOrd for FunctionName<'arena> {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
#[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, Serialize)]
#[repr(C)]
pub struct ConstName<'arena>(Str<'arena>);
impl_id!(ConstName);
impl<'arena> ConstName<'arena> {
pub fn from_ast_name(alloc: &'arena bumpalo::Bump, s: &str) -> ConstName<'arena> {
ConstName(Str::new_str(alloc, hhbc_string_utils::strip_global_ns(s)))
}
}
#[cfg(test)]
mod tests {
use std::collections::BTreeSet;
use super::*;
#[test]
fn test_from_unsafe_as_str() {
let alloc = bumpalo::Bump::new();
assert_eq!(
"Foo",
ClassName::from_raw_string(&alloc, "Foo").unsafe_as_str()
);
}
#[test]
fn test_add_suffix() {
let alloc = bumpalo::Bump::new();
let id = PropName::new(ffi::Str::new_str(&alloc, "Some"));
let id = PropName::add_suffix(&alloc, &id, "Property");
assert_eq!("SomeProperty", id.unsafe_as_str());
}
#[test]
fn test_from_ast_name() {
let alloc = bumpalo::Bump::new();
let id = MethodName::from_ast_name(&alloc, "meth");
assert_eq!("meth", id.unsafe_as_str());
}
#[test]
fn test_eq_function_name() {
let alloc = bumpalo::Bump::new();
let id1 = FunctionName::from_ast_name(&alloc, "foo2$memoize_impl");
let id2 = FunctionName::from_ast_name(&alloc, "Foo2$memoize_impl");
assert_eq!(id1, id2);
}
#[test]
fn test_ord_function_name() {
let alloc = bumpalo::Bump::new();
let mut ids = BTreeSet::new();
ids.insert(FunctionName::from_ast_name(&alloc, "foo"));
ids.insert(FunctionName::from_ast_name(&alloc, "Foo"));
ids.insert(FunctionName::from_ast_name(&alloc, "foo2"));
ids.insert(FunctionName::from_ast_name(&alloc, "Bar"));
ids.insert(FunctionName::from_ast_name(&alloc, "bar"));
let expected = ["Bar", "foo", "foo2"];
let ids: Vec<&str> = ids.into_iter().map(|id| id.unsafe_as_str()).collect();
assert_eq!(expected, ids.as_slice());
}
} |
Rust | hhvm/hphp/hack/src/hackc/hhbc/instruct.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::Slice;
use ffi::Str;
use serde::Serialize;
use crate::opcodes::Opcode;
use crate::typed_value::TypedValue;
use crate::FCallArgsFlags;
use crate::PropName;
use crate::ReadonlyOp;
use crate::SrcLoc;
/// see runtime/base/repo-auth-type.h
pub type RepoAuthType<'arena> = Str<'arena>;
pub type StackIndex = u32;
pub type ClassNum = u32;
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize)]
#[repr(C)]
pub struct Dummy(bool);
impl Dummy {
pub const DEFAULT: Dummy = Dummy(false);
}
/// HHBC encodes bytecode offsets as i32 (HPHP::Offset) so u32
/// is plenty of range for label ids.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd, Serialize)]
#[repr(transparent)]
pub struct Label(pub u32);
impl std::convert::From<Label> for usize {
fn from(id: Label) -> Self {
id.0 as usize
}
}
impl std::fmt::Display for Label {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl Label {
pub const INVALID: Label = Label(u32::MAX);
pub const ZERO: Label = Label(0);
pub fn is_valid(&self) -> bool {
self.0 != u32::MAX
}
pub fn as_usize(&self) -> usize {
self.0 as usize
}
}
pub type NumParams = u32;
pub type ByRefs<'arena> = Slice<'arena, bool>;
// This corresponds to kActRecCells in bytecode.h and must be kept in sync.
pub const NUM_ACT_REC_CELLS: usize = 2;
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize)]
#[repr(C)]
pub struct FCallArgs<'arena> {
pub flags: FCallArgsFlags,
pub async_eager_target: Label,
pub num_args: NumParams,
pub num_rets: NumParams,
pub inouts: ByRefs<'arena>,
pub readonly: ByRefs<'arena>,
pub context: Str<'arena>,
}
impl<'arena> FCallArgs<'arena> {
pub fn new(
mut flags: FCallArgsFlags,
num_rets: NumParams,
num_args: NumParams,
inouts: Slice<'arena, bool>,
readonly: Slice<'arena, bool>,
async_eager_target: Option<Label>,
context: Option<&'arena str>,
) -> Self {
assert!(
inouts.is_empty() || inouts.len() == num_args as usize,
"length of inouts must be either zero or num_args"
);
assert!(
readonly.is_empty() || readonly.len() == num_args as usize,
"length of readonly must be either zero or num_args"
);
assert!(
context.map_or(true, |c| !c.is_empty()),
"unexpected empty context"
);
if context.is_some() {
flags |= FCallArgsFlags::ExplicitContext;
}
let async_eager_target = match async_eager_target {
Some(label) => {
flags |= FCallArgsFlags::HasAsyncEagerOffset;
label
}
None => Label::INVALID,
};
Self {
flags,
num_args,
num_rets,
inouts,
readonly,
async_eager_target,
context: Str::new(context.unwrap_or("").as_bytes()),
}
}
pub fn has_async_eager_target(&self) -> bool {
self.flags.contains(FCallArgsFlags::HasAsyncEagerOffset)
}
pub fn targets(&self) -> &[Label] {
if self.has_async_eager_target() {
std::slice::from_ref(&self.async_eager_target)
} else {
&[]
}
}
/// num_inputs() only includes "interesting" inputs - so it doesn't include
/// the ActRec or inout values. It also doesn't include inputs defined by
/// the specific instruct (such as FCallFunc vs FCallFuncD).
///
/// This is similar but not exactly the same as the numArgsInclUnpack()
/// lambda in HHVM's fcallImpl().
pub fn num_inputs(&self) -> usize {
self.num_args as usize
+ self.flags.contains(FCallArgsFlags::HasUnpack) as usize
+ self.flags.contains(FCallArgsFlags::HasGenerics) as usize
}
pub fn num_inouts(&self) -> usize {
self.inouts.iter().map(|&b| b as usize).sum()
}
}
/// Local variable numbers are ultimately encoded as IVA, limited to u32.
/// Locals with idx < num_params + num_decl_vars are considered named,
/// higher numbered locals are considered unnamed.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize)]
#[repr(C)]
pub struct Local {
/// 0-based index into HHBC stack frame locals.
pub idx: u32,
}
impl std::fmt::Display for Local {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.idx.fmt(f)
}
}
impl Local {
pub const INVALID: Self = Self { idx: u32::MAX };
pub const ZERO: Self = Self { idx: 0 };
pub fn new(x: usize) -> Self {
Self { idx: x as u32 }
}
pub fn is_valid(self) -> bool {
self != Self::INVALID
}
pub fn from_usize(idx: usize) -> Local {
Local { idx: idx as u32 }
}
pub fn as_usize(&self) -> usize {
self.idx as usize
}
}
#[derive(
Default, Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd, Serialize
)]
#[repr(C)]
pub struct IterId {
/// 0-based index into HHBC stack frame iterators
pub idx: u32,
}
impl std::fmt::Display for IterId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.idx)
}
}
#[derive(Clone, Debug, Hash, Eq, PartialEq, Serialize)]
#[repr(C)]
pub struct IterArgs {
pub iter_id: IterId,
pub key_id: Local,
pub val_id: Local,
}
impl std::default::Default for IterArgs {
fn default() -> Self {
Self {
iter_id: Default::default(),
key_id: Local::INVALID,
val_id: Local::INVALID,
}
}
}
#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq, Serialize)]
#[repr(C)]
pub enum MemberKey<'arena> {
EC(StackIndex, ReadonlyOp),
EL(Local, ReadonlyOp),
ET(Str<'arena>, ReadonlyOp),
EI(i64, ReadonlyOp),
PC(StackIndex, ReadonlyOp),
PL(Local, ReadonlyOp),
PT(PropName<'arena>, ReadonlyOp),
QT(PropName<'arena>, ReadonlyOp),
W,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
#[repr(C)]
pub enum HasGenericsOp {
NoGenerics,
MaybeGenerics,
HasGenerics,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
#[repr(C)]
pub enum ClassishKind {
Class, // c.f. ast_defs::ClassishKind - may need Abstraction (Concrete, Abstract)
Interface,
Trait,
Enum,
EnumClass,
}
impl std::convert::From<oxidized::ast_defs::ClassishKind> for ClassishKind {
fn from(k: oxidized::ast_defs::ClassishKind) -> Self {
use oxidized::ast_defs;
match k {
ast_defs::ClassishKind::Cclass(_) => Self::Class,
ast_defs::ClassishKind::Cinterface => Self::Interface,
ast_defs::ClassishKind::Ctrait => Self::Trait,
ast_defs::ClassishKind::Cenum => Self::Enum,
ast_defs::ClassishKind::CenumClass(_) => Self::EnumClass,
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
#[repr(C)]
pub enum Visibility {
Private,
Public,
Protected,
Internal,
}
impl std::convert::From<oxidized::ast_defs::Visibility> for Visibility {
fn from(k: oxidized::ast_defs::Visibility) -> Self {
use oxidized::ast_defs;
match k {
ast_defs::Visibility::Private => Self::Private,
ast_defs::Visibility::Public => Self::Public,
ast_defs::Visibility::Protected => Self::Protected,
ast_defs::Visibility::Internal => Self::Internal,
}
}
}
impl AsRef<str> for Visibility {
fn as_ref(&self) -> &str {
match self {
Self::Private => "private",
Self::Public => "public",
Self::Protected => "protected",
Self::Internal => "internal",
}
}
}
impl From<Visibility> for hhvm_types_ffi::Attr {
fn from(k: Visibility) -> Self {
match k {
Visibility::Private => Self::AttrPrivate,
Visibility::Public => Self::AttrPublic,
Visibility::Protected => Self::AttrProtected,
// TODO(T115356820): Decide whether internal should be mutually
// exclusive with other visibility modifiers or it should be a
// modifier on top the others.
// In order to unblock typechecker, let it be a modifier on top for now.
Visibility::Internal => Self::AttrInternal | Self::AttrPublic,
}
}
}
/// A Contiguous range of locals. The canonical (default) empty
/// range is {0, 0}. This is normally only used for unnamed locals
/// but nothing prevents arbitrary ranges.
#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq, Serialize)]
#[repr(C)]
pub struct LocalRange {
pub start: Local,
pub len: u32,
}
impl LocalRange {
pub const EMPTY: LocalRange = LocalRange {
start: Local::INVALID,
len: 0,
};
pub fn from_local(local: Local) -> LocalRange {
LocalRange {
start: local,
len: 1,
}
}
pub fn iter(&self) -> impl Iterator<Item = Local> {
let start = self.start.as_usize();
let end = start + self.len as usize;
(start..end).map(Local::from_usize)
}
}
/// These are HHAS pseudo-instructions that are handled in the HHAS parser and
/// do not have HHBC opcodes equivalents.
#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize)]
#[repr(C)]
pub enum Pseudo<'arena> {
/// An internal representation of a break statement that is removed by the
/// try/finally rewriter.
Break,
Comment(Str<'arena>),
/// An internal representation of a continue statement that is removed by
/// the try/finally rewriter.
Continue,
Label(Label),
SrcLoc(SrcLoc),
TryCatchBegin,
TryCatchEnd,
TryCatchMiddle,
/// Pseudo instruction that will get translated into appropraite literal
/// bytecode, with possible reference to .adata *)
TypedValue(TypedValue<'arena>),
}
pub trait Targets {
/// Return a slice of labels for the conditional branch targets of this
/// instruction. This excludes the Label in an ILabel instruction, which is
/// not a conditional branch.
fn targets(&self) -> &[Label];
}
#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize)]
#[repr(C)]
pub enum Instruct<'arena> {
// HHVM opcodes.
Opcode(Opcode<'arena>),
// HHAS pseudo-instructions.
Pseudo(Pseudo<'arena>),
}
impl Instruct<'_> {
/// Return a slice of labels for the conditional branch targets of this instruction.
/// This excludes the Label in an ILabel instruction, which is not a conditional branch.
pub fn targets(&self) -> &[Label] {
match self {
Self::Opcode(opcode) => opcode.targets(),
// Make sure new variants with branch target Labels are handled above
// before adding items to this catch-all.
Self::Pseudo(
Pseudo::TypedValue(_)
| Pseudo::Continue
| Pseudo::Break
| Pseudo::Label(_)
| Pseudo::TryCatchBegin
| Pseudo::TryCatchMiddle
| Pseudo::TryCatchEnd
| Pseudo::Comment(_)
| Pseudo::SrcLoc(_),
) => &[],
}
}
pub fn num_inputs(&self) -> usize {
match self {
Self::Opcode(opcode) => opcode.num_inputs(),
Self::Pseudo(
Pseudo::TypedValue(_)
| Pseudo::Continue
| Pseudo::Break
| Pseudo::Label(_)
| Pseudo::TryCatchBegin
| Pseudo::TryCatchMiddle
| Pseudo::TryCatchEnd
| Pseudo::Comment(_)
| Pseudo::SrcLoc(_),
) => 0,
}
}
pub fn variant_name(&self) -> &'static str {
match self {
Self::Opcode(opcode) => opcode.variant_name(),
Self::Pseudo(Pseudo::TypedValue(_)) => "TypedValue",
Self::Pseudo(Pseudo::Continue) => "Continue",
Self::Pseudo(Pseudo::Break) => "Break",
Self::Pseudo(Pseudo::Label(_)) => "Label",
Self::Pseudo(Pseudo::TryCatchBegin) => "TryCatchBegin",
Self::Pseudo(Pseudo::TryCatchMiddle) => "TryCatchMiddle",
Self::Pseudo(Pseudo::TryCatchEnd) => "TryCatchEnd",
Self::Pseudo(Pseudo::Comment(_)) => "Comment",
Self::Pseudo(Pseudo::SrcLoc(_)) => "SrcLoc",
}
}
} |
Rust | hhvm/hphp/hack/src/hackc/hhbc/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.
#![feature(box_patterns)]
mod adata;
mod attribute;
mod body;
mod class;
mod coeffects;
mod constant;
pub mod decl_vars;
mod function;
mod id;
mod instruct;
mod method;
mod module;
mod opcodes;
mod param;
mod pos;
mod property;
mod symbol_refs;
mod type_const;
mod typed_value;
mod typedef;
mod types;
mod unit;
pub use adata::*;
pub use attribute::*;
pub use body::*;
pub use class::*;
pub use coeffects::*;
pub use constant::*;
pub use function::*;
pub use hhvm_hhbc_defs_ffi::ffi::*;
pub use id::*;
pub use instruct::*;
pub use method::*;
pub use module::*;
pub use opcodes::*;
pub use param::*;
pub use pos::*;
pub use property::*;
pub use symbol_refs::*;
pub use type_const::*;
pub use typed_value::*;
pub use typedef::*;
pub use types::*;
pub use unit::*; |
Rust | hhvm/hphp/hack/src/hackc/hhbc/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 bitflags::bitflags;
use ffi::Slice;
use hhvm_types_ffi::ffi::Attr;
use serde::Serialize;
use crate::Attribute;
use crate::Body;
use crate::Coeffects;
use crate::MethodName;
use crate::Span;
use crate::Visibility;
#[derive(Debug, Serialize)]
#[repr(C)]
pub struct Method<'arena> {
pub attributes: Slice<'arena, Attribute<'arena>>,
pub visibility: Visibility,
pub name: MethodName<'arena>,
pub body: Body<'arena>,
pub span: Span,
pub coeffects: Coeffects<'arena>,
pub flags: MethodFlags,
pub attrs: Attr,
}
bitflags! {
#[derive(Default, Serialize)]
#[repr(C)]
pub struct MethodFlags: u16 {
const IS_ASYNC = 1 << 0;
const IS_GENERATOR = 1 << 1;
const IS_PAIR_GENERATOR = 1 << 2;
const IS_CLOSURE_BODY = 1 << 3;
}
}
impl Method<'_> {
pub fn is_closure_body(&self) -> bool {
self.flags.contains(MethodFlags::IS_CLOSURE_BODY)
}
} |
Rust | hhvm/hphp/hack/src/hackc/hhbc/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 ffi::Maybe;
use ffi::Slice;
use ffi::Str;
use serde::Serialize;
use crate::Attribute;
use crate::ClassName;
use crate::Span;
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
#[repr(C)]
pub enum RuleKind {
Global,
Prefix,
Exact,
}
#[derive(Debug, Serialize)]
#[repr(C)]
pub struct Rule<'arena> {
pub kind: RuleKind,
pub name: Maybe<Str<'arena>>,
}
#[derive(Debug, Serialize)]
#[repr(C)]
pub struct Module<'arena> {
pub attributes: Slice<'arena, Attribute<'arena>>,
pub name: ClassName<'arena>,
pub span: Span,
pub doc_comment: Maybe<Str<'arena>>,
pub exports: Maybe<Slice<'arena, Rule<'arena>>>,
pub imports: Maybe<Slice<'arena, Rule<'arena>>>,
} |
Rust | hhvm/hphp/hack/src/hackc/hhbc/opcodes.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_opcodes_macro::Targets;
use ffi::Slice;
use ffi::Str;
use serde::Serialize;
use crate::AdataId;
use crate::BareThisOp;
use crate::ClassName;
use crate::CollectionType;
use crate::ConstName;
use crate::ContCheckOp;
use crate::Dummy;
use crate::FCallArgs;
use crate::FatalOp;
use crate::FloatBits;
use crate::FunctionName;
use crate::IncDecOp;
use crate::InitPropOp;
use crate::IsLogAsDynamicCallOp;
use crate::IsTypeOp;
use crate::IterArgs;
use crate::IterId;
use crate::Label;
use crate::Local;
use crate::LocalRange;
use crate::MOpMode;
use crate::MemberKey;
use crate::MethodName;
use crate::NumParams;
use crate::OODeclExistsOp;
use crate::ObjMethodOp;
use crate::PropName;
use crate::QueryMOp;
use crate::ReadonlyOp;
use crate::RepoAuthType;
use crate::SetOpOp;
use crate::SetRangeOp;
use crate::SilenceOp;
use crate::SpecialClsRef;
use crate::StackIndex;
use crate::SwitchKind;
use crate::Targets;
use crate::TypeStructResolveOp;
use crate::NUM_ACT_REC_CELLS;
#[emit_opcodes_macro::emit_opcodes]
#[derive(Clone, Debug, Targets, Hash, Eq, PartialEq, Serialize)]
#[repr(C)]
pub enum Opcode<'arena> {
// This is filled in by the emit_opcodes macro. It can be printed using the
// "//hphp/hack/src/hackc/hhbc:dump-opcodes" binary.
}
// The macro also generates:
// impl Opcode<'arena> {
// pub fn variant_name(&self) -> &'static str;
// pub fn variant_index(&self) -> usize;
// pub fn num_inputs(&self) -> usize;
// }
// impl Targets for Opcode<'arena>; |
Rust | hhvm/hphp/hack/src/hackc/hhbc/opcode_test_data.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 hhbc_gen::ImmType;
use hhbc_gen::Inputs;
use hhbc_gen::InstrFlags;
use hhbc_gen::OpcodeData;
use hhbc_gen::Outputs;
pub fn test_opcodes() -> Vec<OpcodeData> {
vec![
OpcodeData {
name: "TestZeroImm",
immediates: vec![],
inputs: Inputs::NOV,
outputs: Outputs::NOV,
flags: InstrFlags::NF,
},
OpcodeData {
name: "TestOneImm",
immediates: vec![("str1", ImmType::SA)],
inputs: Inputs::NOV,
outputs: Outputs::NOV,
flags: InstrFlags::NF,
},
OpcodeData {
name: "TestTwoImm",
immediates: vec![("str1", ImmType::SA), ("str2", ImmType::SA)],
inputs: Inputs::NOV,
outputs: Outputs::NOV,
flags: InstrFlags::NF,
},
OpcodeData {
name: "TestThreeImm",
immediates: vec![
("str1", ImmType::SA),
("str2", ImmType::SA),
("str3", ImmType::SA),
],
inputs: Inputs::NOV,
outputs: Outputs::NOV,
flags: InstrFlags::NF,
},
// --------------------------------------------------
OpcodeData {
name: "TestAsStruct",
immediates: vec![("str1", ImmType::SA), ("str2", ImmType::SA)],
inputs: Inputs::NOV,
outputs: Outputs::NOV,
flags: InstrFlags::AS_STRUCT,
},
// --------------------------------------------------
OpcodeData {
name: "TestAA",
immediates: vec![("arr1", ImmType::AA)],
inputs: Inputs::NOV,
outputs: Outputs::NOV,
flags: InstrFlags::NF,
},
OpcodeData {
name: "TestARR",
immediates: vec![("arr1", ImmType::ARR(Box::new(ImmType::SA)))],
inputs: Inputs::NOV,
outputs: Outputs::NOV,
flags: InstrFlags::NF,
},
OpcodeData {
name: "TestBA",
immediates: vec![("target1", ImmType::BA)],
inputs: Inputs::NOV,
outputs: Outputs::NOV,
flags: InstrFlags::CF | InstrFlags::TF,
},
OpcodeData {
name: "TestBA2",
immediates: vec![("target1", ImmType::BA2)],
inputs: Inputs::NOV,
outputs: Outputs::NOV,
flags: InstrFlags::CF | InstrFlags::TF,
},
OpcodeData {
name: "TestBLA",
immediates: vec![("targets", ImmType::BLA)],
inputs: Inputs::NOV,
outputs: Outputs::NOV,
flags: InstrFlags::CF | InstrFlags::TF,
},
OpcodeData {
name: "TestDA",
immediates: vec![("dbl1", ImmType::DA)],
inputs: Inputs::NOV,
outputs: Outputs::NOV,
flags: InstrFlags::NF,
},
OpcodeData {
name: "TestFCA",
immediates: vec![("fca", ImmType::FCA)],
inputs: Inputs::NOV,
outputs: Outputs::NOV,
flags: InstrFlags::CF,
},
OpcodeData {
name: "TestI64A",
immediates: vec![("arg1", ImmType::I64A)],
inputs: Inputs::NOV,
outputs: Outputs::NOV,
flags: InstrFlags::NF,
},
OpcodeData {
name: "TestIA",
immediates: vec![("iter1", ImmType::IA)],
inputs: Inputs::NOV,
outputs: Outputs::NOV,
flags: InstrFlags::NF,
},
OpcodeData {
name: "TestILA",
immediates: vec![("loc1", ImmType::ILA)],
inputs: Inputs::NOV,
outputs: Outputs::NOV,
flags: InstrFlags::NF,
},
OpcodeData {
name: "TestITA",
immediates: vec![("ita", ImmType::ITA)],
inputs: Inputs::NOV,
outputs: Outputs::NOV,
flags: InstrFlags::CF,
},
OpcodeData {
name: "TestIVA",
immediates: vec![("arg1", ImmType::IVA)],
inputs: Inputs::NOV,
outputs: Outputs::NOV,
flags: InstrFlags::NF,
},
OpcodeData {
name: "TestKA",
immediates: vec![("mkey", ImmType::KA)],
inputs: Inputs::NOV,
outputs: Outputs::NOV,
flags: InstrFlags::NF,
},
OpcodeData {
name: "TestLA",
immediates: vec![("loc1", ImmType::LA)],
inputs: Inputs::NOV,
outputs: Outputs::NOV,
flags: InstrFlags::NF,
},
OpcodeData {
name: "TestLAR",
immediates: vec![("locrange", ImmType::LAR)],
inputs: Inputs::NOV,
outputs: Outputs::NOV,
flags: InstrFlags::CF,
},
OpcodeData {
name: "TestNLA",
immediates: vec![("nloc1", ImmType::NLA)],
inputs: Inputs::NOV,
outputs: Outputs::NOV,
flags: InstrFlags::NF,
},
OpcodeData {
name: "TestOA",
immediates: vec![("subop1", ImmType::OA("OaSubType"))],
inputs: Inputs::NOV,
outputs: Outputs::NOV,
flags: InstrFlags::NF,
},
OpcodeData {
name: "TestOAL",
immediates: vec![("subop1", ImmType::OAL("OaSubType"))],
inputs: Inputs::NOV,
outputs: Outputs::NOV,
flags: InstrFlags::NF,
},
OpcodeData {
name: "TestRATA",
immediates: vec![("rat", ImmType::RATA)],
inputs: Inputs::NOV,
outputs: Outputs::NOV,
flags: InstrFlags::NF,
},
OpcodeData {
name: "TestSA",
immediates: vec![("str1", ImmType::SA)],
inputs: Inputs::NOV,
outputs: Outputs::NOV,
flags: InstrFlags::NF,
},
OpcodeData {
name: "TestSLA",
immediates: vec![("targets", ImmType::SLA)],
inputs: Inputs::NOV,
outputs: Outputs::NOV,
flags: InstrFlags::CF | InstrFlags::TF,
},
OpcodeData {
name: "TestVSA",
immediates: vec![("keys", ImmType::VSA)],
inputs: Inputs::NOV,
outputs: Outputs::NOV,
flags: InstrFlags::NF,
},
]
} |
Rust | hhvm/hphp/hack/src/hackc/hhbc/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 ffi::Maybe;
use ffi::Maybe::*;
use ffi::Slice;
use ffi::Str;
use serde::Serialize;
use crate::Attribute;
use crate::Constraint;
use crate::Label;
use crate::TypeInfo;
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[repr(C)]
pub struct Param<'arena> {
pub name: Str<'arena>,
pub is_variadic: bool,
pub is_inout: bool,
pub is_readonly: bool,
pub user_attributes: Slice<'arena, Attribute<'arena>>,
pub type_info: Maybe<TypeInfo<'arena>>,
pub default_value: Maybe<DefaultValue<'arena>>,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[repr(C)]
pub struct DefaultValue<'arena> {
pub label: Label,
pub expr: Str<'arena>,
}
impl<'arena> Param<'arena> {
pub fn replace_default_value_label(&mut self, new_label: Label) {
if let Just(dv) = self.default_value.as_mut() {
dv.label = new_label;
}
}
pub fn without_type(&mut self) {
if let Just(ti) = self.type_info.as_mut() {
ti.type_constraint = Constraint::default()
}
}
pub fn with_name(&mut self, alloc: &'arena bumpalo::Bump, name: &str) {
self.name = Str::new_str(alloc, name);
}
} |
Rust | hhvm/hphp/hack/src/hackc/hhbc/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 serde::Serialize;
// Keep this in sync with HPHP::SourceLoc in hphp/runtime/vm/source-location.h
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize)]
#[repr(C)]
pub struct SrcLoc {
pub line_begin: i32,
pub line_end: i32,
pub col_begin: i32,
pub col_end: i32,
}
impl Default for SrcLoc {
fn default() -> Self {
Self {
line_begin: 1,
line_end: 1,
col_begin: 0,
col_end: 0,
}
}
}
impl std::convert::From<oxidized::pos::Pos> for SrcLoc {
fn from(p: oxidized::pos::Pos) -> Self {
if p.is_none() || !p.is_valid() {
Self::default()
} else {
let (line_begin, line_end, col_begin, col_end) = p.info_pos_extended();
Self {
line_begin: line_begin as i32,
line_end: line_end as i32,
col_begin: col_begin as i32,
col_end: col_end as i32,
}
}
}
}
/// Span, emitted as prefix to classes and functions
/// Keep this in sync with line1,line2 in HPHP::FuncEmitter
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize)]
#[repr(C)]
pub struct Span {
pub line_begin: i32,
pub line_end: i32,
}
impl Span {
pub fn from_pos(pos: &oxidized::pos::Pos) -> Self {
let (line_begin, line_end, _, _) = pos.info_pos_extended();
Self {
line_begin: line_begin as i32,
line_end: line_end as i32,
}
}
} |
Rust | hhvm/hphp/hack/src/hackc/hhbc/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 ffi::Maybe;
use ffi::Slice;
use ffi::Str;
use hhvm_types_ffi::ffi::Attr;
use serde::Serialize;
use crate::Attribute;
use crate::PropName;
use crate::TypeInfo;
use crate::TypedValue;
use crate::Visibility;
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[repr(C)]
pub struct Property<'arena> {
pub name: PropName<'arena>,
pub flags: Attr,
pub attributes: Slice<'arena, Attribute<'arena>>,
pub visibility: Visibility,
pub initial_value: Maybe<TypedValue<'arena>>,
pub type_info: TypeInfo<'arena>,
pub doc_comment: Maybe<Str<'arena>>,
}
impl<'arena> Property<'arena> {
pub fn is_private(&self) -> bool {
self.visibility == Visibility::Private
}
pub fn is_protected(&self) -> bool {
self.visibility == Visibility::Protected
}
pub fn is_public(&self) -> bool {
self.visibility == Visibility::Public
}
} |
Rust | hhvm/hphp/hack/src/hackc/hhbc/symbol_refs.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::cmp::Ordering;
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
use std::path::Path;
use bstr::BString;
use ffi::Slice;
use ffi::Str;
use relative_path::RelativePath;
use serde::Serialize;
use crate::ClassName;
use crate::ConstName;
use crate::FunctionName;
/// Data structure for keeping track of symbols (and includes) we
/// encounter in the course of emitting bytecode for an AST. We split
/// them into these four categories for the sake of HHVM, which has
/// a dedicated lookup function corresponding to each.
#[derive(Default, Clone, Debug, Serialize)]
#[repr(C)]
pub struct SymbolRefs<'arena> {
pub includes: Slice<'arena, IncludePath<'arena>>,
pub constants: Slice<'arena, ConstName<'arena>>,
pub functions: Slice<'arena, FunctionName<'arena>>,
pub classes: Slice<'arena, ClassName<'arena>>,
}
/// NOTE(hrust): order matters (hhbc_hhas write includes in sorted order)
pub type IncludePathSet<'arena> = BTreeSet<IncludePath<'arena>>;
#[derive(Clone, Debug, Eq, Serialize)]
#[repr(C)]
pub enum IncludePath<'arena> {
Absolute(Str<'arena>), // /foo/bar/baz.php
SearchPathRelative(Str<'arena>), // foo/bar/baz.php
IncludeRootRelative(Str<'arena>, Str<'arena>), // $_SERVER['PHP_ROOT'] . "foo/bar/baz.php"
DocRootRelative(Str<'arena>),
}
impl<'arena> Ord for IncludePath<'arena> {
fn cmp(&self, other: &Self) -> Ordering {
self.extract_str().cmp(&other.extract_str())
}
}
impl<'arena> PartialOrd for IncludePath<'arena> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<'arena> PartialEq for IncludePath<'arena> {
fn eq(&self, other: &Self) -> bool {
self.extract_str().eq(&other.extract_str())
}
}
impl<'arena> IncludePath<'arena> {
pub fn resolve_include_roots(
self,
alloc: &'arena bumpalo::Bump,
include_roots: &BTreeMap<BString, BString>,
current_path: &RelativePath,
) -> IncludePath<'arena> {
match self {
IncludePath::IncludeRootRelative(var, lit) => {
match include_roots.get(var.as_bstr()) {
Some(prefix) => {
let path =
Path::new(OsStr::from_bytes(prefix)).join(OsStr::from_bytes(&lit));
let relative = path.is_relative();
let path_str = Str::new_str(alloc, path.to_str().expect("non UTF-8 path"));
return if relative {
IncludePath::DocRootRelative(path_str)
} else {
IncludePath::Absolute(path_str)
};
}
_ => self, // This should probably never happen
}
}
IncludePath::SearchPathRelative(p) => {
let pathbuf = current_path
.path()
.parent()
.unwrap_or_else(|| Path::new(""))
.join(OsStr::from_bytes(&p));
let path_from_cur_dirname = Str::new_str(alloc, pathbuf.to_str().unwrap());
IncludePath::SearchPathRelative(path_from_cur_dirname)
}
_ => self,
}
}
pub fn extract_str(&self) -> (&str, &str) {
match self {
IncludePath::Absolute(s)
| IncludePath::SearchPathRelative(s)
| IncludePath::DocRootRelative(s) => (s.unsafe_as_str(), ""),
IncludePath::IncludeRootRelative(s1, s2) => (s1.unsafe_as_str(), s2.unsafe_as_str()),
}
}
} |
Rust | hhvm/hphp/hack/src/hackc/hhbc/typedef.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::Slice;
use hhvm_types_ffi::ffi::Attr;
use serde::Serialize;
use crate::Attribute;
use crate::ClassName;
use crate::Span;
use crate::TypeInfo;
use crate::TypedValue;
#[derive(Clone, Debug, Serialize)]
#[repr(C)]
pub struct Typedef<'arena> {
pub name: ClassName<'arena>,
pub attributes: Slice<'arena, Attribute<'arena>>,
pub type_info_union: Slice<'arena, TypeInfo<'arena>>,
pub type_structure: TypedValue<'arena>,
pub span: Span,
pub attrs: Attr,
pub case_type: bool,
} |
Rust | hhvm/hphp/hack/src/hackc/hhbc/typed_value.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::Slice;
use ffi::Str;
use serde::Serialize;
/// Raw IEEE floating point bits. We use this rather than f64 so that
/// hash/equality have bitwise interning behavior: -0.0 != 0.0, NaN == NaN.
/// If we ever implement Ord/PartialOrd, we'd need to base it on the raw bits
/// (u64), not floating point partial order.
#[derive(Copy, Clone, Debug, Serialize)]
#[repr(transparent)]
pub struct FloatBits(pub f64);
impl FloatBits {
pub fn to_f64(self) -> f64 {
self.0
}
pub fn to_bits(self) -> u64 {
self.0.to_bits()
}
}
impl Eq for FloatBits {}
impl PartialEq for FloatBits {
fn eq(&self, other: &FloatBits) -> bool {
self.to_bits() == other.to_bits()
}
}
impl std::hash::Hash for FloatBits {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.to_bits().hash(state);
}
}
impl From<f64> for FloatBits {
fn from(x: f64) -> Self {
Self(x)
}
}
/// We introduce a type for Hack/PHP values, mimicking what happens at
/// runtime. Currently this is used for constant folding. By defining
/// a special type, we ensure independence from usage: for example, it
/// can be used for optimization on ASTs, or on bytecode, or (in
/// future) on a compiler intermediate language. HHVM takes a similar
/// approach: see runtime/base/typed-value.h
#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize)]
#[repr(C)]
pub enum TypedValue<'arena> {
/// Used for fields that are initialized in the 86pinit method
Uninit,
/// Hack/PHP integers are signed 64-bit
Int(i64),
Bool(bool),
/// Hack, C++, PHP, and Caml floats are IEEE754 64-bit
Float(FloatBits),
String(Str<'arena>),
LazyClass(Str<'arena>),
Null,
// Hack arrays: vectors, keysets, and dictionaries
Vec(Slice<'arena, TypedValue<'arena>>),
Keyset(Slice<'arena, TypedValue<'arena>>),
Dict(Slice<'arena, Entry<TypedValue<'arena>, TypedValue<'arena>>>),
}
// This is declared as a generic type to work around cbindgen's topo-sort,
// which outputs Entry before TypedValue. This violates C++ ordering rules:
// A struct field type must be declared before the field.
#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize)]
#[repr(C)]
pub struct Entry<K, V> {
pub key: K,
pub value: V,
}
pub type DictEntry<'a> = Entry<TypedValue<'a>, TypedValue<'a>>;
impl<'arena> TypedValue<'arena> {
pub fn string(x: impl Into<Str<'arena>>) -> Self {
Self::String(x.into())
}
pub fn vec(x: impl Into<Slice<'arena, TypedValue<'arena>>>) -> Self {
Self::Vec(x.into())
}
pub fn keyset(x: impl Into<Slice<'arena, TypedValue<'arena>>>) -> Self {
Self::Keyset(x.into())
}
pub fn dict(x: impl Into<Slice<'arena, DictEntry<'arena>>>) -> Self {
Self::Dict(x.into())
}
pub fn alloc_string(s: impl AsRef<str>, alloc: &'arena bumpalo::Bump) -> Self {
Self::String((alloc.alloc_str(s.as_ref()) as &str).into())
}
pub fn float(f: f64) -> Self {
Self::Float(f.into())
}
} |
Rust | hhvm/hphp/hack/src/hackc/hhbc/types.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::Maybe;
use ffi::Maybe::Just;
use ffi::Slice;
use ffi::Str;
use hhvm_types_ffi::ffi::TypeConstraintFlags;
use serde::Serialize;
/// Type info has additional optional user type
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[repr(C)]
pub struct TypeInfo<'arena> {
pub user_type: Maybe<Str<'arena>>,
pub type_constraint: Constraint<'arena>,
}
#[derive(Clone, Default, Debug, Eq, PartialEq, Serialize)]
#[repr(C)]
pub struct Constraint<'arena> {
pub name: Maybe<Str<'arena>>,
pub flags: TypeConstraintFlags,
}
#[derive(Debug, Default, Eq, PartialEq, Serialize)]
#[repr(C)]
pub struct UpperBound<'arena> {
pub name: Str<'arena>,
pub bounds: Slice<'arena, TypeInfo<'arena>>,
}
impl<'arena> Constraint<'arena> {
pub fn make(name: Maybe<Str<'arena>>, flags: TypeConstraintFlags) -> Self {
Self { name, flags }
}
pub fn make_with_raw_str(
alloc: &'arena bumpalo::Bump,
name: &str,
flags: TypeConstraintFlags,
) -> Self {
Constraint::make(Just(Str::new_str(alloc, name)), flags)
}
}
impl<'arena> TypeInfo<'arena> {
pub fn make(user_type: Maybe<Str<'arena>>, type_constraint: Constraint<'arena>) -> Self {
Self {
user_type,
type_constraint,
}
}
pub fn make_empty() -> TypeInfo<'arena> {
TypeInfo::make(Just("".into()), Constraint::default())
}
pub fn has_type_constraint(&self) -> bool {
self.type_constraint.name.is_just()
}
}
#[cfg(test)]
mod test {
#[test]
fn test_constraint_flags_to_string_called_by_hhbc_hhas() {
use hhvm_types_ffi::ffi::TypeConstraintFlags;
let typevar_and_soft = TypeConstraintFlags::TypeVar | TypeConstraintFlags::Soft;
assert_eq!("type_var soft", typevar_and_soft.to_string());
}
} |
Rust | hhvm/hphp/hack/src/hackc/hhbc/type_const.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::Maybe;
use ffi::Str;
use serde::Serialize;
use crate::typed_value::TypedValue;
#[derive(Debug, Eq, PartialEq, Serialize)]
#[repr(C)]
pub struct TypeConstant<'arena> {
pub name: Str<'arena>,
pub initializer: Maybe<TypedValue<'arena>>,
pub is_abstract: bool,
} |
Rust | hhvm/hphp/hack/src/hackc/hhbc/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 ffi::Maybe;
use ffi::Slice;
use ffi::Str;
use serde::Serialize;
use crate::Adata;
use crate::Attribute;
use crate::Class;
use crate::Constant;
use crate::FatalOp;
use crate::Function;
use crate::Module;
use crate::SrcLoc;
use crate::SymbolRefs;
use crate::Typedef;
#[derive(Default, Debug, Serialize)]
#[repr(C)]
pub struct Unit<'arena> {
pub adata: Slice<'arena, Adata<'arena>>,
pub functions: Slice<'arena, Function<'arena>>,
pub classes: Slice<'arena, Class<'arena>>,
pub modules: Slice<'arena, Module<'arena>>,
pub typedefs: Slice<'arena, Typedef<'arena>>,
pub file_attributes: Slice<'arena, Attribute<'arena>>,
pub module_use: Maybe<Str<'arena>>,
pub symbol_refs: SymbolRefs<'arena>,
pub constants: Slice<'arena, Constant<'arena>>,
pub fatal: Maybe<Fatal<'arena>>,
pub missing_symbols: Slice<'arena, Str<'arena>>,
pub error_symbols: Slice<'arena, Str<'arena>>,
}
/// Fields used when a unit had compile-time errors that should be reported
/// when the unit is loaded.
#[derive(Debug, Serialize)]
#[repr(C)]
pub struct Fatal<'arena> {
pub op: FatalOp,
pub loc: SrcLoc,
pub message: Str<'arena>,
} |
Rust | hhvm/hphp/hack/src/hackc/hhbc/unit_cbindgen.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.
/// This definition exists for ffi_cbindgen C++ header generation. Any
/// attempt to call this function will result in an intentional
/// unresolved symbol at link time.
#[no_mangle]
pub extern "C" fn no_call_compile_only_USED_TYPES_hackc_unit<'arena>(_: Unit<'arena>) {
unimplemented!()
} |
TOML | hhvm/hphp/hack/src/hackc/hhbc/cargo/dump-opcodes/Cargo.toml | # @generated by autocargo
[package]
name = "dump-opcodes"
version = "0.0.0"
edition = "2021"
[[bin]]
name = "dump_opcodes"
path = "../../dump_opcodes.rs"
[dependencies]
anyhow = "1.0.71"
clap = { version = "4.3.5", features = ["derive", "env", "string", "unicode", "wrap_help"] }
emit_opcodes = { version = "0.0.0", path = "../emit_opcodes" }
hhbc-gen = { version = "0.0.0", path = "../../../../../../tools/hhbc-gen" }
quote = "1.0.29" |
TOML | hhvm/hphp/hack/src/hackc/hhbc/cargo/emit_opcodes/Cargo.toml | # @generated by autocargo
[package]
name = "emit_opcodes"
version = "0.0.0"
edition = "2021"
[lib]
path = "../../emit_opcodes.rs"
[dependencies]
convert_case = "0.4.0"
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 = "../opcode_test_data" } |
TOML | hhvm/hphp/hack/src/hackc/hhbc/cargo/emit_opcodes_macro/Cargo.toml | # @generated by autocargo
[package]
name = "emit_opcodes_macro"
version = "0.0.0"
edition = "2021"
[lib]
path = "../../emit_opcodes_macro.rs"
test = false
doctest = false
proc-macro = true
[dependencies]
emit_opcodes = { version = "0.0.0", path = "../emit_opcodes" }
hhbc-gen = { version = "0.0.0", path = "../../../../../../tools/hhbc-gen" } |
TOML | hhvm/hphp/hack/src/hackc/hhbc/cargo/hhbc/Cargo.toml | # @generated by autocargo
[package]
name = "hhbc"
version = "0.0.0"
edition = "2021"
[lib]
path = "../../lib.rs"
[dependencies]
bitflags = "1.3"
bstr = { version = "1.4.0", features = ["serde", "std", "unicode"] }
bumpalo = { version = "3.11.1", features = ["collections"] }
emit_opcodes_macro = { version = "0.0.0", path = "../emit_opcodes_macro" }
ffi = { version = "0.0.0", path = "../../../../utils/ffi" }
hash = { version = "0.0.0", path = "../../../../utils/hash" }
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" }
naming_special_names_rust = { version = "0.0.0", path = "../../../../naming" }
oxidized = { version = "0.0.0", path = "../../../../oxidized" }
relative_path = { version = "0.0.0", path = "../../../../utils/rust/relative_path" }
serde = { version = "1.0.176", features = ["derive", "rc"] }
write_bytes = { version = "0.0.0", path = "../../../../utils/write_bytes/write_bytes" } |
TOML | hhvm/hphp/hack/src/hackc/hhbc/cargo/opcode_test_data/Cargo.toml | # @generated by autocargo
[package]
name = "opcode_test_data"
version = "0.0.0"
edition = "2021"
[lib]
path = "../../opcode_test_data.rs"
[dependencies]
hhbc-gen = { version = "0.0.0", path = "../../../../../../tools/hhbc-gen" } |
Rust | hhvm/hphp/hack/src/hackc/hhvm_config/hhvm_config.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 anyhow::Result;
use hhvm_options::HhvmConfig;
use options::HhbcFlags;
use options::JitEnableRenameFunction;
use options::ParserOptions;
/*
These helper functions are best-effort utilities for CLI tools like hackc
to read HHVM configuration. No guarantees are made about coverage;
ultimately the source of truth is HHVM, for how .hdf and .ini
files are turned into hackc/compile::NativeEnv (and its embedded options)
see hphp/runtime/base/config.{cpp,h} and runtime_option.{cpp,h}
*/
pub fn hhbc_flags(config: &HhvmConfig) -> Result<HhbcFlags> {
let mut flags = HhbcFlags::default();
// Use the config setting if provided; otherwise preserve existing value.
let init = |flag: &mut bool, name: &str| -> Result<()> {
match config.get_bool(name)? {
Some(b) => Ok(*flag = b),
None => Ok(()),
}
};
init(&mut flags.ltr_assign, "php7.ltr_assign")?;
init(&mut flags.uvs, "php7.uvs")?;
init(
&mut flags.log_extern_compiler_perf,
"Eval.LogExternCompilerPerf",
)?;
init(
&mut flags.enable_intrinsics_extension,
"Eval.EnableIntrinsicsExtension",
)?;
init(
&mut flags.emit_cls_meth_pointers,
"Eval.EmitClsMethPointers",
)?;
// Only the hdf versions used. Can kill variant in options_cli.rs
flags.emit_meth_caller_func_pointers = config
.get_bool("Eval.EmitMethCallerFuncPointers")?
.unwrap_or(true);
flags.readonly_nonlocal_infer = config
.get_bool("Hack.Lang.ReadonlyNonlocalInference")?
.unwrap_or(false);
flags.optimize_reified_param_checks = config
.get_bool("Hack.Lang.OptimizeReifiedParamChecks")?
.unwrap_or(false);
// ini might use hhvm.array_provenance
// hdf might use Eval.ArrayProvenance
// But super unclear here
init(&mut flags.array_provenance, "Eval.ArrayProvenance")?;
init(&mut flags.array_provenance, "array_provenance")?;
// Only hdf version
flags.fold_lazy_class_keys = config.get_bool("Eval.FoldLazyClassKeys")?.unwrap_or(true);
Ok(flags)
}
pub fn jit_enable_rename_function(config: &HhvmConfig) -> Result<JitEnableRenameFunction> {
match config.get_uint32("Eval.JitEnableRenameFunction")? {
Some(b) => {
if b == 1 {
Ok(JitEnableRenameFunction::Enable)
} else if b == 2 {
Ok(JitEnableRenameFunction::RestrictedEnable)
} else {
Ok(JitEnableRenameFunction::Disable)
}
}
None => Ok(JitEnableRenameFunction::Disable),
}
}
pub fn parser_options(config: &HhvmConfig) -> Result<ParserOptions> {
let mut flags = ParserOptions::default();
// Use the config setting if provided; otherwise preserve default.
let init = |flag: &mut bool, name: &str| -> Result<()> {
match config.get_bool(name)? {
Some(b) => Ok(*flag = b),
None => Ok(()),
}
};
// Note: Could only find examples of Hack.Lang.AbstractStaticProps
init(
&mut flags.po_abstract_static_props,
"Hack.Lang.AbstractStaticProps",
)?;
// TODO: I'm pretty sure allow_new_attribute_syntax is dead and we can kill this option
init(
&mut flags.po_allow_new_attribute_syntax,
"hack.lang.allow_new_attribute_syntax",
)?;
// Both hdf and ini versions are being used
init(
&mut flags.po_allow_unstable_features,
"Hack.Lang.AllowUnstableFeatures",
)?;
// TODO: could not find examples of const_default_func_args, kill it in options_cli.rs
init(
&mut flags.po_const_default_func_args,
"Hack.Lang.ConstDefaultFuncArgs",
)?;
// Only hdf version found in use
init(
&mut flags.tco_const_static_props,
"Hack.Lang.ConstStaticProps",
)?;
// TODO: Kill disable_lval_as_an_expression
// Both ini and hdf variants in use
init(
&mut flags.po_disable_xhp_element_mangling,
"Hack.Lang.DisableXHPElementMangling",
)?;
// Only hdf option in use
init(
&mut flags.po_disallow_func_ptrs_in_constants,
"Hack.Lang.DisallowFuncPtrsInConstants",
)?;
// Both options in use
init(
&mut flags.po_enable_xhp_class_modifier,
"Hack.Lang.EnableXHPClassModifier",
)?;
// Only hdf option in use. Kill variant in options_cli.rs
init(
&mut flags.po_enable_class_level_where_clauses,
"Hack.Lang.EnableClassLevelWhereClauses",
)?;
Ok(flags)
} |
TOML | hhvm/hphp/hack/src/hackc/hhvm_config/cargo/options/Cargo.toml | # @generated by autocargo
[package]
name = "hhvm_config"
version = "0.0.0"
edition = "2021"
[lib]
path = "../../hhvm_config.rs"
[dependencies]
anyhow = "1.0.71"
hhvm_options = { version = "0.0.0", path = "../../../../utils/hhvm_options" }
options = { version = "0.0.0", path = "../../../compile/cargo/options" } |
C++ | hhvm/hphp/hack/src/hackc/hhvm_cxx/hhvm_hhbc_defs/as-hhbc-ffi.cpp | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/hack/src/hackc/hhvm_cxx/hhvm_hhbc_defs/as-hhbc-ffi.h"
namespace HPHP {
rust::String fcall_flags_to_string_ffi(FCallArgsFlags flags) {
return fcall_flags_to_string(flags);
}
} // namespace HPHP |
C/C++ | hhvm/hphp/hack/src/hackc/hhvm_cxx/hhvm_hhbc_defs/as-hhbc-ffi.h | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#pragma once
#include "hphp/runtime/vm/as-base.h"
#include "hphp/runtime/vm/fcall-args-flags.h"
#include "hphp/runtime/vm/hhbc-shared.h"
#include "rust/cxx.h"
namespace HPHP {
//////////////////////////////////////////////////////////////////////
/*
* This header contains routines linked into HackC.
*/
//////////////////////////////////////////////////////////////////////
/*
* Convert an fcall flag `to a string of space-separated flag names.
*/
rust::String fcall_flags_to_string_ffi(FCallArgsFlags);
} // namespace HPHP |
Rust | hhvm/hphp/hack/src/hackc/hhvm_cxx/hhvm_hhbc_defs/build.rs | use std::path::Path;
use std::path::PathBuf;
use std::process::Command;
fn main() {
// Assume the hack workspace 'fbcode/hphp/hack/src/Cargo.toml'.
let mut cargo_cmd = Command::new("cargo");
cargo_cmd.args(&["locate-project", "--workspace", "--message-format=plain"]);
let output = cargo_cmd.output().unwrap().stdout;
let fbcode = Path::new(std::str::from_utf8(&output).unwrap().trim())
.ancestors()
.nth(4)
.unwrap();
let files = vec![
PathBuf::from("hhvm_hhbc_defs_ffi.rs"),
PathBuf::from("as-hhbc-ffi.cpp"),
PathBuf::from("as-hhbc-ffi.h"),
];
cxx_build::bridge("hhvm_hhbc_defs_ffi.rs")
.files(files.iter().filter(is_cpp))
.include(fbcode)
.cpp(true)
.flag("-std=c++17")
.compile("hhvm_hhbc_defs");
files.iter().for_each(rerun_if_changed);
rerun_if_changed("build.rs");
}
fn rerun_if_changed<P: AsRef<Path>>(f: P) {
println!("cargo:rerun-if-changed={}", f.as_ref().to_str().unwrap());
}
fn is_cpp<P: AsRef<Path>>(path: &P) -> bool {
path.as_ref().extension().map_or(false, |e| e == "cpp")
} |
TOML | hhvm/hphp/hack/src/hackc/hhvm_cxx/hhvm_hhbc_defs/Cargo.toml | # @generated by autocargo
[package]
name = "hhvm_hhbc_defs_ffi"
version = "0.0.0"
edition = "2021"
[lib]
path = "hhvm_hhbc_defs_ffi.rs"
crate-type = ["lib", "staticlib"]
[dependencies]
cxx = "1.0.100"
serde = { version = "1.0.176", features = ["derive", "rc"] }
[build-dependencies]
cxx-build = "1.0.100" |
Rust | hhvm/hphp/hack/src/hackc/hhvm_cxx/hhvm_hhbc_defs/hhvm_hhbc_defs_ffi.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::ops::BitAnd;
use std::ops::BitOr;
use std::ops::BitOrAssign;
#[allow(unreachable_patterns)]
#[cxx::bridge(namespace = "HPHP")]
pub mod ffi {
// This is not a real definition. Cxx just adds static asserts on each of
// these enum variants that they match the definition in
// fcall-args-flags.h.
#[repr(u16)]
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Serialize)]
enum FCallArgsFlags {
// This maps to a non-class enum in C++ so the variant names are chosen
// to avoid naming collisions.
FCANone = 0x0,
HasUnpack = 0x1,
HasGenerics = 0x2,
LockWhileUnwinding = 0x4,
SkipRepack = 0x8,
SkipCoeffectsCheck = 0x10,
EnforceMutableReturn = 0x20,
EnforceReadonlyThis = 0x40,
ExplicitContext = 0x80,
HasInOut = 0x100,
EnforceInOut = 0x200,
EnforceReadonly = 0x400,
HasAsyncEagerOffset = 0x800,
NumArgsStart = 0x1000,
}
#[repr(u8)]
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Serialize)]
enum IsTypeOp {
Null,
Bool,
Int,
Dbl,
Str,
Obj,
Res,
/// Int or Dbl or Str or Bool
Scalar,
Keyset,
Dict,
Vec,
/// Arr or Vec or Dict or Keyset
ArrLike,
ClsMeth,
Func,
LegacyArrLike,
Class,
}
#[repr(u8)]
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Serialize)]
enum FatalOp {
Runtime,
Parse,
RuntimeOmitFrame,
}
#[repr(u8)]
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Serialize)]
enum InitPropOp {
Static,
NonStatic,
}
#[repr(u8)]
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Serialize)]
enum SpecialClsRef {
SelfCls,
LateBoundCls,
ParentCls,
}
#[repr(u8)]
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Serialize)]
enum MOpMode {
None,
Warn,
Define,
Unset,
InOut,
}
#[repr(u8)]
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Serialize)]
enum QueryMOp {
CGet,
CGetQuiet,
Isset,
InOut,
}
#[repr(u8)]
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Serialize)]
enum TypeStructResolveOp {
Resolve,
DontResolve,
}
#[repr(u8)]
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Serialize)]
enum IsLogAsDynamicCallOp {
LogAsDynamicCall,
DontLogAsDynamicCall,
}
#[repr(u8)]
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Serialize)]
enum ReadonlyOp {
Any,
Readonly,
Mutable,
CheckROCOW,
CheckMutROCOW,
}
#[repr(u8)]
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Serialize)]
enum SetRangeOp {
Forward,
Reverse,
}
#[repr(u8)]
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Serialize)]
enum ContCheckOp {
IgnoreStarted,
CheckStarted,
}
#[repr(u8)]
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Serialize)]
enum SwitchKind {
Unbounded,
Bounded,
}
#[repr(u8)]
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Serialize)]
enum ObjMethodOp {
NullThrows,
NullSafe,
}
#[repr(u8)]
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Serialize)]
enum SilenceOp {
Start,
End,
}
#[repr(u8)]
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Serialize)]
enum BareThisOp {
Notice,
NoNotice,
NeverNull,
}
#[repr(u8)]
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Serialize)]
enum IncDecOp {
PreInc,
PostInc,
PreDec,
PostDec,
}
#[repr(u8)]
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Serialize)]
enum CollectionType {
Vector = 0x12,
Map = 0x13,
Set = 0x14,
Pair = 0x15,
ImmVector = 0x16,
ImmMap = 0x17,
ImmSet = 0x18,
}
#[repr(u8)]
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Serialize)]
enum SetOpOp {
PlusEqual,
MinusEqual,
MulEqual,
ConcatEqual,
DivEqual,
PowEqual,
ModEqual,
AndEqual,
OrEqual,
XorEqual,
SlEqual,
SrEqual,
}
#[repr(u8)]
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Serialize)]
enum OODeclExistsOp {
Class,
Interface,
Trait,
}
unsafe extern "C++" {
include!("hphp/hack/src/hackc/hhvm_cxx/hhvm_hhbc_defs/as-hhbc-ffi.h");
type BareThisOp;
type CollectionType;
type ContCheckOp;
type FatalOp;
type FCallArgsFlags;
type IncDecOp;
type InitPropOp;
type IsLogAsDynamicCallOp;
type IsTypeOp;
type MOpMode;
type ObjMethodOp;
type OODeclExistsOp;
type QueryMOp;
type ReadonlyOp;
type SetOpOp;
type SetRangeOp;
type SilenceOp;
type SpecialClsRef;
type SwitchKind;
type TypeStructResolveOp;
fn fcall_flags_to_string_ffi(flags: FCallArgsFlags) -> String;
}
}
use ffi::FCallArgsFlags;
impl FCallArgsFlags {
pub fn add(&mut self, flag: Self) {
self.repr = *self | flag
}
pub fn set(&mut self, flag: Self, b: bool) {
if b {
self.add(flag)
}
}
pub fn contains(&self, flag: Self) -> bool {
(*self & flag) != 0
}
}
impl BitOr for FCallArgsFlags {
type Output = u16;
fn bitor(self, other: Self) -> u16 {
self.repr | other.repr
}
}
impl BitOrAssign for FCallArgsFlags {
fn bitor_assign(&mut self, rhs: Self) {
self.repr |= rhs.repr;
}
}
impl BitAnd for FCallArgsFlags {
type Output = u16;
fn bitand(self, other: Self) -> u16 {
self.repr & other.repr
}
}
impl Default for FCallArgsFlags {
fn default() -> Self {
Self::FCANone
}
} |
C++ | hhvm/hphp/hack/src/hackc/hhvm_cxx/hhvm_types/as-base-ffi.cpp | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/hack/src/hackc/hhvm_cxx/hhvm_types/as-base-ffi.h"
namespace HPHP {
rust::String attrs_to_string_ffi(AttrContext ctx, Attr attrs) {
return attrs_to_string(ctx, attrs);
}
rust::String type_flags_to_string_ffi(TypeConstraintFlags flags) {
return type_flags_to_string(flags);
}
} // namespace HPHP |
C/C++ | hhvm/hphp/hack/src/hackc/hhvm_cxx/hhvm_types/as-base-ffi.h | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#pragma once
#include "hphp/runtime/base/type-structure-kinds.h"
#include "hphp/runtime/vm/as-base.h"
#include "hphp/runtime/vm/type-constraint-flags.h"
#include "rust/cxx.h"
namespace HPHP {
//////////////////////////////////////////////////////////////////////
/*
* This header contains routines linked into HackC.
*/
//////////////////////////////////////////////////////////////////////
/*
* Convert an attr to a string of space-separated attribute names, for
* a given context.
*/
rust::String attrs_to_string_ffi(AttrContext, Attr);
/*
* Convert a type flag to a string of space-separated type flag names.
*/
rust::String type_flags_to_string_ffi(TypeConstraintFlags);
} // namespace HPHP |
Rust | hhvm/hphp/hack/src/hackc/hhvm_cxx/hhvm_types/build.rs | use std::path::Path;
use std::path::PathBuf;
use std::process::Command;
fn main() {
// Assume the hack workspace 'fbcode/hphp/hack/src/Cargo.toml'.
let mut cargo_cmd = Command::new("cargo");
cargo_cmd.args(&["locate-project", "--workspace", "--message-format=plain"]);
let output = cargo_cmd.output().unwrap().stdout;
let hphp = Path::new(std::str::from_utf8(&output).unwrap().trim())
.ancestors()
.nth(3)
.unwrap();
let fbcode = hphp.parent().unwrap();
let files = vec![
PathBuf::from("hhvm_types_ffi.rs"),
PathBuf::from("as-base-ffi.cpp"),
PathBuf::from("as-base-ffi.h"),
hphp.join("runtime/vm/as-base.cpp"),
hphp.join("runtime/vm/as-base.h"),
];
cxx_build::bridge("hhvm_types_ffi.rs")
.files(files.iter().filter(is_cpp))
.include(fbcode)
.cpp(true)
.flag("-std=c++17")
.compile("hhvm_types_ffi");
files.iter().for_each(rerun_if_changed);
rerun_if_changed("build.rs");
}
fn rerun_if_changed<P: AsRef<Path>>(f: P) {
println!("cargo:rerun-if-changed={}", f.as_ref().to_str().unwrap());
}
fn is_cpp<P: AsRef<Path>>(path: &P) -> bool {
path.as_ref().extension().map_or(false, |e| e == "cpp")
} |
TOML | hhvm/hphp/hack/src/hackc/hhvm_cxx/hhvm_types/Cargo.toml | # @generated by autocargo
[package]
name = "hhvm_types_ffi"
version = "0.0.0"
edition = "2021"
[lib]
path = "hhvm_types_ffi.rs"
crate-type = ["lib", "staticlib"]
[dependencies]
cxx = "1.0.100"
oxidized = { version = "0.0.0", path = "../../../oxidized" }
serde = { version = "1.0.176", features = ["derive", "rc"] }
[build-dependencies]
cxx-build = "1.0.100" |
Rust | hhvm/hphp/hack/src/hackc/hhvm_cxx/hhvm_types/hhvm_types_ffi.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::ops::BitAnd;
use std::ops::BitAndAssign;
use std::ops::BitOr;
use std::ops::Sub;
use std::ops::SubAssign;
#[allow(unreachable_patterns)]
#[cxx::bridge(namespace = "HPHP")]
pub mod ffi {
// This is not a real definition. Cxx just adds static asserts on each of these enum variants
// that they match the definition in attr.h.
#[repr(u32)]
#[derive(Debug, Copy, Clone, Serialize)]
pub enum Attr {
AttrNone = 0x0,
AttrForbidDynamicProps = 0x1,
AttrDeepInit = 0x1,
AttrPublic = 0x2,
AttrProtected = 0x4,
AttrPrivate = 0x8,
AttrEnum = 0x10,
AttrSystemInitialValue = 0x20,
AttrNoImplicitNullable = 0x40,
AttrStatic = 0x10,
AttrAbstract = 0x20,
AttrFinal = 0x40,
AttrInterface = 0x80,
AttrLSB = 0x80,
AttrSupportsAsyncEagerReturn = 0x80,
AttrTrait = 0x100,
AttrNoInjection = 0x200,
AttrInitialSatisfiesTC = 0x200,
AttrNoBadRedeclare = 0x400,
AttrInterceptable = 0x800,
AttrSealed = 0x800,
AttrLateInit = 0x800,
AttrNoExpandTrait = 0x1000,
AttrNoOverride = 0x2000,
AttrIsReadonly = 0x4000,
AttrReadonlyThis = 0x4000,
AttrReadonlyReturn = 0x8000,
AttrInternal = 0x10000,
AttrInternalSoft = 0x20000,
AttrPersistent = 0x40000,
AttrDynamicallyCallable = 0x80000,
AttrDynamicallyConstructible = 0x80000,
AttrBuiltin = 0x100000,
AttrIsConst = 0x200000,
AttrNoReifiedInit = 0x800000,
AttrIsMethCaller = 0x1000000,
AttrIsClosureClass = 0x1000000,
AttrHasClosureCoeffectsProp = 0x2000000,
AttrHasCoeffectRules = 0x2000000,
AttrIsFoldable = 0x4000000,
AttrNoFCallBuiltin = 0x8000000,
AttrVariadicParam = 0x10000000,
AttrProvenanceSkipFrame = 0x20000000,
AttrEnumClass = 0x40000000,
AttrUnusedMaxAttr = 0x80000000,
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Serialize)]
enum AttrContext {
Class = 0x1,
Func = 0x2,
Prop = 0x4,
TraitImport = 0x8,
Alias = 0x10,
Parameter = 0x20,
Constant = 0x40,
Module = 0x80,
}
#[repr(u16)]
#[derive(Debug, Copy, Clone, Hash, Serialize)]
enum TypeConstraintFlags {
NoFlags = 0x0,
Nullable = 0x1,
ExtendedHint = 0x4,
TypeVar = 0x8,
Soft = 0x10,
TypeConstant = 0x20,
Resolved = 0x40,
DisplayNullable = 0x100,
UpperBound = 0x200,
}
#[repr(u8)]
#[derive(Debug, Copy, Clone, Hash, Serialize)]
enum TypeStructureKind {
T_void = 0,
T_int = 1,
T_bool = 2,
T_float = 3,
T_string = 4,
T_resource = 5,
T_num = 6,
T_arraykey = 7,
T_noreturn = 8,
T_mixed = 9,
T_tuple = 10,
T_fun = 11,
T_typevar = 13, // corresponds to user OF_GENERIC
T_shape = 14,
// These values are only used after resolution in ext_reflection.cpp
T_class = 15,
T_interface = 16,
T_trait = 17,
T_enum = 18,
// Hack array types
T_dict = 19,
T_vec = 20,
T_keyset = 21,
T_vec_or_dict = 22,
T_nonnull = 23,
T_darray = 24,
T_varray = 25,
T_varray_or_darray = 26,
T_any_array = 27,
T_null = 28,
T_nothing = 29,
T_dynamic = 30,
T_union = 31,
// The following kinds needs class/alias resolution, and
// are generally not exposed to the users.
// Unfortunately this is a bit leaky, and a few of these are needed by tooling.
T_unresolved = 101,
T_typeaccess = 102,
T_xhp = 103,
T_reifiedtype = 104,
}
unsafe extern "C++" {
include!("hphp/hack/src/hackc/hhvm_cxx/hhvm_types/as-base-ffi.h");
type Attr;
type AttrContext;
type TypeConstraintFlags;
type TypeStructureKind;
fn attrs_to_string_ffi(ctx: AttrContext, attrs: Attr) -> String;
fn type_flags_to_string_ffi(flags: TypeConstraintFlags) -> String;
}
}
use ffi::type_flags_to_string_ffi;
pub use ffi::Attr;
pub use ffi::TypeConstraintFlags;
pub use ffi::TypeStructureKind;
impl Default for TypeConstraintFlags {
fn default() -> Self {
TypeConstraintFlags::NoFlags
}
}
impl std::fmt::Display for TypeConstraintFlags {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", type_flags_to_string_ffi(*self))
}
}
impl TypeConstraintFlags {
pub fn is_empty(&self) -> bool {
*self == TypeConstraintFlags::NoFlags
}
pub fn contains(&self, flag: Self) -> bool {
(self.repr & flag.repr) != 0
}
}
impl BitOr for TypeConstraintFlags {
type Output = Self;
fn bitor(self, other: Self) -> Self {
Self {
repr: (self.repr | other.repr),
}
}
}
impl BitAnd for TypeConstraintFlags {
type Output = Self;
fn bitand(self, other: Self) -> Self {
TypeConstraintFlags {
repr: self.repr & other.repr,
}
}
}
impl BitAndAssign for TypeConstraintFlags {
fn bitand_assign(&mut self, rhs: Self) {
self.repr &= rhs.repr;
}
}
impl Sub for TypeConstraintFlags {
type Output = Self;
fn sub(self, other: Self) -> Self {
Self {
repr: self.repr & !other.repr,
}
}
}
impl SubAssign for TypeConstraintFlags {
fn sub_assign(&mut self, other: Self) {
// For flags subtract just drops the bits.
self.repr &= !other.repr;
}
}
impl From<&TypeConstraintFlags> for u16 {
fn from(r: &TypeConstraintFlags) -> Self {
r.repr
}
}
impl From<TypeStructureKind> for i64 {
fn from(r: TypeStructureKind) -> Self {
r.repr as i64
}
}
impl From<u32> for Attr {
fn from(r: u32) -> Self {
Self { repr: r }
}
}
impl From<oxidized::ast_defs::Visibility> for Attr {
fn from(k: oxidized::ast_defs::Visibility) -> Self {
use oxidized::ast_defs::Visibility;
match k {
Visibility::Private => Self::AttrPrivate,
Visibility::Public => Self::AttrPublic,
Visibility::Protected => Self::AttrProtected,
// TODO(T115356820): Decide whether internal should be mutually
// exclusive with other visibility modifiers or it should be a
// modifier on top the others.
// In order to unblock typechecker, let it be a modifier on top for now.
Visibility::Internal => Self::AttrInternal | Self::AttrPublic,
}
}
}
impl From<&oxidized::ast_defs::Visibility> for Attr {
fn from(k: &oxidized::ast_defs::Visibility) -> Self {
use oxidized::ast_defs::Visibility;
match k {
Visibility::Private => Self::AttrPrivate,
Visibility::Public => Self::AttrPublic,
Visibility::Protected => Self::AttrProtected,
// TODO(T115356820): Decide whether internal should be mutually
// exclusive with other visibility modifiers or it should be a
// modifier on top the others.
// In order to unblock typechecker, let it be a modifier on top for now.
Visibility::Internal => Self::AttrInternal | Self::AttrPublic,
}
}
}
impl From<Attr> for u32 {
fn from(attr: Attr) -> Self {
attr.repr
}
}
impl Attr {
pub fn add(&mut self, attr: Attr) {
*self = *self | attr
}
pub fn remove(&mut self, attr: Attr) {
self.repr &= !attr.repr;
}
pub fn contains(&self, attr: Attr) -> bool {
(self.repr & attr.repr) == attr.repr
}
pub fn set(&mut self, attr: Attr, b: bool) {
if b {
self.add(attr)
}
}
pub fn clear(&mut self, attr: Attr) {
self.repr &= !attr.repr;
}
pub fn is_enum(&self) -> bool {
(*self & Self::AttrEnum) != Self::AttrNone
}
pub fn is_internal(&self) -> bool {
(*self & Self::AttrInternal) != Self::AttrNone
}
pub fn is_public(&self) -> bool {
(*self & Self::AttrPublic) != Self::AttrNone
}
pub fn is_private(&self) -> bool {
(*self & Self::AttrPrivate) != Self::AttrNone
}
pub fn is_protected(&self) -> bool {
(*self & Self::AttrProtected) != Self::AttrNone
}
pub fn is_final(&self) -> bool {
(*self & Self::AttrFinal) != Self::AttrNone
}
pub fn is_sealed(&self) -> bool {
(*self & Self::AttrSealed) != Self::AttrNone
}
pub fn is_abstract(&self) -> bool {
(*self & Self::AttrAbstract) != Self::AttrNone
}
pub fn is_interface(&self) -> bool {
(*self & Self::AttrInterface) != Self::AttrNone
}
pub fn is_trait(&self) -> bool {
(*self & Self::AttrTrait) != Self::AttrNone
}
pub fn is_const(&self) -> bool {
(*self & Self::AttrIsConst) != Self::AttrNone
}
pub fn no_dynamic_props(&self) -> bool {
(*self & Self::AttrForbidDynamicProps) != Self::AttrNone
}
pub fn needs_no_reifiedinit(&self) -> bool {
(*self & Self::AttrNoReifiedInit) != Self::AttrNone
}
pub fn is_late_init(&self) -> bool {
(*self & Self::AttrLateInit) != Self::AttrNone
}
pub fn is_no_bad_redeclare(&self) -> bool {
(*self & Self::AttrNoBadRedeclare) != Self::AttrNone
}
pub fn initial_satisfies_tc(&self) -> bool {
(*self & Self::AttrInitialSatisfiesTC) != Self::AttrNone
}
pub fn no_implicit_null(&self) -> bool {
(*self & Self::AttrNoImplicitNullable) != Self::AttrNone
}
pub fn has_system_initial(&self) -> bool {
(*self & Self::AttrSystemInitialValue) != Self::AttrNone
}
pub fn is_deep_init(&self) -> bool {
(*self & Self::AttrDeepInit) != Self::AttrNone
}
pub fn is_lsb(&self) -> bool {
(*self & Self::AttrLSB) != Self::AttrNone
}
pub fn is_static(&self) -> bool {
(*self & Self::AttrStatic) != Self::AttrNone
}
pub fn is_readonly(&self) -> bool {
(*self & Self::AttrIsReadonly) != Self::AttrNone
}
pub fn is_no_injection(&self) -> bool {
(*self & Self::AttrNoInjection) != Self::AttrNone
}
pub fn is_interceptable(&self) -> bool {
(*self & Self::AttrInterceptable) != Self::AttrNone
}
pub fn is_empty(&self) -> bool {
*self == Self::AttrNone
}
}
impl SubAssign for Attr {
fn sub_assign(&mut self, other: Self) {
// For flags subtract just drops the bits.
self.repr &= !other.repr;
}
}
impl BitOr for Attr {
type Output = Self;
fn bitor(self, other: Self) -> Self {
Self {
repr: self.repr | other.repr,
}
}
}
impl BitOr<Attr> for u32 {
type Output = u32;
fn bitor(self, other: Attr) -> u32 {
self | other.repr
}
}
impl BitAnd for Attr {
type Output = Self;
fn bitand(self, other: Self) -> Self {
Self {
repr: self.repr & other.repr,
}
}
}
impl BitAnd<u32> for Attr {
type Output = u32;
fn bitand(self, other: u32) -> u32 {
self.repr & other
}
}
impl BitAndAssign for Attr {
fn bitand_assign(&mut self, rhs: Self) {
self.repr &= rhs.repr;
}
} |
TOML | hhvm/hphp/hack/src/hackc/ir/Cargo.toml | # @generated by autocargo
[package]
name = "ir"
version = "0.0.0"
edition = "2021"
[lib]
path = "lib.rs"
[dependencies]
analysis = { version = "0.0.0", path = "analysis" }
assemble_ir = { version = "0.0.0", path = "assemble" }
ir_core = { version = "0.0.0", path = "ir_core" }
passes = { version = "0.0.0", path = "passes" }
print = { version = "0.0.0", path = "print" }
verify = { version = "0.0.0", path = "verify" }
[dev-dependencies]
testutils = { version = "0.0.0", path = "testutils" } |
Rust | hhvm/hphp/hack/src/hackc/ir/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 analysis;
pub use assemble_ir as assemble;
pub use ir_core::*;
pub use passes;
pub use print;
pub use print::print_unit;
#[cfg(test)]
pub use testutils;
pub use verify; |
TOML | hhvm/hphp/hack/src/hackc/ir/analysis/Cargo.toml | # @generated by autocargo
[package]
name = "analysis"
version = "0.0.0"
edition = "2021"
[lib]
path = "lib.rs"
[dependencies]
ir_core = { version = "0.0.0", path = "../ir_core" }
itertools = "0.10.3"
newtype = { version = "0.0.0", path = "../../../utils/newtype" }
print = { version = "0.0.0", path = "../print" } |
Rust | hhvm/hphp/hack/src/hackc/ir/analysis/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 mod liveness;
pub mod predecessors;
pub mod rpo;
pub use liveness::LiveInstrs;
pub use predecessors::compute_num_predecessors;
pub use predecessors::compute_predecessor_blocks;
pub use predecessors::PredecessorCatchMode;
pub use predecessors::PredecessorFlags;
pub use predecessors::Predecessors;
pub use rpo::compute_rpo;
pub use rpo::compute_rrpo; |
Rust | hhvm/hphp/hack/src/hackc/ir/analysis/liveness.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.
// Everything you want to know about what InstrIds are alive when.
use std::collections::VecDeque;
use ir_core::instr::HasOperands;
use ir_core::BlockId;
use ir_core::BlockIdMap;
use ir_core::BlockIdSet;
use ir_core::Func;
use ir_core::InstrId;
use ir_core::InstrIdSet;
use ir_core::ValueId;
use itertools::Itertools;
use newtype::IdVec;
use crate::PredecessorCatchMode;
use crate::PredecessorFlags;
/// Used to compute the set of live InstrIds across a Func.
pub struct LiveInstrs {
/// This is a list of where a given InstrId dies. It's a set because an
/// InstrId could end its lifetime in multiple blocks.
pub instr_last_use: IdVec<InstrId, InstrIdSet>,
/// This is the inverse of instr_last_use - for a given InstrId what
/// InstrIds have their last use there.
pub instrs_dead_at: IdVec<InstrId, InstrIdSet>,
/// Per-block liveness information.
pub blocks: IdVec<BlockId, LiveBlockInfo>,
}
impl std::fmt::Debug for LiveInstrs {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
use std::fmt::Display;
use print::FmtRawVid;
use print::FmtSep;
writeln!(f, "instr_last_use: {{")?;
for (vid, v) in self.instr_last_use.iter().enumerate() {
writeln!(
f,
" {vid} => ({}),",
FmtSep::comma(v.iter(), |f, i| { Display::fmt(&i, f) })
)?;
}
writeln!(f, "}},")?;
writeln!(f, "instrs_dead_at: {{")?;
for (vid, v) in self.instrs_dead_at.iter().enumerate() {
writeln!(
f,
" {vid} => [{}],",
FmtSep::comma(v.iter(), |f, i| { Display::fmt(&i, f) })
)?;
}
writeln!(f, "}},")?;
writeln!(f, "blocks: {{")?;
for (bid, bi) in self.blocks.iter().enumerate() {
writeln!(
f,
" {bid} => {{ entry: [{entry}], dead_on_entry: [{doe}], exit: [{exit}] }}",
entry = FmtSep::comma(bi.entry.iter(), |f, i| {
FmtRawVid(ValueId::from_instr(*i)).fmt(f)
}),
doe = FmtSep::comma(bi.dead_on_entry.iter(), |f, i| {
FmtRawVid(ValueId::from_instr(*i)).fmt(f)
}),
exit = FmtSep::comma(bi.exit.iter(), |f, i| {
FmtRawVid(ValueId::from_instr(*i)).fmt(f)
}),
)?;
}
writeln!(f, "}}")
}
}
impl LiveInstrs {
pub fn compute(func: &Func<'_>) -> Self {
let mut live = LiveInstrs {
instr_last_use: IdVec::new_from_vec(vec![Default::default(); func.instrs_len()]),
instrs_dead_at: IdVec::new_from_vec(vec![Default::default(); func.instrs_len()]),
blocks: IdVec::new_from_vec(vec![Default::default(); func.blocks.len()]),
};
// Start by computing what InstrIds are introduced and referenced in
// each block.
for bid in func.block_ids() {
live.compute_referenced(func, bid);
}
let predecessor_blocks = crate::compute_predecessor_blocks(
func,
PredecessorFlags {
mark_entry_blocks: false,
catch: PredecessorCatchMode::Throw,
},
);
// Next compute the entry and exit InstrIds for each block.
//
// Because we'll add stuff back to the work queue as necessary this
// doesn't actually have to start in post-order - it's just more
// efficient.
let mut work: VecDeque<BlockId> = func.block_ids().rev().collect_vec().into();
while let Some(bid) = work.pop_front() {
live.compute_exit(&mut work, func, &predecessor_blocks, bid);
}
// At this point LiveBlockInfo::exit is correct but LiveBlockInfo::entry
// may be wrong (although it will be 'close')! This is because
// LiveBlockInfo::entry needs to be recomputed from all the
// LiveBlockInfo::exit values - in case one successor expanded the exit
// of a predecessor (see the example at the end of
// compute_instr_use_by_block()).
for bid in func.block_ids() {
live.expand_entry(func, bid);
}
// Finally compute where each instruction is last used.
for bid in func.block_ids() {
live.compute_instr_use_by_block(func, bid);
}
live
}
fn compute_referenced(&mut self, func: &Func<'_>, bid: BlockId) {
// Nothing in self is valid here.
let block_info = &mut self.blocks[bid];
block_info.referenced = func
.block(bid)
.iids()
.flat_map(|iid| {
func.instr(iid)
.operands()
.iter()
.copied()
.filter_map(ValueId::instr)
})
.collect();
// At this point LiveBlockInfo::referenced is correct for this
// block.
}
// Go through `bid` and figure out which InstrIds are referenced and live on
// exit but not created in this block - those must be live on entry. If this
// changes our callers' exit then we need to recompute our callers.
fn compute_exit(
&mut self,
work: &mut VecDeque<BlockId>,
func: &Func<'_>,
predecessor_blocks: &BlockIdMap<BlockIdSet>,
bid: BlockId,
) {
// At this point:
// - LiveBlockInfo::referenced is correct for all blocks.
// - The LiveBlockInfo::exit is a subset of the "correct" info (we loop
// until we hit a steady state).
let block_info = &self.blocks[bid];
let created: InstrIdSet = func
.block(bid)
.iids()
.chain(func.block(bid).params.iter().copied())
.collect();
let entry = &(&block_info.exit | &block_info.referenced) - &created;
for &src in &predecessor_blocks[&bid] {
let exit = &mut self.blocks[src].exit;
let old = exit.len();
exit.extend(entry.iter().copied());
if exit.len() != old {
work.push_back(src);
}
}
self.blocks[bid].entry = entry;
// At this point:
// - LiveBlockInfo::entry is an accurate reflection of LiveBlockInfo::exit.
// - If we changed LiveBlockInfo::exit for our callers we've added them
// back onto the work list.
}
fn expand_entry(&mut self, func: &Func<'_>, bid: BlockId) {
let exit = self.blocks[bid].exit.clone();
for &edge in func.edges(bid) {
self.blocks[edge].entry.extend(exit.iter().copied());
}
let catch_bid = func.catch_target(bid);
if catch_bid != BlockId::NONE {
self.blocks[catch_bid].entry.extend(exit.iter().copied());
}
}
fn compute_instr_use_by_block(&mut self, func: &Func<'_>, bid: BlockId) {
// At this point:
// - LiveBlockInfo is correct for all blocks.
// We start with the InstrIds that are live on block exit and walk
// backward through the block.
let block = func.block(bid);
let mut live = self.blocks[bid].exit.clone();
for iid in block.iids().rev() {
if !live.remove(&iid) {
// This InstrId was both created and last live at this point.
self.instr_last_use[iid].insert(iid);
self.instrs_dead_at[iid].insert(iid);
}
for &op in func.instr(iid).operands() {
if let Some(op) = op.instr() {
if live.insert(op) {
// If we're just seeing this ValueId for the first time then
// this must be where the ValueId is last used.
self.instr_last_use[op].insert(iid);
self.instrs_dead_at[iid].insert(op);
}
}
}
}
let mostly_dead = {
let mut s: InstrIdSet = self.blocks[bid].entry.clone();
s.extend(func.block(bid).params.iter());
s.retain(|item| !live.contains(item));
s
};
if !mostly_dead.is_empty() {
// Anything in entry or params that isn't in live needs to be marked
// dead at our start (note that this includes block params)! This
// can happen like this:
//
// b0:
// %1 = call...
// %2 = jmp if zero %1 b1 else b2
// b1:
// %3 = call(%1)
// %4 = jmp b3
// b2:
// %5 = jmp b3
// b3:
// %6 = ret
//
// Where would %1 die? It can't be %2 because it's used after that
// in b1. It can't be %6 because it dies long before that. It needs
// to be at %3 and %5 - but b2 never actually sees a use of %1 so it
// doesn't know that it dies there.
// Mark it dead at the first InstrId of the block (an argument
// could be made for doing it at the terminal as well).
let dead_at = *block.iids.first().unwrap();
for &iid in &mostly_dead {
self.instr_last_use[iid].insert(dead_at);
}
self.instrs_dead_at[dead_at].extend(&mostly_dead);
self.blocks[bid].dead_on_entry = mostly_dead;
}
}
}
/// Information about what InstrIds are live at different points in a block.
/// The relationship is:
///
/// entry - dead_on_entry - referenced = exit
///
/// dead_on_entry and referenced are mutually exclusive - no InstrId should
/// appear in both sets.
///
#[derive(Debug, Default, Clone)]
pub struct LiveBlockInfo {
/// What InstrIds are live on entry to this block.
pub entry: InstrIdSet,
/// What InstrIds are live on exit from this block.
pub exit: InstrIdSet,
/// What InstrIds are referenced by this block.
pub referenced: InstrIdSet,
/// What InstrIds are dead immediately on block entry.
pub dead_on_entry: InstrIdSet,
} |
Rust | hhvm/hphp/hack/src/hackc/ir/analysis/predecessors.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 ir_core::BlockId;
use ir_core::BlockIdMap;
use ir_core::BlockIdSet;
use ir_core::Func;
use newtype::IdVec;
pub type Predecessors = BlockIdMap<BlockIdSet>;
/// Compute the predecessor Blocks for a Func's Blocks.
///
/// For every Block in the Func compute the Block's predecessors.
///
/// The result is guaranteed to have an entry for every known block, even if it
/// has no predecessors.
pub fn compute_predecessor_blocks(func: &Func<'_>, flags: PredecessorFlags) -> Predecessors {
let mut predecessors: Predecessors = Default::default();
if flags.mark_entry_blocks {
// Insert BlockId::NONE as a source of ENTRY_BID to indicate that it's
// called externally.
mark_edge(&mut predecessors, BlockId::NONE, Func::ENTRY_BID);
// Handle the default params.
for param in &func.params {
if let Some(dv) = param.default_value {
mark_edge(&mut predecessors, BlockId::NONE, dv.init);
}
}
}
for bid in func.block_ids() {
predecessors.entry(bid).or_default();
for &target_bid in func.edges(bid) {
mark_edge(&mut predecessors, bid, target_bid);
}
flags.catch.mark(&mut predecessors, func, bid);
}
predecessors
}
#[derive(Clone, Copy, Eq, PartialEq)]
pub enum PredecessorCatchMode {
// Don't mark catch blocks with any source.
Ignore,
// Mark catch blocks with a predecessor of BlockId::NONE
FromNone,
// Mark catch blocks with a predecessor of potential throwers.
Throw,
}
impl Default for PredecessorCatchMode {
fn default() -> Self {
Self::Ignore
}
}
impl PredecessorCatchMode {
fn mark(self, predecessors: &mut Predecessors, func: &Func<'_>, mut src: BlockId) {
if self == PredecessorCatchMode::Ignore {
return;
}
let dst = func.catch_target(src);
if dst == BlockId::NONE {
return;
}
if self == PredecessorCatchMode::FromNone {
src = BlockId::NONE;
}
mark_edge(predecessors, src, dst);
}
}
#[derive(Default)]
pub struct PredecessorFlags {
// If mark_entry_blocks is true then blocks that can be called from outside
// the function (such as the entry block and default value blocks) will be
// marked as having a predecessor of BlockId::NONE.
pub mark_entry_blocks: bool,
pub catch: PredecessorCatchMode,
}
fn mark_edge(predecessors: &mut Predecessors, src: BlockId, dst: BlockId) {
predecessors.entry(dst).or_default().insert(src);
}
/// Compute the number of incoming control-flow edges to each block. If there are no
/// critical edges, this is also the number of predecessor blocks.
pub fn compute_num_predecessors(func: &Func<'_>, flags: PredecessorFlags) -> IdVec<BlockId, u32> {
let mut counts = IdVec::new_from_vec(vec![0; func.blocks.len()]);
if flags.mark_entry_blocks {
// Entry
counts[BlockId::NONE] += 1;
// Default Params
for param in &func.params {
if let Some(dv) = param.default_value {
counts[dv.init] += 1;
}
}
}
let note_catch = !matches!(flags.catch, PredecessorCatchMode::Ignore);
for bid in func.block_ids() {
for &target in func.edges(bid) {
counts[target] += 1;
}
if note_catch {
let dst = func.catch_target(bid);
if dst != BlockId::NONE {
counts[dst] += 1;
}
}
}
counts
} |
Rust | hhvm/hphp/hack/src/hackc/ir/analysis/rpo.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 ir_core::BlockId;
use ir_core::Func;
use newtype::IdVec;
/// Compute the Block post-order for a Func. In the returned Vec a BlockId will
/// appear after all of its successors.
pub fn compute_po(func: &Func<'_>) -> Vec<BlockId> {
compute_general_po(func, |edges| edges.split_last())
}
/// Compute the Block reverse-post-order for a Func. In the retuned Vec a
/// BlockId will appear before any of its successors.
pub fn compute_rpo(func: &Func<'_>) -> Vec<BlockId> {
let mut po = compute_general_po(func, |edges| edges.split_last());
po.reverse();
po
}
/// Compute reversed rpo, which is rpo of a dfs that walks children in
/// the opposite order that ordinary rpo does. This is useful for
/// varying rpo traversal order when doing a fixed point computation
/// such as dominators to avoid quadratic corner cases.
pub fn compute_rrpo(func: &Func<'_>) -> Vec<BlockId> {
// Note that we're spliting by first whereas compute_rpo() splits by last...
let mut po = compute_general_po(func, |edges| edges.split_first());
po.reverse();
po
}
fn compute_general_po(
func: &Func<'_>,
splitter: impl Fn(&[BlockId]) -> Option<(&BlockId, &[BlockId])>,
) -> Vec<BlockId> {
let blocks = &func.blocks;
let mut result = Vec::with_capacity(blocks.len());
if blocks.is_empty() {
return result;
}
// Use an explicit recursion stack seeded with the entry block to avoid
// blowing the program stack recursing through a large Func.
let mut stack = Vec::new();
let mut already_pushed = IdVec::new_from_vec(vec![false; blocks.len()]);
mark_block(&mut stack, &mut already_pushed, func, Func::ENTRY_BID);
for param in &func.params {
if let Some(dv) = param.default_value.as_ref() {
mark_block(&mut stack, &mut already_pushed, func, dv.init);
}
}
fn mark_block<'a>(
stack: &mut Vec<(BlockId, &'a [BlockId], BlockId)>,
already_pushed: &mut [bool],
func: &'a Func<'a>,
bid: BlockId,
) {
let edges = func.edges(bid);
let catch_bid = func.catch_target(bid);
stack.push((bid, edges, catch_bid));
already_pushed[bid.as_usize()] = true;
}
fn process_child<'a>(
func: &'a Func<'_>,
stack: &mut Vec<(BlockId, &'a [BlockId], BlockId)>,
already_pushed: &mut IdVec<BlockId, bool>,
bid: BlockId,
parent: (BlockId, &'a [BlockId], BlockId),
) -> bool {
let was_pushed = &mut already_pushed[bid];
if *was_pushed {
return false;
}
*was_pushed = true;
// Remember to revisit the parent once this child is done.
stack.push(parent);
let child_edges = func.edges(bid);
let child_catch_bid = func.catch_target(bid);
stack.push((bid, child_edges, child_catch_bid));
true
}
'outer: while let Some((bid, mut edges, catch_bid)) = stack.pop() {
while !edges.is_empty() {
let (&child_bid, next_edges) = splitter(edges).unwrap();
edges = next_edges;
let parent = (bid, edges, catch_bid);
if process_child(func, &mut stack, &mut already_pushed, child_bid, parent) {
continue 'outer;
}
}
// If this is the 'try' for a try/catch block then add a fake edge to
// the catch block.
if catch_bid != BlockId::NONE {
let parent = (bid, &[] as &[BlockId], BlockId::NONE);
if process_child(func, &mut stack, &mut already_pushed, catch_bid, parent) {
continue;
}
}
// All successors were visited, so record this block (i.e. "postorder").
result.push(bid);
}
result
} |
Rust | hhvm/hphp/hack/src/hackc/ir/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::io::Read;
use std::path::Path;
use std::sync::Arc;
use anyhow::Context;
use anyhow::Result;
use bumpalo::Bump;
use ir_core::ClassId;
use ir_core::ClassName;
use ir_core::ConstName;
use ir_core::Fatal;
use ir_core::Function;
use ir_core::FunctionName;
use ir_core::IncludePath;
use ir_core::Method;
use ir_core::MethodId;
use ir_core::Module;
use ir_core::SrcLoc;
use ir_core::StringInterner;
use ir_core::Typedef;
use ir_core::Unit;
use parse_macro_ir::parse;
use crate::parse::parse_attr;
use crate::parse::parse_attribute;
use crate::parse::parse_attributes;
use crate::parse::parse_class_id;
use crate::parse::parse_comma_list;
use crate::parse::parse_doc_comment;
use crate::parse::parse_fatal_op;
use crate::parse::parse_hack_constant;
use crate::parse::parse_src_loc;
use crate::parse::parse_type_info;
use crate::parse::parse_typed_value;
use crate::parse::parse_user_id;
use crate::tokenizer::Tokenizer;
pub fn unit_from_path<'a>(
path: &Path,
strings: Arc<StringInterner>,
alloc: &'a Bump,
) -> Result<Unit<'a>> {
use std::fs::File;
let mut file = File::open(path)?;
read_unit(&mut file, &format!("{}", path.display()), strings, alloc)
}
pub fn unit_from_string<'a>(
input: &str,
strings: Arc<StringInterner>,
alloc: &'a Bump,
) -> Result<Unit<'a>> {
let mut input = input.as_bytes();
read_unit(&mut input, "<string>", strings, alloc)
}
pub fn read_unit<'a>(
read: &mut dyn Read,
filename: &str,
strings: Arc<StringInterner>,
alloc: &'a Bump,
) -> Result<Unit<'a>> {
let mut tokenizer = Tokenizer::new(read, filename, strings);
let unit = UnitParser::parse(&mut tokenizer, alloc)?;
Ok(unit)
}
pub(crate) struct UnitParser<'a> {
pub(crate) alloc: &'a Bump,
pub(crate) unit: Unit<'a>,
pub(crate) src_loc: Option<SrcLoc>,
}
impl<'a> UnitParser<'a> {
pub(crate) fn get_cur_src_loc(&self) -> SrcLoc {
self.src_loc.as_ref().cloned().unwrap_or_default()
}
}
impl<'a> UnitParser<'a> {
fn parse(tokenizer: &mut Tokenizer<'_>, alloc: &'a Bump) -> Result<Unit<'a>> {
let strings = Arc::clone(&tokenizer.strings);
let mut state = UnitParser {
alloc,
unit: Unit {
strings,
..Default::default()
},
src_loc: None,
};
while let Some(next) = tokenizer.read_token()? {
if next.is_eol() {
continue;
}
let res = match next.identifier() {
".class_ref" => state.parse_class_ref(tokenizer),
".const_ref" => state.parse_const_ref(tokenizer),
".fatal" => state.parse_fatal(tokenizer),
".func_ref" => state.parse_func_ref(tokenizer),
".include_ref" => state.parse_include_ref(tokenizer),
".srcloc" => state.parse_src_loc(tokenizer),
"attribute" => state.parse_file_attribute(tokenizer),
"class" => state.parse_class(tokenizer),
"constant" => state.parse_constant(tokenizer),
"function" => state.parse_function(tokenizer),
"method" => state.parse_method(tokenizer),
"module" => state.parse_module(tokenizer),
"module_use" => state.parse_module_use(tokenizer),
"typedef" => state.parse_typedef(tokenizer),
_ => Err(next.bail(format!("Unexpected token '{next}' in input"))),
};
res.with_context(|| format!("Parsing {}", next))?;
}
Ok(state.unit)
}
fn parse_file_attribute(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<()> {
let a = crate::parse::parse_attribute(tokenizer)?;
self.unit.file_attributes.push(a);
Ok(())
}
fn parse_class(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<()> {
let c = crate::class::ClassParser::parse(tokenizer, self)?;
self.unit.classes.push(c);
Ok(())
}
fn parse_class_ref(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<()> {
let (id, _) = parse_user_id(tokenizer)?;
self.unit
.symbol_refs
.classes
.push(ClassName::from_bytes(self.alloc, &id));
Ok(())
}
fn parse_const_ref(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<()> {
let (id, _) = parse_user_id(tokenizer)?;
self.unit
.symbol_refs
.constants
.push(ConstName::from_bytes(self.alloc, &id));
Ok(())
}
fn parse_constant(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<()> {
let c = parse_hack_constant(tokenizer)?;
self.unit.constants.push(c);
Ok(())
}
fn parse_fatal(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<()> {
let loc = self.get_cur_src_loc();
let op = parse_fatal_op(tokenizer)?;
let message = tokenizer.expect_any_string()?;
let message = message.unescaped_string()?;
let message = bstr::BString::from(message);
self.unit.fatal = Some(Fatal { op, message, loc });
Ok(())
}
fn parse_func_ref(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<()> {
let (id, _) = parse_user_id(tokenizer)?;
self.unit
.symbol_refs
.functions
.push(FunctionName::from_bytes(self.alloc, &id));
Ok(())
}
fn parse_include_ref(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<()> {
let incref = if tokenizer.next_is_identifier("relative")? {
let a = tokenizer
.expect_any_string()?
.unescaped_bump_str(self.alloc)?;
IncludePath::SearchPathRelative(a)
} else if tokenizer.next_is_identifier("rooted")? {
let a = tokenizer
.expect_any_string()?
.unescaped_bump_str(self.alloc)?;
let b = tokenizer
.expect_any_string()?
.unescaped_bump_str(self.alloc)?;
IncludePath::IncludeRootRelative(a, b)
} else if tokenizer.next_is_identifier("doc")? {
let a = tokenizer
.expect_any_string()?
.unescaped_bump_str(self.alloc)?;
IncludePath::DocRootRelative(a)
} else {
let a = tokenizer
.expect_any_string()?
.unescaped_bump_str(self.alloc)?;
IncludePath::Absolute(a)
};
self.unit.symbol_refs.includes.push(incref);
Ok(())
}
fn parse_function(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<()> {
let f = crate::func::FunctionParser::parse(tokenizer, self, None)?;
self.unit.functions.push(f);
Ok(())
}
fn parse_method(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<()> {
let (clsname, clsloc) = parse_user_id(tokenizer)?;
let clsid = ClassId::from_bytes(&clsname, &self.unit.strings);
tokenizer.expect_identifier("::")?;
let mut cs = crate::func::ClassState::default();
let f = crate::func::FunctionParser::parse(tokenizer, self, Some(&mut cs))?;
let class = self.unit.classes.iter_mut().find(|c| c.name == clsid);
if let Some(class) = class {
let Function {
attributes,
attrs,
coeffects,
flags: _,
name,
func,
} = f;
let name = MethodId::new(name.id);
class.methods.push(Method {
attributes,
attrs,
coeffects,
flags: cs.flags,
func,
name,
visibility: cs.visibility,
});
} else {
return Err(clsloc.bail(format!(
"Class '{}' not defined",
String::from_utf8_lossy(&clsname)
)));
}
Ok(())
}
fn parse_src_loc(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<()> {
let src_loc = parse_src_loc(tokenizer, None)?;
self.src_loc = Some(src_loc);
Ok(())
}
fn parse_module(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<()> {
parse!(tokenizer, <name:parse_class_id> "[" <attributes:parse_attribute,*> "]");
let doc_comment = parse_doc_comment(tokenizer, self.alloc)?;
let src_loc = self.get_cur_src_loc();
self.unit.modules.push(Module {
attributes,
name,
src_loc,
doc_comment,
});
Ok(())
}
fn parse_module_use(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<()> {
let module_use = tokenizer
.expect_any_string()?
.unescaped_bump_str(self.alloc)?;
self.unit.module_use = Some(module_use);
Ok(())
}
fn parse_typedef(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<()> {
parse!(tokenizer, <vis:parse_user_id> <name:parse_class_id> ":" <type_info_union:parse_type_info,*> "="
<attributes:parse_attributes("<")> <type_structure:parse_typed_value> <attrs:parse_attr>);
let loc = self.get_cur_src_loc();
self.unit.typedefs.push(Typedef {
attributes,
attrs,
loc,
name,
type_info_union,
type_structure,
case_type: &vis.0 == b"case_type",
});
Ok(())
}
} |
TOML | hhvm/hphp/hack/src/hackc/ir/assemble/Cargo.toml | # @generated by autocargo
[package]
name = "assemble_ir"
version = "0.0.0"
edition = "2021"
[lib]
path = "lib.rs"
[dependencies]
anyhow = "1.0.71"
bstr = { version = "1.4.0", features = ["serde", "std", "unicode"] }
bumpalo = { version = "3.11.1", features = ["collections"] }
ffi = { version = "0.0.0", path = "../../../utils/ffi" }
hash = { version = "0.0.0", path = "../../../utils/hash" }
ir_core = { version = "0.0.0", path = "../ir_core" }
itertools = "0.10.3"
log = { version = "0.4.17", features = ["kv_unstable", "kv_unstable_std"] }
naming_special_names_rust = { version = "0.0.0", path = "../../../naming" }
once_cell = "1.12"
parse_macro_ir = { version = "0.0.0", path = "../cargo/parse_macro" } |
Rust | hhvm/hphp/hack/src/hackc/ir/assemble/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::sync::Arc;
use anyhow::Context;
use anyhow::Result;
use bumpalo::Bump;
use ffi::Str;
use ir_core::class::Requirement;
use ir_core::Class;
use ir_core::ClassId;
use ir_core::CtxConstant;
use ir_core::PropId;
use ir_core::Property;
use ir_core::StringInterner;
use ir_core::TraitReqKind;
use ir_core::TypeConstant;
use itertools::Itertools;
use parse_macro_ir::parse;
use crate::parse::parse_attr;
use crate::parse::parse_attribute;
use crate::parse::parse_attributes;
use crate::parse::parse_class_id;
use crate::parse::parse_comma_list;
use crate::parse::parse_doc_comment;
use crate::parse::parse_enum;
use crate::parse::parse_hack_constant;
use crate::parse::parse_type_info;
use crate::parse::parse_typed_value;
use crate::parse::parse_user_id;
use crate::parse::parse_visibility;
use crate::tokenizer::Tokenizer;
pub(crate) struct ClassParser<'a> {
alloc: &'a Bump,
class: Class<'a>,
strings: Arc<StringInterner>,
}
impl<'a> ClassParser<'a> {
pub(crate) fn parse(
tokenizer: &mut Tokenizer<'_>,
unit_state: &mut crate::assemble::UnitParser<'a>,
) -> Result<Class<'a>> {
parse!(tokenizer, <name:parse_user_id> <flags:parse_attr> "{" "\n");
let name = ClassId::from_bytes(&name.0, &unit_state.unit.strings);
let src_loc = unit_state.get_cur_src_loc();
let mut state = ClassParser {
alloc: unit_state.alloc,
strings: Arc::clone(&unit_state.unit.strings),
class: Class {
attributes: Default::default(),
base: Default::default(),
constants: Default::default(),
ctx_constants: Default::default(),
doc_comment: Default::default(),
enum_type: Default::default(),
enum_includes: Default::default(),
flags,
implements: Default::default(),
methods: Default::default(),
name,
properties: Default::default(),
requirements: Default::default(),
src_loc,
type_constants: Default::default(),
upper_bounds: Default::default(),
uses: Default::default(),
},
};
while !tokenizer.next_is_identifier("}")? {
let next = tokenizer.expect_any_identifier()?;
let tok = next.get_identifier().unwrap();
let res = match tok {
"attribute" => state.parse_attribute(tokenizer),
"constant" => state.parse_constant(tokenizer),
"ctx_constant" => state.parse_ctx_constant(tokenizer),
"doc_comment" => state.parse_doc_comment(tokenizer),
"enum_type" => state.parse_enum_type(tokenizer),
"enum_includes" => state.parse_enum_includes(tokenizer),
"extends" => state.parse_extends(tokenizer),
"implements" => state.parse_implements(tokenizer),
"method" => state.parse_method(tokenizer),
"property" => state.parse_property(tokenizer),
"require" => state.parse_require(tokenizer),
"type_constant" => state.parse_type_constant(tokenizer),
"upper_bound" => state.parse_upper_bound(tokenizer),
"uses" => state.parse_uses(tokenizer),
_ => Err(next.bail(format!("Unexpected token '{next}' parsing class"))),
};
res.with_context(|| format!("Parsing {}", next))?;
tokenizer.expect_eol()?;
}
Ok(state.class)
}
fn parse_attribute(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<()> {
let attr = parse_attribute(tokenizer)?;
self.class.attributes.push(attr);
Ok(())
}
fn parse_constant(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<()> {
let c = parse_hack_constant(tokenizer)?;
self.class.constants.push(c);
Ok(())
}
fn parse_ctx_constant(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<()> {
parse!(tokenizer, <name:parse_user_id>
"[" <recognized:parse_user_id,*> "]"
"[" <unrecognized:parse_user_id,*> "]"
<is_abstract:"abstract"?>);
let name = Str::new_slice(self.alloc, &name.0);
let recognized = recognized
.into_iter()
.map(|(name, _)| Str::new_slice(self.alloc, &name))
.collect_vec();
let unrecognized = unrecognized
.into_iter()
.map(|(name, _)| Str::new_slice(self.alloc, &name))
.collect_vec();
let is_abstract = is_abstract.is_some();
let ctx = CtxConstant {
name,
recognized,
unrecognized,
is_abstract,
};
self.class.ctx_constants.push(ctx);
Ok(())
}
fn parse_doc_comment(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<()> {
let doc_comment = tokenizer
.expect_any_string()?
.unescaped_bump_str(self.alloc)?;
self.class.doc_comment = Some(doc_comment);
Ok(())
}
fn parse_enum_type(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<()> {
let ti = parse_type_info(tokenizer)?;
self.class.enum_type = Some(ti);
Ok(())
}
fn parse_enum_includes(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<()> {
parse!(tokenizer, <enum_includes:parse_class_id,*>);
self.class.enum_includes = enum_includes;
Ok(())
}
fn parse_extends(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<()> {
let name = parse_class_id(tokenizer)?;
self.class.base = Some(name);
Ok(())
}
fn parse_implements(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<()> {
let name = parse_class_id(tokenizer)?;
self.class.implements.push(name);
Ok(())
}
fn parse_method(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<()> {
parse!(tokenizer, parse_user_id);
Ok(())
}
fn parse_property(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<()> {
let alloc = self.alloc;
parse!(tokenizer,
<name:parse_user_id> <flags:parse_attr>
<attributes:parse_attributes("<")> <visibility:parse_visibility>
":" <type_info:parse_type_info>
<doc_comment:parse_doc_comment(alloc)>);
let name = PropId::from_bytes(&name.0, &self.strings);
let initial_value = if tokenizer.next_is_identifier("=")? {
Some(parse_typed_value(tokenizer)?)
} else {
None
};
let prop = Property {
name,
flags,
attributes,
doc_comment: doc_comment.into(),
initial_value,
type_info,
visibility,
};
self.class.properties.push(prop);
Ok(())
}
fn parse_require(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<()> {
let kind = parse_enum(tokenizer, "TraitReqKind", |id| {
Some(match id {
"extends" => TraitReqKind::MustExtend,
"implements" => TraitReqKind::MustImplement,
"must_be_class" => TraitReqKind::MustBeClass,
_ => return None,
})
})?;
let name = parse_class_id(tokenizer)?;
self.class.requirements.push(Requirement { name, kind });
Ok(())
}
fn parse_type_constant(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<()> {
parse!(tokenizer, <is_abstract:"abstract"?> <name:parse_user_id>);
let name = Str::new_slice(self.alloc, &name.0);
let initializer = if tokenizer.next_is_identifier("=")? {
Some(parse_typed_value(tokenizer)?)
} else {
None
};
let tc = TypeConstant {
name,
initializer,
is_abstract: is_abstract.is_some(),
};
self.class.type_constants.push(tc);
Ok(())
}
fn parse_upper_bound(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<()> {
parse!(tokenizer, <name:parse_user_id> ":" "[" <bounds:parse_type_info,*> "]");
let name = Str::new_slice(self.alloc, &name.0);
self.class.upper_bounds.push((name, bounds));
Ok(())
}
fn parse_uses(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<()> {
let name = parse_class_id(tokenizer)?;
self.class.uses.push(name);
Ok(())
}
} |
Rust | hhvm/hphp/hack/src/hackc/ir/assemble/func.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 anyhow::anyhow;
use anyhow::Context;
use anyhow::Result;
use bumpalo::Bump;
use ffi::Str;
use ir_core::func::ExFrame;
use ir_core::instr;
use ir_core::instr::BaseOp;
use ir_core::instr::CallDetail;
use ir_core::instr::CmpOp;
use ir_core::instr::FinalOp;
use ir_core::instr::Hhbc;
use ir_core::instr::IncludeEval;
use ir_core::instr::IncludeKind;
use ir_core::instr::Instr;
use ir_core::instr::IntermediateOp;
use ir_core::instr::MemberKey;
use ir_core::instr::MemberOp;
use ir_core::instr::MemoGet;
use ir_core::instr::MemoGetEager;
use ir_core::instr::Predicate;
use ir_core::instr::Special;
use ir_core::instr::Terminator;
use ir_core::Attr;
use ir_core::Attribute;
use ir_core::Block;
use ir_core::BlockId;
use ir_core::CcParam;
use ir_core::CcReified;
use ir_core::CcThis;
use ir_core::ClassIdMap;
use ir_core::Coeffects;
use ir_core::CollectionType;
use ir_core::Constant;
use ir_core::ExFrameId;
use ir_core::FCallArgsFlags;
use ir_core::Func;
use ir_core::FuncBuilder;
use ir_core::Function;
use ir_core::FunctionFlags;
use ir_core::InstrId;
use ir_core::InstrIdSet;
use ir_core::IterId;
use ir_core::LocId;
use ir_core::LocalId;
use ir_core::MOpMode;
use ir_core::MethodFlags;
use ir_core::ObjMethodOp;
use ir_core::PropId;
use ir_core::QueryMOp;
use ir_core::SetRangeOp;
use ir_core::SwitchKind;
use ir_core::TParamBounds;
use ir_core::TryCatchId;
use ir_core::UnitBytesId;
use ir_core::UnnamedLocalId;
use ir_core::ValueId;
use ir_core::Visibility;
use itertools::Itertools;
use parse_macro_ir::parse;
use crate::parse::convert_bid;
use crate::parse::is_block;
use crate::parse::is_int;
use crate::parse::is_lid;
use crate::parse::is_vid;
use crate::parse::parse_attr;
use crate::parse::parse_attribute;
use crate::parse::parse_bare_this_op;
use crate::parse::parse_bid;
use crate::parse::parse_class_id;
use crate::parse::parse_comma_list;
use crate::parse::parse_const_id;
use crate::parse::parse_constant;
use crate::parse::parse_constant_id;
use crate::parse::parse_dynamic_call_op;
use crate::parse::parse_fatal_op;
use crate::parse::parse_func_id;
use crate::parse::parse_i64;
use crate::parse::parse_inc_dec_op_post;
use crate::parse::parse_inc_dec_op_pre;
use crate::parse::parse_init_prop_op;
use crate::parse::parse_instr_id;
use crate::parse::parse_is_type_op;
use crate::parse::parse_m_op_mode;
use crate::parse::parse_method_id;
use crate::parse::parse_oo_decl_exists_op;
use crate::parse::parse_opt_enum;
use crate::parse::parse_param;
use crate::parse::parse_prop_id;
use crate::parse::parse_readonly;
use crate::parse::parse_set_op_op;
use crate::parse::parse_shadowed_tparams;
use crate::parse::parse_silence_op;
use crate::parse::parse_special_cls_ref;
use crate::parse::parse_special_cls_ref_opt;
use crate::parse::parse_src_loc;
use crate::parse::parse_string_id;
use crate::parse::parse_type_info;
use crate::parse::parse_type_struct_resolve_op;
use crate::parse::parse_u32;
use crate::parse::parse_user_id;
use crate::parse::parse_usize;
use crate::parse::parse_visibility;
use crate::tokenizer::Token;
use crate::tokenizer::TokenLoc;
use crate::tokenizer::Tokenizer;
macro_rules! parse_instr {
($tok:ident, $cons:expr, $($rest:tt)+) => {{
parse!($tok, $($rest)+);
$cons
}};
}
#[derive(Debug)]
enum OpKind {
C,
I(i64),
L,
T(UnitBytesId),
W,
}
struct InstrInfo {
iid: InstrId,
instr: Instr,
}
struct BlockInfo {
bid: BlockId,
instrs: Vec<InstrInfo>,
}
pub(crate) struct ClassState {
pub(crate) visibility: Visibility,
pub(crate) flags: MethodFlags,
}
impl Default for ClassState {
fn default() -> Self {
Self {
visibility: Visibility::Public,
flags: Default::default(),
}
}
}
pub(crate) struct FunctionParser<'a, 'b> {
alloc: &'a Bump,
attributes: Vec<Attribute>,
attrs: Attr,
// A local cache for the (Block x (InstrId, Instr)) state. BlockId::NONE
// (where we put the non-block instrs like params) is guaranteed to be
// blocks[0].
blocks: Vec<BlockInfo>,
builder: FuncBuilder<'a>,
class_state: Option<&'b mut ClassState>,
coeffects: Coeffects<'a>,
cur_loc: LocId,
flags: FunctionFlags,
}
impl<'a, 'b> FunctionParser<'a, 'b> {
pub(crate) fn parse(
tokenizer: &mut Tokenizer<'_>,
unit_state: &mut crate::assemble::UnitParser<'a>,
mut class_state: Option<&'b mut ClassState>,
) -> Result<Function<'a>> {
let alloc = unit_state.alloc;
parse!(tokenizer, <name:parse_func_id>);
let tparams = if tokenizer.next_is_identifier("<")? {
let mut tparams = ClassIdMap::default();
parse_comma_list(tokenizer, false, |tokenizer| {
let name = parse_class_id(tokenizer)?;
let mut bounds = TParamBounds::default();
if tokenizer.next_is_identifier(":")? {
loop {
bounds.bounds.push(parse_type_info(tokenizer)?);
if !tokenizer.next_is_identifier("+")? {
break;
}
}
}
tparams.insert(name, bounds);
Ok(())
})?;
tokenizer.expect_identifier(">")?;
tparams
} else {
Default::default()
};
parse!(tokenizer, "(" <params:parse_param(alloc),*> ")" <shadowed_tparams:parse_shadowed_tparams> ":" <return_type:parse_type_info>);
let attrs = parse_attr(tokenizer)?;
if let Some(class_state) = &mut class_state {
let vis = parse_visibility(tokenizer)?;
class_state.visibility = vis;
}
parse!(tokenizer, "{" "\n");
let mut builder = FuncBuilder::with_func(
Func {
return_type,
params,
tparams,
shadowed_tparams,
..Default::default()
},
Arc::clone(&unit_state.unit.strings),
);
let cur_loc = if let Some(src_loc) = unit_state.src_loc.as_ref() {
let loc = builder.add_loc(src_loc.clone());
builder.func.loc_id = loc;
loc
} else {
LocId::NONE
};
// Initialize the blocks with an empty BlockId::NONE at [0].
let blocks = vec![BlockInfo {
bid: BlockId::NONE,
instrs: Vec::default(),
}];
let mut state = FunctionParser {
alloc: unit_state.alloc,
attributes: Default::default(),
attrs,
blocks,
builder,
class_state,
coeffects: Default::default(),
cur_loc,
flags: Default::default(),
};
while !tokenizer.next_is_identifier("}")? {
let next = tokenizer.expect_any_identifier()?;
let tok = next.identifier();
let res = match tok {
id if is_block(id) => state.parse_label(tokenizer, &next),
".async" => state.parse_flags(&next),
".attr" => state.parse_attr(tokenizer),
".catch_id" => state.parse_catch_id(tokenizer),
".closure_body" => state.parse_flags(&next),
".coeffects_cc_param" => state.parse_coeffects_cc_param(tokenizer),
".coeffects_cc_reified" => state.parse_coeffects_cc_reified(tokenizer),
".coeffects_cc_this" => state.parse_coeffects_cc_this(tokenizer),
".coeffects_closure_parent_scope" => {
state.coeffects.closure_parent_scope = true;
Ok(())
}
".coeffects_fun_param" => state.parse_coeffects_fun_param(tokenizer),
".coeffects_static" => state.parse_coeffects_static(tokenizer),
".coeffects_caller" => {
state.coeffects.caller = true;
Ok(())
}
".const" => state.parse_const(tokenizer),
".doc" => state.parse_doc(tokenizer),
".ex_frame" => state.parse_ex_frame(tokenizer),
".generator" => state.parse_flags(&next),
".is_memoize_wrapper" => {
state.builder.func.is_memoize_wrapper = true;
Ok(())
}
".is_memoize_wrapper_lsb" => {
state.builder.func.is_memoize_wrapper_lsb = true;
Ok(())
}
".memoize_impl" => state.parse_flags(&next),
".num_iters" => state.parse_num_iters(tokenizer),
".pair_generator" => state.parse_flags(&next),
".srcloc" => state.parse_srcloc_decl(tokenizer),
".try_id" => state.parse_try_id(tokenizer),
_ => state.parse_instr(tokenizer, &next),
};
res.with_context(|| format!("Parsing {}", next))?;
tokenizer.expect_eol()?;
}
state.latch_blocks();
Ok(Function {
attributes: state.attributes,
attrs: state.attrs,
coeffects: state.coeffects,
flags: state.flags,
name,
func: state.builder.finish(),
})
}
fn latch_blocks(&mut self) {
assert!(self.builder.func.instrs.is_empty());
// Sort the blocks. BlockId::NONE (where the params all live) will end
// up at the end.
self.blocks.sort_by_key(|block| block.bid);
let func_blocks = &mut self.builder.func.blocks;
let count_instrs: usize = self.blocks.iter().map(|bi| bi.instrs.len()).sum();
self.builder
.func
.instrs
.resize(count_instrs, Instr::tombstone());
let mut unused_iids: InstrIdSet = (0..count_instrs).map(InstrId::from_usize).collect();
let func_instrs = &mut self.builder.func.instrs;
// Place the Instrs with known InstrIds.
for bi in &mut self.blocks {
for ii in &mut bi.instrs {
if ii.iid != InstrId::NONE {
unused_iids.remove(&ii.iid);
while ii.iid.as_usize() >= func_instrs.len() {
func_instrs.resize(ii.iid.as_usize() + 1, Instr::tombstone());
}
std::mem::swap(&mut func_instrs[ii.iid], &mut ii.instr);
}
}
}
// Figure out the (ordered) unused slots.
let mut unused_iids = unused_iids.into_iter().sorted();
// Place the remaining Instrs and fill in the Func blocks.
for bi in &mut self.blocks {
for ii in &mut bi.instrs {
if ii.iid == InstrId::NONE {
let next_iid = unused_iids.next().unwrap();
std::mem::swap(&mut func_instrs[next_iid], &mut ii.instr);
ii.iid = next_iid;
}
}
if bi.bid != BlockId::NONE {
func_blocks[bi.bid].iids = bi.instrs.iter().map(|ii| ii.iid).collect();
}
}
}
}
impl FunctionParser<'_, '_> {
fn iid(&self, tokenizer: &mut Tokenizer<'_>) -> Result<InstrId> {
match tokenizer.expect_any_token()? {
Token::Identifier(s, _) if s.starts_with('%') => {
let i = s[1..].parse()?;
Ok(InstrId::from_usize(i))
}
t => Err(t.bail(format!("Expected InstrId, not '{t}'"))),
}
}
fn keyvalue(&self, tokenizer: &mut Tokenizer<'_>) -> Result<(Option<LocalId>, LocalId)> {
let a = self.lid(tokenizer)?;
Ok(if tokenizer.next_is_identifier("=>")? {
(Some(a), self.lid(tokenizer)?)
} else {
(None, a)
})
}
fn lid(&self, tokenizer: &mut Tokenizer<'_>) -> Result<LocalId> {
let (id, loc) = parse_user_id(tokenizer)?;
if id.is_empty() {
return Err(loc.bail("'$' expected, not ''".to_string()));
}
match id[0] {
b'$' => {
let id = self.builder.strings.intern_bytes(id);
Ok(LocalId::Named(id))
}
b'@' => {
let id = std::str::from_utf8(&id[1..])?.parse()?;
Ok(LocalId::Unnamed(UnnamedLocalId::from_usize(id)))
}
_ => Err(loc.bail(format!(
"'$' expected, not '{}'",
String::from_utf8_lossy(&id)
))),
}
}
fn vid(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<ValueId> {
match tokenizer.peek_token()? {
Some(Token::Identifier(s, _)) if s.starts_with('#') => {
Ok(ValueId::from_constant(parse_constant_id(tokenizer)?))
}
Some(Token::Identifier(s, _)) if s.starts_with('%') => {
Ok(ValueId::from_instr(parse_instr_id(tokenizer)?))
}
Some(_) => {
let c = parse_constant(tokenizer, self.alloc)?;
let id = self.builder.emit_constant(c);
Ok(id)
}
None => Err(anyhow!("Expected token at end")),
}
}
fn vid_opt(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<Option<ValueId>> {
let t = tokenizer.peek_expect_token()?;
match t {
Token::Identifier(s, _) if s.starts_with('#') || s.starts_with('%') => {
Ok(Some(self.vid(tokenizer)?))
}
_ => Ok(None),
}
}
fn vid2(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<[ValueId; 2]> {
parse!(tokenizer, <p0:self.vid> "," <p1:self.vid>);
Ok([p0, p1])
}
fn vid3(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<[ValueId; 3]> {
parse!(tokenizer, <p0:self.vid> "," <p1:self.vid> "," <p2:self.vid>);
Ok([p0, p1, p2])
}
fn arg(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<Arg> {
let mut inout = false;
let mut readonly = false;
loop {
if tokenizer.next_is_identifier("inout")? {
inout = true;
continue;
}
if tokenizer.next_is_identifier("readonly")? {
readonly = true;
continue;
}
break;
}
let vid = self.vid(tokenizer)?;
Ok(Arg {
inout,
readonly,
vid,
})
}
}
struct Arg {
inout: bool,
readonly: bool,
vid: ValueId,
}
impl FunctionParser<'_, '_> {
fn parse_call(
&mut self,
tokenizer: &mut Tokenizer<'_>,
is_async: bool,
loc: LocId,
) -> Result<Instr> {
// call direct var_dump(%1) enforce_mutable_return ""
let kind = tokenizer.expect_any_identifier()?;
let mut operands = Vec::new();
let mut operands_suffix = Vec::new();
let detail = match kind.identifier() {
"cls_method" => {
if let Some(clsref) = parse_special_cls_ref_opt(tokenizer)? {
tokenizer.expect_identifier("::")?;
if let Some(vid) = self.vid_opt(tokenizer)? {
// clsref::vid => FCallClsMethodS
operands_suffix.push(vid);
CallDetail::FCallClsMethodS { clsref }
} else {
// clsref::id => FCallClsMethodSD
let method = parse_method_id(tokenizer)?;
CallDetail::FCallClsMethodSD { clsref, method }
}
} else if let Some(cls_vid) = self.vid_opt(tokenizer)? {
operands_suffix.push(cls_vid);
tokenizer.expect_identifier("::")?;
if let Some(vid) = self.vid_opt(tokenizer)? {
// vid::vid dc => FCallClsMethod
operands_suffix.push(vid);
let log = parse_dynamic_call_op(tokenizer)?;
CallDetail::FCallClsMethod { log }
} else {
// vid::id dc => FCallClsMethodM
let method = parse_method_id(tokenizer)?;
let log = parse_dynamic_call_op(tokenizer)?;
CallDetail::FCallClsMethodM { method, log }
}
} else {
// id::id => FCallClsMethodD
let clsid = parse_class_id(tokenizer)?;
tokenizer.expect_identifier("::")?;
let method = parse_method_id(tokenizer)?;
CallDetail::FCallClsMethodD { clsid, method }
}
}
"ctor" => {
let op = self.vid(tokenizer)?;
operands.push(op);
CallDetail::FCallCtor
}
"func" => {
if let Some(vid) = self.vid_opt(tokenizer)? {
operands_suffix.push(vid);
CallDetail::FCallFunc
} else {
let func = parse_func_id(tokenizer)?;
CallDetail::FCallFuncD { func }
}
}
"obj_method" => {
parse!(tokenizer, <obj:self.vid>
<flavor:["->": "->" { ObjMethodOp::NullThrows } ;
"?->": "?->" { ObjMethodOp::NullSafe }]> );
operands.push(obj);
let next = tokenizer.peek_expect_token()?;
if next
.get_identifier()
.map_or(false, |n| is_vid(n.as_bytes()))
{
// vid->vid => FCallObjMethod
let method = self.vid(tokenizer)?;
operands_suffix.push(method);
CallDetail::FCallObjMethod { flavor }
} else {
// vid->id => FCallObjMethodD
let method = parse_method_id(tokenizer)?;
CallDetail::FCallObjMethodD { method, flavor }
}
}
_ => return Err(kind.bail(format!("Unknown call kind '{kind}'"))),
};
parse!(tokenizer, "(" <ops:self.arg,*> ")");
operands.extend(ops.iter().map(|arg| arg.vid));
operands_suffix.reverse();
operands.extend(operands_suffix);
let inouts: Option<Box<[u32]>> = if ops.iter().any(|arg| arg.inout) {
Some(
ops.iter()
.enumerate()
.filter_map(|(i, arg)| if arg.inout { Some(i as u32) } else { None })
.collect(),
)
} else {
None
};
let num_rets = 1 + inouts.as_ref().map_or(0, |i| i.len() as u32);
let readonly = if ops.iter().any(|arg| arg.readonly) {
Some(
ops.iter()
.enumerate()
.filter_map(|(i, arg)| if arg.readonly { Some(i as u32) } else { None })
.collect(),
)
} else {
None
};
fn convert_fcall_args_flags(id: &str) -> Option<FCallArgsFlags> {
Some(match id {
"has_unpack" => FCallArgsFlags::HasUnpack,
"has_generics" => FCallArgsFlags::HasGenerics,
"lock_while_unwinding" => FCallArgsFlags::LockWhileUnwinding,
"enforce_mutable_return" => FCallArgsFlags::EnforceMutableReturn,
"enforce_readonly_this" => FCallArgsFlags::EnforceReadonlyThis,
"skip_repack" => FCallArgsFlags::SkipRepack,
"skip_coeffects_check" => FCallArgsFlags::SkipCoeffectsCheck,
"explicit_context" => FCallArgsFlags::ExplicitContext,
"has_in_out" => FCallArgsFlags::HasInOut,
"enforce_in_out" => FCallArgsFlags::EnforceInOut,
"enforce_readonly" => FCallArgsFlags::EnforceReadonly,
"has_async_eager_offset" => FCallArgsFlags::HasAsyncEagerOffset,
"num_args_start" => FCallArgsFlags::NumArgsStart,
_ => return None,
})
}
let mut flags = FCallArgsFlags::default();
while let Some(flag) = parse_opt_enum(tokenizer, convert_fcall_args_flags)? {
flags |= flag;
}
let context = parse_string_id(tokenizer)?;
let call = instr::Call {
operands: operands.into(),
context,
detail,
flags,
num_rets,
inouts,
readonly,
loc,
};
if is_async {
parse!(tokenizer, "to" <p0:parse_bid> "eager" <p1:parse_bid>);
Ok(Instr::Terminator(Terminator::CallAsync(
Box::new(call),
[p0, p1],
)))
} else {
Ok(Instr::Call(Box::new(call)))
}
}
fn parse_cmp(&mut self, tokenizer: &mut Tokenizer<'_>, loc: LocId) -> Result<Instr> {
parse!(tokenizer, <lhs:self.vid> <e:id> <rhs:self.vid>);
let op = match e.identifier() {
"<=>" => {
return Ok(Instr::Hhbc(Hhbc::Cmp([lhs, rhs], loc)));
}
"==" => CmpOp::Eq,
">" => CmpOp::Gt,
">=" => CmpOp::Gte,
"<" => CmpOp::Lt,
"<=" => CmpOp::Lte,
"!==" => CmpOp::NSame,
"!=" => CmpOp::Neq,
"===" => CmpOp::Same,
_ => return Err(e.bail(format!("Expected compare identifier, got '{e}'"))),
};
Ok(Instr::Hhbc(Hhbc::CmpOp([lhs, rhs], op, loc)))
}
fn parse_col_from_array(&mut self, tokenizer: &mut Tokenizer<'_>, loc: LocId) -> Result<Instr> {
parse!(tokenizer, <colty:id> <vid:self.vid>);
fn convert_collection_type(id: &str) -> Option<CollectionType> {
Some(match id {
"vector" => CollectionType::Vector,
"map" => CollectionType::Map,
"set" => CollectionType::Set,
"pair" => CollectionType::Pair,
"imm_vector" => CollectionType::ImmVector,
"imm_map" => CollectionType::ImmMap,
"imm_set" => CollectionType::ImmSet,
_ => return None,
})
}
let colty = convert_collection_type(colty.identifier())
.ok_or_else(|| colty.bail(format!("Expected CollectionType but got '{colty}'")))?;
Ok(Instr::Hhbc(Hhbc::ColFromArray(vid, colty, loc)))
}
fn parse_incdec_local(&mut self, tokenizer: &mut Tokenizer<'_>, loc: LocId) -> Result<Instr> {
parse!(tokenizer, <inc_dec_op_pre:parse_inc_dec_op_pre> <lid:self.lid> <inc_dec_op:parse_inc_dec_op_post(inc_dec_op_pre)>);
Ok(Instr::Hhbc(Hhbc::IncDecL(lid, inc_dec_op, loc)))
}
fn parse_incdec_static_prop(
&mut self,
tokenizer: &mut Tokenizer<'_>,
loc: LocId,
) -> Result<Instr> {
parse!(tokenizer, <inc_dec_op_pre:parse_inc_dec_op_pre> <cls:self.vid> "::" <prop:self.vid> <inc_dec_op:parse_inc_dec_op_post(inc_dec_op_pre)>);
Ok(Instr::Hhbc(Hhbc::IncDecS([cls, prop], inc_dec_op, loc)))
}
fn parse_iterator(&mut self, tokenizer: &mut Tokenizer<'_>, loc: LocId) -> Result<Instr> {
parse!(tokenizer, "^" <iter_id:parse_u32> <op:["free":"free"; "next":"next"; "init":"init"]>);
let iter_id = IterId { idx: iter_id };
Ok(match op.identifier() {
"free" => Instr::Hhbc(Hhbc::IterFree(iter_id, loc)),
"init" => {
parse!(tokenizer, "from" <vid:self.vid> "jmp" "to" <target0:parse_bid> "else" <target1:parse_bid> "with" <locals:self.keyvalue>);
Instr::Terminator(Terminator::IterInit(
instr::IteratorArgs::new(iter_id, locals.0, locals.1, target0, target1, loc),
vid,
))
}
"next" => {
parse!(tokenizer, "jmp" "to" <target0:parse_bid> "else" <target1:parse_bid> "with" <locals:self.keyvalue>);
Instr::Terminator(Terminator::IterNext(instr::IteratorArgs::new(
iter_id, locals.0, locals.1, target0, target1, loc,
)))
}
_ => unreachable!(),
})
}
fn parse_jmp(&mut self, tokenizer: &mut Tokenizer<'_>, loc: LocId) -> Result<Instr> {
let jmp = if tokenizer.next_is_identifier("if")? {
parse!(tokenizer,
<pred:["nonzero": "nonzero" { Predicate::NonZero } ; "zero": "zero" { Predicate::Zero }]>
<cond:self.vid> "to" <true_bid:parse_bid> "else" <false_bid:parse_bid>);
Terminator::JmpOp {
cond,
pred,
targets: [true_bid, false_bid],
loc,
}
} else {
parse!(tokenizer, "to" <target:parse_bid>);
if tokenizer.next_is_identifier("with")? {
parse!(tokenizer, "(" <params:self.vid,*> ")");
Terminator::JmpArgs(target, params.into(), loc)
} else {
Terminator::Jmp(target, loc)
}
};
Ok(Instr::Terminator(jmp))
}
fn parse_memo_get(
&mut self,
tokenizer: &mut Tokenizer<'_>,
mnemonic: &str,
loc: LocId,
) -> Result<Instr> {
Ok(Instr::Terminator(match mnemonic {
"memo_get" => {
parse!(tokenizer, "[" <locals:self.lid,*> "]" "to" <value:parse_bid> "else" <no_value:parse_bid>);
Terminator::MemoGet(MemoGet::new(value, no_value, &locals, loc))
}
"memo_get_eager" => {
parse!(tokenizer, "[" <locals:self.lid,*> "]" "to" <suspended:parse_bid> "eager" <eager:parse_bid> "else" <no_value:parse_bid>);
Terminator::MemoGetEager(MemoGetEager::new(
no_value, suspended, eager, &locals, loc,
))
}
_ => unreachable!(),
}))
}
fn parse_new_obj(&mut self, tokenizer: &mut Tokenizer<'_>, loc: LocId) -> Result<Instr> {
if tokenizer.next_is_identifier("direct")? {
let clsid = parse_class_id(tokenizer)?;
Ok(Instr::Hhbc(Hhbc::NewObjD(clsid, loc)))
} else if tokenizer.next_is_identifier("static")? {
let clsref = parse_special_cls_ref(tokenizer)?;
Ok(Instr::Hhbc(Hhbc::NewObjS(clsref, loc)))
} else {
Ok(Instr::Hhbc(Hhbc::NewObj(self.vid(tokenizer)?, loc)))
}
}
fn parse_new_struct_dict(
&mut self,
tokenizer: &mut Tokenizer<'_>,
loc: LocId,
) -> Result<Instr> {
tokenizer.expect_identifier("[")?;
let mut keys: Vec<UnitBytesId> = Vec::new();
let mut values: Vec<ValueId> = Vec::new();
loop {
let name = parse_string_id(tokenizer)?;
keys.push(name);
tokenizer.expect_identifier("=>")?;
values.push(self.vid(tokenizer)?);
if !tokenizer.next_is_identifier(",")? {
break;
}
}
tokenizer.expect_identifier("]")?;
Ok(Instr::Hhbc(Hhbc::NewStructDict(
keys.into(),
values.into(),
loc,
)))
}
fn parse_ret(&mut self, tokenizer: &mut Tokenizer<'_>, loc: LocId) -> Result<Instr> {
Ok(if tokenizer.next_is_identifier("[")? {
parse!(tokenizer, <params:self.vid,*> "]");
Instr::Terminator(Terminator::RetM(params.into(), loc))
} else {
Instr::ret(self.vid(tokenizer)?, loc)
})
}
fn parse_sswitch(&mut self, tokenizer: &mut Tokenizer<'_>, loc: LocId) -> Result<Instr> {
parse!(tokenizer, <cond:self.vid> "[" <cases:self.parse_sswitch_case,*> "]");
let (cases, targets): (Vec<UnitBytesId>, Vec<BlockId>) = cases.into_iter().unzip();
Ok(Instr::Terminator(Terminator::SSwitch {
cond,
cases: cases.into(),
targets: targets.into(),
loc,
}))
}
fn parse_switch(&mut self, tokenizer: &mut Tokenizer<'_>, loc: LocId) -> Result<Instr> {
parse!(tokenizer,
<bounded:["bounded": "bounded" { SwitchKind::Bounded } ;
"unbounded": "unbounded" { SwitchKind::Unbounded }]>
<cond:self.vid> <base:parse_i64> "[" <targets:parse_bid,*> "]");
Ok(Instr::Terminator(Terminator::Switch {
cond,
bounded,
base,
targets: targets.into(),
loc,
}))
}
fn parse_sswitch_case(
&mut self,
tokenizer: &mut Tokenizer<'_>,
) -> Result<(UnitBytesId, BlockId)> {
parse!(tokenizer, <key:parse_string_id> "=>" <bid:parse_bid>);
Ok((key, bid))
}
fn parse_unset(&mut self, tokenizer: &mut Tokenizer<'_>, loc: LocId) -> Result<Instr> {
if let Some(t) = tokenizer.peek_if_any_identifier()? {
if t.identifier().starts_with('@') || t.identifier().starts_with('$') {
return Ok(Instr::Hhbc(Hhbc::UnsetL(self.lid(tokenizer)?, loc)));
}
}
Ok(Instr::Hhbc(Hhbc::UnsetG(self.vid(tokenizer)?, loc)))
}
fn parse_yield(&mut self, tokenizer: &mut Tokenizer<'_>, loc: LocId) -> Result<Instr> {
let value = self.vid(tokenizer)?;
if tokenizer.next_is_identifier("=>")? {
let key = self.vid(tokenizer)?;
Ok(Instr::Hhbc(Hhbc::YieldK([value, key], loc)))
} else {
Ok(Instr::Hhbc(Hhbc::Yield(value, loc)))
}
}
}
impl FunctionParser<'_, '_> {
fn parse_member_op(
&mut self,
tokenizer: &mut Tokenizer<'_>,
mnemonic: &str,
loc: LocId,
) -> Result<Instr> {
let inc_dec_op = if mnemonic == "incdecm" {
parse_inc_dec_op_pre(tokenizer)?
} else {
None
};
let mut operands = Vec::new();
let mut locals = Vec::new();
let base_op = {
let mode = parse_m_op_mode(tokenizer)?;
let readonly = parse_readonly(tokenizer)?;
let t = tokenizer.peek_expect_token()?;
let s = t.unescaped_identifier()?;
match s.as_ref() {
b"$this" => {
tokenizer.read_token()?;
BaseOp::BaseH { loc }
}
b"global" => {
tokenizer.read_token()?;
let vid = self.vid(tokenizer)?;
operands.push(vid);
BaseOp::BaseGC { mode, loc }
}
s if is_vid(s) => {
let vid_cls = self.vid(tokenizer)?;
if tokenizer.next_is_identifier("::")? {
let vid_prop = self.vid(tokenizer)?;
operands.push(vid_prop);
operands.push(vid_cls);
BaseOp::BaseSC {
mode,
loc,
readonly,
}
} else {
operands.push(vid_cls);
BaseOp::BaseC { mode, loc }
}
}
s if is_lid(s) => {
let lid = self.lid(tokenizer)?;
locals.push(lid);
BaseOp::BaseL {
mode,
readonly,
loc,
}
}
_ => return Err(t.bail(format!("Invalid base, got '{t}'"))),
}
};
let mut intermediate_ops = Vec::new();
while let Some(op) = self.parse_intermediate_op(tokenizer, &mut operands, &mut locals)? {
intermediate_ops.push(op);
}
let final_op = if mnemonic == "setrangem" {
parse!(tokenizer, "set" <vids:self.vid3> "size" <sz:parse_u32>
<set_range_op:[
"forward":"forward" { SetRangeOp::Forward } ;
"reverse":"reverse" { SetRangeOp::Reverse }
]>);
operands.extend(vids);
FinalOp::SetRangeM {
sz,
set_range_op,
loc,
}
} else {
let IntermediateOp {
key,
readonly,
loc,
mode: _,
} = intermediate_ops.pop().unwrap();
match mnemonic {
"incdecm" => {
let inc_dec_op = parse_inc_dec_op_post(tokenizer, inc_dec_op)?;
FinalOp::IncDecM {
inc_dec_op,
key,
readonly,
loc,
}
}
"querym" => {
let query_m_op = parse_opt_enum(tokenizer, |id| {
Some(match id {
"quiet" => QueryMOp::CGetQuiet,
"isset" => QueryMOp::Isset,
"inout" => QueryMOp::InOut,
_ => return None,
})
})?
.unwrap_or(QueryMOp::CGet);
FinalOp::QueryM {
key,
readonly,
query_m_op,
loc,
}
}
"setm" => {
parse!(tokenizer, "=" <value:self.vid>);
operands.push(value);
FinalOp::SetM { key, readonly, loc }
}
"setopm" => {
parse!(tokenizer, <set_op_op:parse_set_op_op> <value:self.vid>);
operands.push(value);
FinalOp::SetOpM {
set_op_op,
key,
readonly,
loc,
}
}
"unsetm" => FinalOp::UnsetM { key, readonly, loc },
_ => unreachable!(),
}
};
Ok(Instr::MemberOp(MemberOp {
base_op,
final_op,
intermediate_ops: intermediate_ops.into(),
locals: locals.into(),
operands: operands.into(),
}))
}
fn parse_intermediate_op(
&mut self,
tokenizer: &mut Tokenizer<'_>,
operands: &mut Vec<ValueId>,
locals: &mut Vec<LocalId>,
) -> Result<Option<IntermediateOp>> {
let lead = if let Some(t) = tokenizer.next_if_predicate(|t| {
t.is_identifier("[") || t.is_identifier("->") || t.is_identifier("?->")
})? {
t
} else {
return Ok(None);
};
if tokenizer.next_is_identifier("<")? {
parse!(tokenizer, "srcloc" self.parse_src_loc ">");
}
let mode = parse_opt_enum(tokenizer, |id| match id {
"define" => Some(MOpMode::Define),
"inout" => Some(MOpMode::InOut),
"unset" => Some(MOpMode::Unset),
"warn" => Some(MOpMode::Warn),
_ => None,
})?
.unwrap_or(MOpMode::None);
let readonly = parse_readonly(tokenizer)?;
let (kind, tloc) = self.read_op(tokenizer, operands, locals)?;
let key = match lead.identifier() {
"[" => {
let key = match kind {
OpKind::C => MemberKey::EC,
OpKind::I(i) => MemberKey::EI(i),
OpKind::L => MemberKey::EL,
OpKind::T(id) => MemberKey::ET(id),
OpKind::W => MemberKey::W,
};
tokenizer.expect_identifier("]")?;
key
}
"->" => match kind {
OpKind::C => MemberKey::PC,
OpKind::I(i) => {
// This needs to be pushed as a constant!
operands.push(self.builder.emit_constant(Constant::Int(i)));
MemberKey::PC
}
OpKind::L => MemberKey::PL,
OpKind::T(id) => MemberKey::PT(PropId::new(id)),
OpKind::W => return Err(tloc.bail("']' not allowed with pointer")),
},
"?->" => match kind {
OpKind::T(id) => MemberKey::QT(PropId::new(id)),
OpKind::C | OpKind::I(_) | OpKind::L | OpKind::W => {
return Err(tloc.bail("']' not allowed with {kind:?}"));
}
},
_ => unreachable!(),
};
let loc = self.cur_loc;
Ok(Some(IntermediateOp {
key,
mode,
readonly,
loc,
}))
}
fn read_op(
&mut self,
tokenizer: &mut Tokenizer<'_>,
operands: &mut Vec<ValueId>,
locals: &mut Vec<LocalId>,
) -> Result<(OpKind, TokenLoc)> {
let tloc = tokenizer.peek_loc();
let t = tokenizer.peek_expect_token()?;
Ok(match t {
Token::QuotedString(_, _, _) => {
let id = parse_string_id(tokenizer)?;
(OpKind::T(id), tloc)
}
Token::Identifier(ident, _) => {
if ident == "]" {
(OpKind::W, tloc)
} else if is_lid(ident.as_bytes()) {
let lid = self.lid(tokenizer)?;
locals.push(lid);
(OpKind::L, tloc)
} else if is_int(ident.as_bytes()) {
let i = parse_i64(tokenizer)?;
(OpKind::I(i), tloc)
} else {
let vid = self.vid(tokenizer)?;
operands.push(vid);
(OpKind::C, tloc)
}
}
Token::Eol(_) => return Err(t.bail(format!("Expected op but got '{t}'"))),
})
}
}
impl FunctionParser<'_, '_> {
fn parse_attr(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<()> {
let attr = parse_attribute(tokenizer)?;
self.attributes.push(attr);
Ok(())
}
fn parse_catch_id(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<()> {
let id = ExFrameId::from_usize(parse_usize(tokenizer)?);
self.builder.cur_block_mut().tcid = TryCatchId::Catch(id);
Ok(())
}
fn parse_coeffects_cc_param(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<()> {
parse!(tokenizer, <index:parse_u32> <ctx_name:string>);
let ctx_name = Str::new_slice(self.alloc, &ctx_name.unescaped_string()?);
self.coeffects.cc_param.push(CcParam { index, ctx_name });
Ok(())
}
fn parse_coeffects_cc_reified(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<()> {
parse!(tokenizer, <is_class:"is_class"?> <index:parse_u32>);
let is_class = is_class.is_some();
let mut types = Vec::new();
loop {
let (id, _) = parse_user_id(tokenizer)?;
types.push(Str::new_slice(self.alloc, &id));
if !tokenizer.next_is_identifier("::")? {
break;
}
}
self.coeffects.cc_reified.push(CcReified {
is_class,
index,
types,
});
Ok(())
}
fn parse_coeffects_cc_this(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<()> {
parse!(tokenizer, <types:string,*>);
let types = types
.into_iter()
.map(|t| Ok(Str::new_slice(self.alloc, &t.unescaped_string()?)))
.collect::<Result<_>>()?;
self.coeffects.cc_this.push(CcThis { types });
Ok(())
}
fn parse_coeffects_fun_param(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<()> {
parse!(tokenizer, <fun_param:parse_u32,+>);
self.coeffects.fun_param = fun_param;
Ok(())
}
fn parse_coeffects_static(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<()> {
let static_coeffects = if tokenizer.next_is_identifier("enforced")? {
parse!(tokenizer, "(" <static_coeffects:parse_user_id,*> ")");
static_coeffects
.into_iter()
.map(|(ctx, loc)| {
let s = String::from_utf8_lossy(&ctx);
naming_special_names_rust::coeffects::ctx_str_to_enum(&s).ok_or_else(|| {
loc.bail(format!(
"Expected coeffect but got '{}'",
String::from_utf8_lossy(&ctx)
))
})
})
.try_collect()?
} else {
Vec::new()
};
let unenforced_static_coeffects = if tokenizer.next_is_identifier("unenforced")? {
parse!(tokenizer, "(" <unenforced_static_coeffects:parse_user_id,*> ")");
unenforced_static_coeffects
.into_iter()
.map(|(ctx, _)| Str::new_slice(self.alloc, &ctx))
.collect()
} else {
Vec::new()
};
self.coeffects = Coeffects {
static_coeffects,
unenforced_static_coeffects,
..Coeffects::default()
};
Ok(())
}
fn parse_const(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<()> {
parse!(tokenizer, <idx:parse_constant_id> "=" <value:parse_constant(self.alloc)>);
if self.builder.func.constants.len() <= idx.as_usize() {
self.builder
.func
.constants
.resize(idx.as_usize() + 1, Constant::Uninit);
}
self.builder.constant_lookup.insert(value.clone(), idx);
self.builder.func.constants[idx] = value;
Ok(())
}
fn parse_doc(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<()> {
let doc = tokenizer
.expect_any_string()?
.unescaped_bump_str(self.alloc)?;
self.builder.func.doc_comment = Some(doc);
Ok(())
}
fn parse_ex_frame(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<()> {
parse!(tokenizer, <num:parse_u32> ":" "catch" "=" <catch_bid:parse_bid>);
let num = ExFrameId(num);
let parent = if tokenizer.next_is_identifier(",")? {
parse!(tokenizer, "parent" "=" <kind:["try": "try"; "catch": "catch"]> "(" <parent:parse_u32> ")");
let parent = ExFrameId(parent);
match kind.identifier() {
"try" => TryCatchId::Try(parent),
"catch" => TryCatchId::Catch(parent),
_ => unreachable!(),
}
} else {
TryCatchId::None
};
let frame = ExFrame { parent, catch_bid };
self.builder.func.ex_frames.insert(num, frame);
Ok(())
}
fn parse_flags(&mut self, lead: &Token) -> Result<()> {
if let Some(class_state) = &mut self.class_state {
let bit = match lead.identifier() {
".async" => MethodFlags::IS_ASYNC,
".closure_body" => MethodFlags::IS_CLOSURE_BODY,
".generator" => MethodFlags::IS_GENERATOR,
".pair_generator" => MethodFlags::IS_PAIR_GENERATOR,
_ => return Err(lead.bail(format!("Expected MethodFlags, got {lead}"))),
};
class_state.flags |= bit;
} else {
let bit = match lead.identifier() {
".async" => FunctionFlags::ASYNC,
".generator" => FunctionFlags::GENERATOR,
".memoize_impl" => FunctionFlags::MEMOIZE_IMPL,
".pair_generator" => FunctionFlags::PAIR_GENERATOR,
_ => return Err(lead.bail(format!("Expected FunctionFlags, got {lead}"))),
};
self.flags |= bit;
}
Ok(())
}
fn parse_num_iters(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<()> {
self.builder.func.num_iters = parse_usize(tokenizer)?;
Ok(())
}
fn parse_instr(&mut self, tokenizer: &mut Tokenizer<'_>, lead: &Token) -> Result<()> {
let tmp: Token;
let mut mnemonic = lead.identifier();
let iid = if mnemonic.starts_with('%') {
let iid = InstrId::from_usize(mnemonic[1..].parse::<usize>()?);
tokenizer.expect_identifier("=")?;
tmp = tokenizer.expect_any_identifier()?;
mnemonic = tmp.identifier();
iid
} else {
InstrId::NONE
};
use Hhbc as H;
use Instr as I;
use Terminator as T;
let loc = self.cur_loc;
let tok = tokenizer;
#[rustfmt::skip]
let instr = match mnemonic {
"add" => I::Hhbc(H::Add(self.vid2(tok)?, loc)),
"add_elem_c" => parse_instr!(tok, I::Hhbc(H::AddElemC([p0, p1, p2], loc)), <p0:self.vid> "[" <p1:self.vid> "]" "=" <p2:self.vid>),
"add_new_elem_c" => parse_instr!(tok, I::Hhbc(H::AddNewElemC([p0, p1], loc)), <p0:self.vid> "[" "]" "=" <p1:self.vid>),
"ak_exists" => I::Hhbc(Hhbc::AKExists(self.vid2(tok)?, loc)),
"array_idx" => parse_instr!(tok, I::Hhbc(H::ArrayIdx([p0, p1, p2], loc)), <p0:self.vid> "[" <p1:self.vid> "]" "or" <p2:self.vid>),
"array_mark_legacy" => I::Hhbc(H::ArrayMarkLegacy(self.vid2(tok)?, loc)),
"array_unmark_legacy" => I::Hhbc(H::ArrayUnmarkLegacy(self.vid2(tok)?, loc)),
"async_call" => self.parse_call(tok, true, loc)?,
"await" => I::Hhbc(H::Await(self.vid(tok)?, loc)),
"await_all" => parse_instr!(tok, I::Hhbc(H::AwaitAll(p0.into(), loc)), "[" <p0:self.lid,*> "]"),
"bare_this" => I::Hhbc(H::BareThis(parse_bare_this_op(tok)?, loc)),
"bit_and" => I::Hhbc(H::BitAnd(self.vid2(tok)?, loc)),
"bit_not" => I::Hhbc(H::BitNot(self.vid(tok)?, loc)),
"bit_or" => I::Hhbc(H::BitOr(self.vid2(tok)?, loc)),
"bit_xor" => I::Hhbc(H::BitXor(self.vid2(tok)?, loc)),
"call" => self.parse_call(tok, false, loc)?,
"cast_bool" => I::Hhbc(H::CastBool(self.vid(tok)?, loc)),
"cast_dict" => I::Hhbc(H::CastDict(self.vid(tok)?, loc)),
"cast_double" => I::Hhbc(H::CastDouble(self.vid(tok)?, loc)),
"cast_int" => I::Hhbc(H::CastInt(self.vid(tok)?, loc)),
"cast_keyset" => I::Hhbc(H::CastKeyset(self.vid(tok)?, loc)),
"cast_string" => I::Hhbc(H::CastString(self.vid(tok)?, loc)),
"cast_vec" => I::Hhbc(H::CastVec(self.vid(tok)?, loc)),
"chain_faults" => I::Hhbc(H::ChainFaults(self.vid2(tok)?, loc)),
"check_cls_reified_generic_mismatch" => I::Hhbc(H::CheckClsReifiedGenericMismatch(self.vid(tok)?, loc)),
"check_cls_rg_soft" => I::Hhbc(H::CheckClsRGSoft(self.vid(tok)?, loc)),
"check_prop" => I::Hhbc(H::CheckProp(parse_prop_id(tok)?, loc)),
"check_this" => I::Hhbc(H::CheckThis(loc)),
"class_get_c" => I::Hhbc(H::ClassGetC(self.vid(tok)?, loc)),
"class_get_ts" => I::Hhbc(H::ClassGetTS(self.vid(tok)?, loc)),
"class_has_reified_generics" => I::Hhbc(H::ClassHasReifiedGenerics(self.vid(tok)?, loc)),
"class_name" => I::Hhbc(H::ClassName(self.vid(tok)?, loc)),
"clone" => I::Hhbc(H::Clone(self.vid(tok)?, loc)),
"cls_cns" => parse_instr!(tok, I::Hhbc(H::ClsCns(p0, p1, loc)), <p0:self.vid> "::" <p1:parse_const_id>),
"cls_cns_d" => parse_instr!(tok, I::Hhbc(H::ClsCnsD(p0, p1, loc)), <p1:parse_class_id> "::" <p0:parse_const_id>),
"cmp" => self.parse_cmp(tok, loc)?,
"col_from_array" => self.parse_col_from_array(tok, loc)?,
"combine_and_resolve_type_struct" => I::Hhbc(H::CombineAndResolveTypeStruct(parse_comma_list(tok, false, |tok| self.vid(tok))?.into(), loc)),
"concat" => I::Hhbc(H::Concat(self.vid2(tok)?, loc)),
"concatn" => parse_instr!(tok, I::Hhbc(H::ConcatN(p0.into(), loc)), <p0:self.vid,*>),
"consume_local" => I::Hhbc(H::ConsumeL(self.lid(tok)?, loc)),
"cont_current" => I::Hhbc(H::ContCurrent(loc)),
"cont_enter" => I::Hhbc(H::ContEnter(self.vid(tok)?, loc)),
"cont_get_return" => I::Hhbc(H::ContGetReturn(loc)),
"cont_key" => I::Hhbc(H::ContKey(loc)),
"cont_raise" => I::Hhbc(H::ContRaise(self.vid(tok)?, loc)),
"cont_valid" => I::Hhbc(H::ContValid(loc)),
"create_class" => parse_instr!(tok, I::Hhbc(H::CreateCl{operands: operands.into(), clsid, loc}), <clsid:parse_class_id> "(" <operands:self.vid,*> ")"),
"create_cont" => I::Hhbc(H::CreateCont(loc)),
"create_special_implicit_context" => I::Hhbc(H::CreateSpecialImplicitContext(self.vid2(tok)?, loc)),
"div" => I::Hhbc(H::Div(self.vid2(tok)?, loc)),
"enter" => parse_instr!(tok, I::Terminator(T::Enter(p0, loc)), "to" <p0:parse_bid>),
"eval" => I::Hhbc(H::IncludeEval(IncludeEval { kind: IncludeKind::Eval, vid: self.vid(tok)?, loc })),
"exit" => I::Terminator(T::Exit(self.vid(tok)?, loc)),
"fatal" => parse_instr!(tok, I::Terminator(T::Fatal(p0, p1, loc)), <p1:parse_fatal_op> "," <p0:self.vid>),
"get_class_rg_prop" => I::Hhbc(H::GetClsRGProp(self.vid(tok)?, loc)),
"get_global" => I::Hhbc(H::CGetG(self.vid(tok)?, loc)),
"get_local" => I::Hhbc(H::CGetL(self.lid(tok)?, loc)),
"get_local_quiet" => I::Hhbc(H::CGetQuietL(self.lid(tok)?, loc)),
"get_local_or_uninit" => I::Hhbc(H::CUGetL(self.lid(tok)?, loc)),
"get_memo_key" => I::Hhbc(H::GetMemoKeyL(self.lid(tok)?, loc)),
"get_static" => parse_instr!(tok, I::Hhbc(H::CGetS([p0, p1], p2, loc)), <p1:self.vid> "->" <p0:self.vid> <p2:parse_readonly>),
"has_reified_parent" => I::Hhbc(H::HasReifiedParent(self.vid(tok)?, loc)),
"idx" => parse_instr!(tok, I::Hhbc(H::Idx([p0, p1, p2], loc)), <p0:self.vid> "[" <p1:self.vid> "]" "or" <p2:self.vid>),
"incdec_local" => self.parse_incdec_local(tok, loc)?,
"incdec_static_prop" => self.parse_incdec_static_prop(tok, loc)?,
"incdecm" => self.parse_member_op(tok, mnemonic, loc)?,
"include" => I::Hhbc(H::IncludeEval(IncludeEval { kind: IncludeKind::Include, vid: self.vid(tok)?, loc })),
"include_once" => I::Hhbc(H::IncludeEval(IncludeEval { kind: IncludeKind::IncludeOnce, vid: self.vid(tok)?, loc })),
"init_prop" => parse_instr!(tok, I::Hhbc(H::InitProp(p0, p1, p2, loc)), <p1:parse_prop_id> "," <p0:self.vid> "," <p2:parse_init_prop_op>),
"instance_of_d" => parse_instr!(tok, I::Hhbc(H::InstanceOfD(p0, p1, loc)), <p0:self.vid> "," <p1:parse_class_id>),
"is_late_bound_cls" => I::Hhbc(H::IsLateBoundCls(self.vid(tok)?, loc)),
"is_type_c" => parse_instr!(tok, I::Hhbc(H::IsTypeC(p0, p1, loc)), <p0:self.vid> "," <p1:parse_is_type_op>),
"is_type_l" => parse_instr!(tok, I::Hhbc(H::IsTypeL(p0, p1, loc)), <p0:self.lid> "," <p1:parse_is_type_op>),
"is_type_struct_c" => parse_instr!(tok, I::Hhbc(H::IsTypeStructC([p0, p1], p2, loc)), <p0:self.vid> <p2:parse_type_struct_resolve_op> <p1:self.vid>),
"isset_g" => I::Hhbc(H::IssetG(self.vid(tok)?, loc)),
"isset_l" => I::Hhbc(H::IssetL(self.lid(tok)?, loc)),
"isset_s" => parse_instr!(tok, I::Hhbc(H::IssetS([p0, p1], loc)), <p0:self.vid> "::" <p1:self.vid>),
"iterator" => self.parse_iterator(tok, loc)?,
"jmp" => self.parse_jmp(tok, loc)?,
"late_bound_cls" => I::Hhbc(H::LateBoundCls(loc)),
"lazy_class" => I::Hhbc(H::LazyClass(parse_class_id(tok)?, loc)),
"lazy_class_from_class" => I::Hhbc(H::LazyClassFromClass(self.vid(tok)?, loc)),
"lock_obj" => I::Hhbc(H::LockObj(self.vid(tok)?, loc)),
"memo_get" => self.parse_memo_get(tok, mnemonic, loc)?,
"memo_get_eager" => self.parse_memo_get(tok, mnemonic, loc)?,
"memo_set" => parse_instr!(tok, I::Hhbc(H::MemoSet(p0, p1.into(), loc)), "[" <p1:self.lid,*> "]" "," <p0:self.vid>),
"memo_set_eager" => parse_instr!(tok, I::Hhbc(H::MemoSetEager(p0, p1.into(), loc)), "[" <p1:self.lid,*> "]" "," <p0:self.vid>),
"mod" => I::Hhbc(H::Modulo(self.vid2(tok)?, loc)),
"mul" => I::Hhbc(H::Mul(self.vid2(tok)?, loc)),
"new_dict_array" => I::Hhbc(H::NewDictArray(parse_u32(tok)?, loc)),
"new_keyset_array" => parse_instr!(tok, I::Hhbc(H::NewKeysetArray(p0.into(), loc)), "[" <p0:self.vid,*> "]"),
"new_obj" => self.parse_new_obj(tok, loc)?,
"new_pair" => I::Hhbc(H::NewPair(self.vid2(tok)?, loc)),
"new_struct_dict" => self.parse_new_struct_dict(tok, loc)?,
"new_vec" => parse_instr!(tok, I::Hhbc(H::NewVec(p0.into(), loc)), "[" <p0:self.vid,*> "]"),
"not" => I::Hhbc(H::Not(self.vid(tok)?, loc)),
"oo_decl_exists" => parse_instr!(tok, I::Hhbc(H::OODeclExists(p0, p1, loc)), <p0:self.vid2> <p1:parse_oo_decl_exists_op>),
"parent" => I::Hhbc(H::ParentCls(loc)),
"pow" => I::Hhbc(H::Pow(self.vid2(tok)?, loc)),
"print" => I::Hhbc(H::Print(self.vid(tok)?, loc)),
"querym" => self.parse_member_op(tok, mnemonic, loc)?,
"raise_class_string_conversion_warning" => I::Hhbc(H::RaiseClassStringConversionWarning(loc)),
"record_reified_generic" => I::Hhbc(H::RecordReifiedGeneric(self.vid(tok)?, loc)),
"require" => I::Hhbc(H::IncludeEval(IncludeEval { kind: IncludeKind::Require, vid: self.vid(tok)?, loc })),
"require_once" => I::Hhbc(H::IncludeEval(IncludeEval { kind: IncludeKind::RequireOnce, vid: self.vid(tok)?, loc })),
"require_once_doc" => I::Hhbc(H::IncludeEval(IncludeEval { kind: IncludeKind::RequireOnceDoc, vid: self.vid(tok)?, loc })),
"resolve_class" => I::Hhbc(H::ResolveClass(parse_class_id(tok)?, loc)),
"resolve_cls_method" => parse_instr!(tok, I::Hhbc(H::ResolveClsMethod(p0, p1, loc)), <p0:self.vid> "::" <p1:parse_method_id>),
"resolve_cls_method_d" => parse_instr!(tok, I::Hhbc(H::ResolveClsMethodD(p0, p1, loc)), <p0:parse_class_id> "::" <p1:parse_method_id>),
"resolve_cls_method_s" => parse_instr!(tok, I::Hhbc(H::ResolveClsMethodS(p0, p1, loc)), <p0:parse_special_cls_ref> "::" <p1:parse_method_id>),
"resolve_func" => I::Hhbc(H::ResolveFunc(parse_func_id(tok)?, loc)),
"resolve_meth_caller" => I::Hhbc(H::ResolveMethCaller(parse_func_id(tok)?, loc)),
"resolve_r_cls_method" => parse_instr!(tok, I::Hhbc(H::ResolveRClsMethod([p0, p1], p2, loc)), <p0:self.vid> "::" <p2:parse_method_id> "," <p1:self.vid>),
"resolve_r_cls_method_d" => parse_instr!(tok, I::Hhbc(Hhbc::ResolveRClsMethodD(p0, p1, p2, loc)), <p1:parse_class_id> "::" <p2:parse_method_id> "," <p0:self.vid>),
"resolve_r_cls_method_s" => parse_instr!(tok, I::Hhbc(H::ResolveRClsMethodS(p0, p1, p2, loc)), <p1:parse_special_cls_ref> "::" <p2:parse_method_id> "," <p0:self.vid>),
"resolve_r_func" => parse_instr!(tok, I::Hhbc(H::ResolveRFunc(p0, p1, loc)), <p1:parse_func_id> "," <p0:self.vid>),
"ret" => self.parse_ret(tok, loc)?,
"ret_c_suspended" => I::Terminator(T::RetCSuspended(self.vid(tok)?, loc)),
"select" => parse_instr!(tok, I::Special(Special::Select(p0, p1)), <p1:parse_u32> "from" <p0:self.vid>),
"self" => I::Hhbc(H::SelfCls(loc)),
"set_global" => I::Hhbc(H::SetG(self.vid2(tok)?, loc)),
"set_implicit_context_by_value" => I::Hhbc(H::SetImplicitContextByValue(self.vid(tok)?, loc)),
"set_local" => parse_instr!(tok, I::Hhbc(H::SetL(p0, p1, loc)), <p1:self.lid> "," <p0:self.vid>),
"set_op_local" => parse_instr!(tok, I::Hhbc(H::SetOpL(p0, p1, p2, loc)), <p1:self.lid> <p2:parse_set_op_op> <p0:self.vid>),
"set_op_global" => parse_instr!(tok, I::Hhbc(H::SetOpG([p0, p1], p2, loc)), <p0:self.vid> <p2:parse_set_op_op> <p1:self.vid>),
"set_op_static_property" => parse_instr!(tok, I::Hhbc(H::SetOpS(p0, p1, loc)), <p0:self.vid3> "," <p1:parse_set_op_op>),
"set_s" => parse_instr!(tok, I::Hhbc(H::SetS([p0, p1, p2], p3, loc)), <p1:self.vid> "->" <p0:self.vid> <p3:parse_readonly> "=" <p2:self.vid>),
"setm" => self.parse_member_op(tok, mnemonic, loc)?,
"setopm" => self.parse_member_op(tok, mnemonic, loc)?,
"setrangem" => self.parse_member_op(tok, mnemonic, loc)?,
"shl" => I::Hhbc(H::Shl(self.vid2(tok)?, loc)),
"shr" => I::Hhbc(H::Shr(self.vid2(tok)?, loc)),
"silence" => parse_instr!(tok, I::Hhbc(Hhbc::Silence(p0, p1, loc)), <p0:self.lid> "," <p1:parse_silence_op>),
"sswitch" => self.parse_sswitch(tok, loc)?,
"switch" => self.parse_switch(tok, loc)?,
"sub" => I::Hhbc(H::Sub(self.vid2(tok)?, loc)),
"this" => I::Hhbc(H::This(loc)),
"throw" => I::Terminator(T::Throw(self.vid(tok)?, loc)),
"throw_as_type_struct_exception" => I::Terminator(T::ThrowAsTypeStructException(self.vid2(tok)?, loc)),
"throw_nonexhaustive_switch" => I::Hhbc(H::ThrowNonExhaustiveSwitch(loc)),
"unset" => self.parse_unset(tok, loc)?,
"unsetm" => self.parse_member_op(tok, mnemonic, loc)?,
"verify_implicit_context_state" => I::Hhbc(H::VerifyImplicitContextState(loc)),
"verify_out_type" => parse_instr!(tok, I::Hhbc(Hhbc::VerifyOutType(p0, p1, loc)), <p0:self.vid> "," <p1:self.lid>),
"verify_param_type" => parse_instr!(tok, I::Hhbc(Hhbc::VerifyParamType(p0, p1, loc)), <p0:self.vid> "," <p1:self.lid>),
"verify_param_type_ts" => parse_instr!(tok, I::Hhbc(Hhbc::VerifyParamTypeTS(p0, p1, loc)), <p0:self.vid> "," <p1:self.lid>),
"verify_ret_type_c" => I::Hhbc(H::VerifyRetTypeC(self.vid(tok)?, loc)),
"verify_ret_type_ts" => I::Hhbc(H::VerifyRetTypeTS(self.vid2(tok)?, loc)),
"wh_result" => I::Hhbc(H::WHResult(self.vid(tok)?, loc)),
"yield" => self.parse_yield(tok, loc)?,
_ => {
return Err(lead.bail(format!(
"Unknown instruction '{mnemonic}' parsing function"
)));
}
};
self.blocks
.last_mut()
.unwrap()
.instrs
.push(InstrInfo { iid, instr });
Ok(())
}
fn parse_label(&mut self, tokenizer: &mut Tokenizer<'_>, lead: &Token) -> Result<()> {
let bid = convert_bid(lead)?;
self.blocks.push(BlockInfo {
bid,
instrs: Default::default(),
});
if self.builder.func.blocks.len() <= bid.as_usize() {
self.builder
.func
.blocks
.resize_with(bid.as_usize() + 1, Block::default);
}
self.builder.start_block(bid);
if tokenizer.next_is_identifier("(")? {
// b2(%1, %2, %3):
parse!(tokenizer, <params:self.iid,*> ")");
debug_assert_eq!(self.blocks[0].bid, BlockId::NONE);
self.builder.cur_block_mut().params.extend(¶ms);
self.blocks[0]
.instrs
.extend(params.into_iter().map(|iid| InstrInfo {
iid,
instr: Instr::param(),
}));
}
tokenizer.expect_identifier(":")?;
Ok(())
}
fn parse_src_loc(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<LocId> {
let old = if self.cur_loc == LocId::NONE {
None
} else {
self.builder.func.get_loc(self.cur_loc)
};
let src_loc = parse_src_loc(tokenizer, old)?;
self.cur_loc = self.builder.add_loc(src_loc);
Ok(self.cur_loc)
}
fn parse_srcloc_decl(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<()> {
self.parse_src_loc(tokenizer)?;
Ok(())
}
fn parse_try_id(&mut self, tokenizer: &mut Tokenizer<'_>) -> Result<()> {
let id = ExFrameId::from_usize(parse_usize(tokenizer)?);
self.builder.cur_block_mut().tcid = TryCatchId::Try(id);
Ok(())
}
} |
Rust | hhvm/hphp/hack/src/hackc/ir/assemble/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 assemble;
mod class;
mod func;
mod parse;
mod tokenizer;
mod util;
pub use assemble::unit_from_path;
pub use assemble::unit_from_string; |
Rust | hhvm/hphp/hack/src/hackc/ir/assemble/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::sync::Arc;
use anyhow::Result;
use bumpalo::Bump;
use ffi::Str;
use ir_core::func::DefaultValue;
use ir_core::ArrayKey;
use ir_core::Attr;
use ir_core::Attribute;
use ir_core::BareThisOp;
use ir_core::BaseType;
use ir_core::BlockId;
use ir_core::ClassId;
use ir_core::CollectionType;
use ir_core::ConstId;
use ir_core::ConstName;
use ir_core::Constant;
use ir_core::ConstantId;
use ir_core::DictValue;
use ir_core::EnforceableType;
use ir_core::FatalOp;
use ir_core::Filename;
use ir_core::FloatBits;
use ir_core::FunctionId;
use ir_core::HackConstant;
use ir_core::IncDecOp;
use ir_core::InitPropOp;
use ir_core::InstrId;
use ir_core::IsLogAsDynamicCallOp;
use ir_core::IsTypeOp;
use ir_core::KeysetValue;
use ir_core::MOpMode;
use ir_core::MethodId;
use ir_core::OODeclExistsOp;
use ir_core::Param;
use ir_core::PropId;
use ir_core::ReadonlyOp;
use ir_core::SetOpOp;
use ir_core::SilenceOp;
use ir_core::SpecialClsRef;
use ir_core::SrcLoc;
use ir_core::TypeConstraintFlags;
use ir_core::TypeInfo;
use ir_core::TypeStructResolveOp;
use ir_core::TypedValue;
use ir_core::UnitBytesId;
use ir_core::Visibility;
use parse_macro_ir::parse;
use crate::tokenizer::Token;
use crate::tokenizer::TokenLoc;
use crate::tokenizer::Tokenizer;
use crate::util::unescape;
pub(crate) fn is_block(id: &str) -> bool {
id.starts_with('b') && id.as_bytes().get(1).map_or(false, u8::is_ascii_digit)
}
pub(crate) fn is_lid(id: &[u8]) -> bool {
id.starts_with(b"$") || id.starts_with(b"@")
}
pub(crate) fn is_vid(id: &[u8]) -> bool {
id.starts_with(b"%") || id.starts_with(b"#")
}
fn parse_array_key(tokenizer: &mut Tokenizer<'_>) -> Result<ArrayKey> {
let t = tokenizer.expect_any_token()?;
Ok(match t {
Token::Identifier(s, _) if s == "lazy" => {
parse!(tokenizer, "(" <id:parse_class_id> ")");
ArrayKey::LazyClass(id)
}
Token::Identifier(s, _) if is_int(s.as_bytes()) => {
let i = s.parse()?;
ArrayKey::Int(i)
}
Token::QuotedString(_, s, _) => {
let id = tokenizer.strings.intern_bytes(unescape(&s)?);
ArrayKey::String(id)
}
_ => return Err(t.bail(format!("Expected string or int but got {t}"))),
})
}
pub(crate) fn parse_attr(tokenizer: &mut Tokenizer<'_>) -> Result<Attr> {
let mut attr = Attr::AttrNone;
fn convert_attr(id: &str) -> Option<Attr> {
Some(match id {
"abstract" => Attr::AttrAbstract,
"builtin" => Attr::AttrBuiltin,
"is_closure_class" => Attr::AttrIsClosureClass,
"const" => Attr::AttrIsConst,
"deep_init" => Attr::AttrDeepInit,
"dynamically_callable" => Attr::AttrDynamicallyCallable,
"enum_class" => Attr::AttrEnumClass,
"final" => Attr::AttrFinal,
"initial_satisfies_tc" => Attr::AttrInitialSatisfiesTC,
"interceptable" => Attr::AttrInterceptable,
"interface" => Attr::AttrInterface,
"internal" => Attr::AttrInternal,
"is_meth_caller" => Attr::AttrIsMethCaller,
"late_init" => Attr::AttrLateInit,
"lsb" => Attr::AttrLSB,
"no_bad_redeclare" => Attr::AttrNoBadRedeclare,
"no_dynamic_props" => Attr::AttrForbidDynamicProps,
"no_implicit_null" => Attr::AttrNoImplicitNullable,
"no_injection" => Attr::AttrNoInjection,
"no_override" => Attr::AttrNoOverride,
"no_reified_init" => Attr::AttrNoReifiedInit,
"persistent" => Attr::AttrPersistent,
"private" => Attr::AttrPrivate,
"protected" => Attr::AttrProtected,
"provenance_skip_frame" => Attr::AttrProvenanceSkipFrame,
"public" => Attr::AttrPublic,
"readonly" => Attr::AttrIsReadonly,
"readonly_return" => Attr::AttrReadonlyReturn,
"sealed" => Attr::AttrSealed,
"static" => Attr::AttrStatic,
"system_initial_value" => Attr::AttrSystemInitialValue,
"trait" => Attr::AttrTrait,
"variadic_param" => Attr::AttrVariadicParam,
_ => return None,
})
}
if tokenizer.next_is_identifier("[")? {
parse!(tokenizer, <parts:id,*> "]");
for id in parts {
let bit = convert_attr(id.identifier())
.ok_or_else(|| id.bail(format!("Unknown attr string {}", id)))?;
attr.add(bit);
}
}
Ok(attr)
}
pub(crate) fn parse_attribute(tokenizer: &mut Tokenizer<'_>) -> Result<Attribute> {
let name = parse_class_id(tokenizer)?;
let arguments = if tokenizer.next_is_identifier("(")? {
parse!(tokenizer, <args:parse_typed_value,*> ")");
args
} else {
Vec::new()
};
Ok(Attribute { name, arguments })
}
pub(crate) fn parse_attributes(
tokenizer: &mut Tokenizer<'_>,
delimiter: &str,
) -> Result<Vec<Attribute>> {
if tokenizer.next_is_identifier(delimiter)? {
let attributes = parse_comma_list(tokenizer, false, parse_attribute)?;
let close = match delimiter {
"[" => "]",
"<" => ">",
_ => unreachable!(),
};
tokenizer.expect_identifier(close)?;
Ok(attributes)
} else {
Ok(Vec::new())
}
}
fn parse_base_type(tokenizer: &mut Tokenizer<'_>) -> Result<BaseType> {
let base_type = tokenizer.expect_any_identifier()?;
Ok(match base_type.identifier() {
"array" => BaseType::AnyArray,
"arraykey" => BaseType::Arraykey,
"bool" => BaseType::Bool,
"class" => BaseType::Class(parse_class_id(tokenizer)?),
"classname" => BaseType::Classname,
"darray" => BaseType::Darray,
"dict" => BaseType::Dict,
"float" => BaseType::Float,
"int" => BaseType::Int,
"keyset" => BaseType::Keyset,
"mixed" => BaseType::Mixed,
"none" => BaseType::None,
"nonnull" => BaseType::Nonnull,
"noreturn" => BaseType::Noreturn,
"nothing" => BaseType::Nothing,
"null" => BaseType::Null,
"num" => BaseType::Num,
"resource" => BaseType::Resource,
"string" => BaseType::String,
"this" => BaseType::This,
"typename" => BaseType::Typename,
"varray" => BaseType::Varray,
"varray_or_darray" => BaseType::VarrayOrDarray,
"vec" => BaseType::Vec,
"vec_or_dict" => BaseType::VecOrDict,
"void" => BaseType::Void,
s => {
return Err(base_type.bail(format!("BaseType expected but got '{}'", s)));
}
})
}
pub(crate) fn convert_bid(ident: &Token) -> Result<BlockId> {
let s = ident.identifier();
if s == "none" {
return Ok(BlockId::NONE);
}
if !s.starts_with('b') {
return Err(ident.bail(format!(
"Expected BlockId but '{ident}' doesn't start with 'b'"
)));
}
if let Ok(i) = s[1..].parse::<usize>() {
Ok(BlockId::from_usize(i))
} else {
Err(ident.bail(format!("Error parsing number in BlockId '{ident}'")))
}
}
pub(crate) fn parse_bid(tokenizer: &mut Tokenizer<'_>) -> Result<BlockId> {
let ident = tokenizer.expect_any_identifier()?;
convert_bid(&ident)
}
pub(crate) fn parse_class_id(tokenizer: &mut Tokenizer<'_>) -> Result<ClassId> {
let (id, _) = parse_user_id(tokenizer)?;
Ok(ClassId::from_bytes(&id, &tokenizer.strings))
}
pub(crate) fn parse_const_id(tokenizer: &mut Tokenizer<'_>) -> Result<ConstId> {
let (id, _) = parse_user_id(tokenizer)?;
Ok(ConstId::from_bytes(&id, &tokenizer.strings))
}
pub(crate) fn parse_constant_id(tokenizer: &mut Tokenizer<'_>) -> Result<ConstantId> {
let t = tokenizer.expect_any_identifier()?;
if !t.identifier().starts_with('#') {
return Err(t.bail(format!("Expected '#' but got {t}")));
}
Ok(ConstantId::from_usize(t.identifier()[1..].parse()?))
}
pub(crate) fn parse_comma_list<T, F: FnMut(&mut Tokenizer<'_>) -> Result<T>>(
tokenizer: &mut Tokenizer<'_>,
mut expect_comma: bool,
mut callback: F,
) -> Result<Vec<T>> {
// a, b, c
let mut result = Vec::new();
loop {
if expect_comma {
if !tokenizer.next_is_identifier(",")? {
break;
}
} else {
expect_comma = true;
}
result.push(callback(tokenizer)?);
}
Ok(result)
}
enum Num {
Int(i64),
Float(f64),
}
fn convert_num(t: &Token) -> Result<Num> {
Ok(match t {
Token::Identifier(s, _) if s == "inf" => Num::Float(f64::INFINITY),
Token::Identifier(s, _) if s == "nan" => Num::Float(f64::NAN),
Token::Identifier(s, _) if s.contains('.') => Num::Float(s.parse()?),
Token::Identifier(s, _) => Num::Int(s.parse()?),
_ => return Err(t.bail(format!("Expected number but got '{t}'"))),
})
}
fn is_num_lead(c: u8) -> bool {
c.is_ascii_digit() || c == b'-'
}
pub(crate) fn is_int(s: &[u8]) -> bool {
if s.is_empty() {
return false;
}
if s[0] == b'-' {
is_int(&s[1..])
} else {
s.iter().all(|c| c.is_ascii_digit())
}
}
pub(crate) fn parse_bare_this_op(tokenizer: &mut Tokenizer<'_>) -> Result<BareThisOp> {
parse_enum(tokenizer, "BareThisOp", |t| {
Some(match t {
"notice" => BareThisOp::Notice,
"no_notice" => BareThisOp::NoNotice,
"never_null" => BareThisOp::NeverNull,
_ => return None,
})
})
}
pub(crate) fn parse_constant<'a>(
tokenizer: &mut Tokenizer<'_>,
alloc: &'a Bump,
) -> Result<Constant<'a>> {
Ok(match tokenizer.expect_any_token()? {
t @ Token::QuotedString(..) => {
let id = tokenizer.strings.intern_bytes(t.unescaped_string()?);
Constant::String(id)
}
ref t @ Token::Identifier(ref s, _) => match s.as_str() {
"array" => {
parse!(tokenizer, "(" <tv:parse_typed_value> ")");
Constant::Array(Arc::new(tv))
}
"constant" => {
parse!(tokenizer, "(" <value:parse_user_id> ")");
Constant::Named(ConstName::from_bytes(alloc, &value.0))
}
"dir" => Constant::Dir,
"false" => Constant::Bool(false),
"file" => Constant::File,
"func_cred" => Constant::FuncCred,
"inf" => Constant::Float(FloatBits(f64::INFINITY)),
"method" => Constant::Method,
"new_col" => {
parse!(tokenizer, "(" <kind:id> ")");
let kind = match kind.identifier() {
"Vector" => CollectionType::Vector,
"Map" => CollectionType::Map,
"Set" => CollectionType::Set,
"Pair" => CollectionType::Pair,
"ImmVector" => CollectionType::ImmVector,
"ImmMap" => CollectionType::ImmMap,
"ImmSet" => CollectionType::ImmSet,
_ => return Err(kind.bail(format!("Unknown constant type '{kind}'"))),
};
Constant::NewCol(kind)
}
"null" => Constant::Null,
"true" => Constant::Bool(true),
"uninit" => Constant::Uninit,
"nan" => Constant::Float(FloatBits(f64::NAN)),
"-" => {
let next = tokenizer.expect_any_identifier()?;
match next.identifier() {
"inf" => Constant::Float(FloatBits(f64::NEG_INFINITY)),
_ => return Err(next.bail(format!("Invalid constant following '-': '{next}'"))),
}
}
s if is_num_lead(s.as_bytes()[0]) => match convert_num(t)? {
Num::Int(i) => Constant::Int(i),
Num::Float(f) => Constant::Float(FloatBits(f)),
},
_ => {
return Err(t.bail(format!("Expected constant but got '{t}'")));
}
},
t => return Err(t.bail(format!("Unexpected token reading constant '{t}'"))),
})
}
pub(crate) fn parse_doc_comment<'a>(
tokenizer: &mut Tokenizer<'_>,
alloc: &'a Bump,
) -> Result<Option<Str<'a>>> {
Ok(if tokenizer.next_is_identifier("N")? {
None
} else {
Some(tokenizer.expect_any_string()?.unescaped_bump_str(alloc)?)
})
}
pub(crate) fn parse_dynamic_call_op(tokenizer: &mut Tokenizer<'_>) -> Result<IsLogAsDynamicCallOp> {
Ok(if tokenizer.next_is_identifier("log_as_dc")? {
IsLogAsDynamicCallOp::LogAsDynamicCall
} else {
IsLogAsDynamicCallOp::DontLogAsDynamicCall
})
}
pub(crate) fn parse_fatal_op(tokenizer: &mut Tokenizer<'_>) -> Result<FatalOp> {
parse_enum(tokenizer, "FatalOp", |id| {
Some(match id {
"parse" => ir_core::FatalOp::Parse,
"runtime" => ir_core::FatalOp::Runtime,
"runtime_omit_frame" => ir_core::FatalOp::RuntimeOmitFrame,
_ => return None,
})
})
}
pub(crate) fn parse_func_id(tokenizer: &mut Tokenizer<'_>) -> Result<FunctionId> {
let (ident, _) = parse_user_id(tokenizer)?;
Ok(FunctionId::from_bytes(&ident, &tokenizer.strings))
}
pub(crate) fn parse_hack_constant(tokenizer: &mut Tokenizer<'_>) -> Result<HackConstant> {
parse!(tokenizer, <attrs:parse_attr> <name:parse_const_id>);
let value = if tokenizer.next_is_identifier("=")? {
Some(parse_typed_value(tokenizer)?)
} else {
None
};
Ok(HackConstant { name, value, attrs })
}
fn parse_i32(tokenizer: &mut Tokenizer<'_>) -> Result<i32> {
let t = tokenizer.expect_any_identifier()?;
let i = t.identifier().parse()?;
Ok(i)
}
pub(crate) fn parse_i64(tokenizer: &mut Tokenizer<'_>) -> Result<i64> {
let t = tokenizer.expect_any_identifier()?;
let i = t.identifier().parse()?;
Ok(i)
}
pub(crate) fn parse_enum<T, F>(tokenizer: &mut Tokenizer<'_>, what: &str, f: F) -> Result<T>
where
F: FnOnce(&str) -> Option<T>,
{
let t = tokenizer.expect_any_identifier()?;
if let Some(r) = f(t.identifier()) {
Ok(r)
} else {
Err(t.bail(format!("Expected {what} but got '{t}'")))
}
}
pub(crate) fn parse_inc_dec_op_post(
tokenizer: &mut Tokenizer<'_>,
op: Option<IncDecOp>,
) -> Result<IncDecOp> {
Ok(match op {
None => parse_enum(tokenizer, "IncDecOp", |t| {
Some(match t {
"++" => IncDecOp::PostInc,
"--" => IncDecOp::PostDec,
_ => return None,
})
})?,
Some(op) => op,
})
}
pub(crate) fn parse_inc_dec_op_pre(tokenizer: &mut Tokenizer<'_>) -> Result<Option<IncDecOp>> {
parse_opt_enum(tokenizer, |t| {
Some(match t {
"++" => IncDecOp::PreInc,
"--" => IncDecOp::PreDec,
_ => return None,
})
})
}
pub(crate) fn parse_init_prop_op(tokenizer: &mut Tokenizer<'_>) -> Result<InitPropOp> {
parse_enum(tokenizer, "InitPropOp", |t| {
Some(match t {
"static" => InitPropOp::Static,
"non_static" => InitPropOp::NonStatic,
_ => return None,
})
})
}
pub(crate) fn parse_instr_id(tokenizer: &mut Tokenizer<'_>) -> Result<InstrId> {
let t = tokenizer.expect_any_identifier()?;
if !t.identifier().starts_with('%') {
return Err(t.bail(format!("Expected '%' but got {t}")));
}
Ok(InstrId::from_usize(t.identifier()[1..].parse()?))
}
pub(crate) fn parse_is_type_op(tokenizer: &mut Tokenizer<'_>) -> Result<IsTypeOp> {
parse_enum(tokenizer, "IsTypeOp", |t| {
Some(match t {
"null" => IsTypeOp::Null,
"bool" => IsTypeOp::Bool,
"int" => IsTypeOp::Int,
"double" => IsTypeOp::Dbl,
"string" => IsTypeOp::Str,
"object" => IsTypeOp::Obj,
"resource" => IsTypeOp::Res,
"scalar" => IsTypeOp::Scalar,
"keyset" => IsTypeOp::Keyset,
"dict" => IsTypeOp::Dict,
"vec" => IsTypeOp::Vec,
"array" => IsTypeOp::ArrLike,
"clsmeth" => IsTypeOp::ClsMeth,
"func" => IsTypeOp::Func,
"legacy_array" => IsTypeOp::LegacyArrLike,
"class" => IsTypeOp::Class,
_ => return None,
})
})
}
pub(crate) fn parse_m_op_mode(tokenizer: &mut Tokenizer<'_>) -> Result<MOpMode> {
Ok(parse_opt_enum(tokenizer, |id| {
Some(match id {
"warn" => MOpMode::Warn,
"define" => MOpMode::Define,
"unset" => MOpMode::Unset,
"inout" => MOpMode::InOut,
_ => return None,
})
})?
.unwrap_or(MOpMode::None))
}
pub(crate) fn parse_method_id(tokenizer: &mut Tokenizer<'_>) -> Result<MethodId> {
let (id, _) = parse_user_id(tokenizer)?;
Ok(MethodId::from_bytes(&id, &tokenizer.strings))
}
pub(crate) fn parse_oo_decl_exists_op(tokenizer: &mut Tokenizer<'_>) -> Result<OODeclExistsOp> {
parse_enum(tokenizer, "OODeclExistsOp", |id| {
Some(match id {
"class" => OODeclExistsOp::Class,
"interface" => OODeclExistsOp::Interface,
"trait" => OODeclExistsOp::Trait,
_ => return None,
})
})
}
pub(crate) fn parse_opt_enum<T, F>(tokenizer: &mut Tokenizer<'_>, f: F) -> Result<Option<T>>
where
F: FnOnce(&str) -> Option<T>,
{
if let Some(t) = tokenizer.peek_if_any_identifier()? {
if let Some(r) = f(t.identifier()) {
tokenizer.read_token()?;
return Ok(Some(r));
}
}
Ok(None)
}
pub(crate) fn parse_param<'a>(tokenizer: &mut Tokenizer<'_>, alloc: &'a Bump) -> Result<Param<'a>> {
parse!(tokenizer, <inout:"inout"?> <readonly:"readonly"?> <user_attributes:parse_attributes("[")> <ty:parse_type_info>);
let is_variadic = tokenizer.next_is_identifier("...")?;
parse!(tokenizer, <name:parse_var>);
let default_value = if tokenizer.next_is_identifier("@")? {
parse!(tokenizer, <init:parse_bid> "(" <expr:string> ")");
let expr = expr.unescaped_bump_str(alloc)?;
Some(DefaultValue { init, expr })
} else {
None
};
Ok(Param {
name,
ty,
is_variadic,
is_inout: inout.is_some(),
is_readonly: readonly.is_some(),
user_attributes,
default_value,
})
}
pub(crate) fn parse_prop_id(tokenizer: &mut Tokenizer<'_>) -> Result<PropId> {
let (id, _) = parse_user_id(tokenizer)?;
Ok(PropId::from_bytes(&id, &tokenizer.strings))
}
pub(crate) fn parse_readonly(tokenizer: &mut Tokenizer<'_>) -> Result<ReadonlyOp> {
Ok(parse_opt_enum(tokenizer, |id| {
Some(match id {
"readonly" => ReadonlyOp::Readonly,
"mutable" => ReadonlyOp::Mutable,
"any" => ReadonlyOp::Any,
"check_ro_cow" => ReadonlyOp::CheckROCOW,
"check_mut_ro_cow" => ReadonlyOp::CheckMutROCOW,
_ => return None,
})
})?
.unwrap_or(ReadonlyOp::Any))
}
pub(crate) fn parse_shadowed_tparams(tokenizer: &mut Tokenizer<'_>) -> Result<Vec<ClassId>> {
Ok(if tokenizer.next_is_identifier("[")? {
parse!(tokenizer, <tparams:parse_class_id,*> "]");
tparams
} else {
Vec::new()
})
}
pub(crate) fn parse_special_cls_ref(tokenizer: &mut Tokenizer<'_>) -> Result<SpecialClsRef> {
if let Some(t) = parse_special_cls_ref_opt(tokenizer)? {
Ok(t)
} else {
parse_enum(tokenizer, "SpecialClsRef", |_| None)
}
}
pub(crate) fn parse_special_cls_ref_opt(
tokenizer: &mut Tokenizer<'_>,
) -> Result<Option<SpecialClsRef>> {
parse_opt_enum(tokenizer, |id| {
Some(match id {
"late_bound" => SpecialClsRef::LateBoundCls,
"self" => SpecialClsRef::SelfCls,
"parent" => SpecialClsRef::ParentCls,
_ => return None,
})
})
}
pub(crate) fn parse_src_loc(tokenizer: &mut Tokenizer<'_>, cur: Option<&SrcLoc>) -> Result<SrcLoc> {
parse!(tokenizer, <line_begin:parse_i32> ":" <col_begin:parse_i32> "," <line_end:parse_i32> ":" <col_end:parse_i32> <filename:string?>);
let filename = if let Some(filename) = filename {
let filename = filename.unescaped_string()?;
Filename(tokenizer.strings.intern_bytes(filename))
} else if let Some(cur) = cur {
cur.filename
} else {
Filename::NONE
};
Ok(SrcLoc {
filename,
line_begin,
col_begin,
line_end,
col_end,
})
}
pub(crate) fn parse_set_op_op(tokenizer: &mut Tokenizer<'_>) -> Result<SetOpOp> {
parse_enum(tokenizer, "SetOpOp", |id| {
Some(match id {
"&=" => SetOpOp::AndEqual,
".=" => SetOpOp::ConcatEqual,
"/=" => SetOpOp::DivEqual,
"-=" => SetOpOp::MinusEqual,
"%=" => SetOpOp::ModEqual,
"*=" => SetOpOp::MulEqual,
"|=" => SetOpOp::OrEqual,
"+=" => SetOpOp::PlusEqual,
"**=" => SetOpOp::PowEqual,
"<<=" => SetOpOp::SlEqual,
">>=" => SetOpOp::SrEqual,
"^=" => SetOpOp::XorEqual,
_ => return None,
})
})
}
pub(crate) fn parse_silence_op(tokenizer: &mut Tokenizer<'_>) -> Result<SilenceOp> {
parse_enum(tokenizer, "SilenceOp", |id| {
Some(match id {
"start" => SilenceOp::Start,
"end" => SilenceOp::End,
_ => return None,
})
})
}
pub(crate) fn parse_string_id(tokenizer: &mut Tokenizer<'_>) -> Result<UnitBytesId> {
let name = tokenizer.expect_any_string()?;
let name = name.unescaped_string()?;
Ok(tokenizer.strings.intern_bytes(name))
}
pub(crate) fn parse_type_info(tokenizer: &mut Tokenizer<'_>) -> Result<TypeInfo> {
parse!(tokenizer, "<" <user_type:tok> <ty:parse_base_type> <modifiers:parse_type_constraint_flags> ">");
let user_type = if user_type.is_identifier("N") {
None
} else if !user_type.is_any_string() {
return Err(user_type.bail(format!("String expected but got '{user_type}'")));
} else {
Some(
tokenizer
.strings
.intern_bytes(user_type.unescaped_string()?),
)
};
Ok(TypeInfo {
user_type,
enforced: EnforceableType { ty, modifiers },
})
}
fn parse_type_constraint_flags(tokenizer: &mut Tokenizer<'_>) -> Result<TypeConstraintFlags> {
let mut flags = TypeConstraintFlags::NoFlags;
while let Some(flag) = parse_type_constraint_flag(tokenizer)? {
flags = flags | flag;
}
Ok(flags)
}
fn parse_type_constraint_flag(
tokenizer: &mut Tokenizer<'_>,
) -> Result<Option<TypeConstraintFlags>> {
parse_opt_enum(tokenizer, |id| {
Some(match id {
"extended" => TypeConstraintFlags::ExtendedHint,
"nullable" => TypeConstraintFlags::Nullable,
"type_var" => TypeConstraintFlags::TypeVar,
"soft" => TypeConstraintFlags::Soft,
"type_constant" => TypeConstraintFlags::TypeConstant,
"resolved" => TypeConstraintFlags::Resolved,
"display_nullable" => TypeConstraintFlags::DisplayNullable,
"upper_bound" => TypeConstraintFlags::UpperBound,
_ => return None,
})
})
}
pub(crate) fn parse_type_struct_resolve_op(
tokenizer: &mut Tokenizer<'_>,
) -> Result<TypeStructResolveOp> {
parse_enum(tokenizer, "TypeStructResolveOp", |id| {
Some(match id {
"resolve" => TypeStructResolveOp::Resolve,
"dont_resolve" => TypeStructResolveOp::DontResolve,
_ => return None,
})
})
}
pub(crate) fn parse_typed_value(tokenizer: &mut Tokenizer<'_>) -> Result<TypedValue> {
let t = tokenizer.expect_any_token()?;
Ok(match t {
Token::Identifier(s, _) if s == "dict" => {
fn parse_arrow_tuple(tokenizer: &mut Tokenizer<'_>) -> Result<(ArrayKey, TypedValue)> {
parse!(tokenizer, <k:parse_array_key> "=>" <v:parse_typed_value>);
Ok((k, v))
}
parse!(tokenizer, "[" <values:parse_arrow_tuple,*> "]");
TypedValue::Dict(DictValue(values.into_iter().collect()))
}
Token::Identifier(s, _) if s == "false" => TypedValue::Bool(false),
Token::Identifier(s, _) if s == "inf" => TypedValue::Float(FloatBits(f64::INFINITY)),
Token::Identifier(s, _) if s == "keyset" => {
parse!(tokenizer, "[" <values:parse_array_key,*> "]");
TypedValue::Keyset(KeysetValue(values.into_iter().collect()))
}
Token::Identifier(s, _) if s == "lazy" => {
parse!(tokenizer, "(" <id:parse_class_id> ")");
TypedValue::LazyClass(id)
}
Token::Identifier(s, _) if s == "nan" => TypedValue::Float(FloatBits(f64::NAN)),
Token::Identifier(s, _) if s == "null" => TypedValue::Null,
Token::Identifier(s, _) if s == "true" => TypedValue::Bool(true),
Token::Identifier(s, _) if s == "uninit" => TypedValue::Uninit,
Token::Identifier(s, _) if s == "vec" => {
parse!(tokenizer, "[" <values:parse_typed_value,*> "]");
TypedValue::Vec(values)
}
Token::Identifier(s, _) if s == "-" && tokenizer.next_is_identifier("inf")? => {
TypedValue::Float(FloatBits(f64::NEG_INFINITY))
}
Token::Identifier(ref s, _) if is_num_lead(s.as_bytes()[0]) => match convert_num(&t)? {
Num::Int(i) => TypedValue::Int(i),
Num::Float(f) => TypedValue::Float(FloatBits(f)),
},
Token::QuotedString(_, s, _) => {
let id = tokenizer.strings.intern_bytes(unescape(&s)?);
TypedValue::String(id)
}
_ => return Err(t.bail("Invalid TypedValue, got '{t}'")),
})
}
pub(crate) fn parse_u32(tokenizer: &mut Tokenizer<'_>) -> Result<u32> {
let t = tokenizer.expect_any_identifier()?;
let i = t.identifier().parse()?;
Ok(i)
}
pub(crate) fn parse_usize(tokenizer: &mut Tokenizer<'_>) -> Result<usize> {
let t = tokenizer.expect_any_identifier()?;
let i = t.identifier().parse()?;
Ok(i)
}
pub(crate) fn parse_user_id(tokenizer: &mut Tokenizer<'_>) -> Result<(Vec<u8>, TokenLoc)> {
let t = tokenizer.expect_any_token()?;
let tloc = t.loc().clone();
let value = t.unescaped_identifier()?;
Ok((value.into_owned(), tloc))
}
fn parse_var(tokenizer: &mut Tokenizer<'_>) -> Result<UnitBytesId> {
parse!(tokenizer, @pos <name:parse_user_id>);
if name.0.first().copied() == Some(b'$') {
let id = tokenizer.strings.intern_bytes(name.0);
Ok(id)
} else {
Err(pos.bail(format!(
"Expected leading '$' but got {}",
&String::from_utf8_lossy(&name.0),
)))
}
}
pub(crate) fn parse_visibility(tokenizer: &mut Tokenizer<'_>) -> Result<Visibility> {
parse_enum(tokenizer, "Visibility", |id| {
Some(match id {
"private" => Visibility::Private,
"public" => Visibility::Public,
"protected" => Visibility::Protected,
"internal" => Visibility::Internal,
_ => return None,
})
})
} |
Rust | hhvm/hphp/hack/src/hackc/ir/assemble/parse_macro.rs | // Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
#![feature(box_patterns)]
use std::fmt;
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::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 identifiers.
/// "\n" - matches a newline.
/// id - matches any identifier.
/// string - matches any quoted string.
/// tok - matches any token.
/// @<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);
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.1)
}
}
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 state = State { tokenizer };
let mut var_decl = TokenStream::new();
state.collect_var_decl(&tree, &mut var_decl);
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,
AnyString,
EndOfLine,
Identifier { expect: TokenStream, desc: String },
}
impl Predicate {
fn to_stream(&self, tokenizer: &TokenTree, context: Context) -> TokenStream {
match (context, self) {
(Context::None, Predicate::Any) => {
quote!(#tokenizer.expect_any_token()?)
}
(Context::None, Predicate::AnyIdentifier) => {
quote!(#tokenizer.expect_any_identifier()?)
}
(Context::None, Predicate::AnyString) => {
quote!(#tokenizer.expect_any_string()?)
}
(Context::None, Predicate::EndOfLine) => {
quote!(#tokenizer.expect_eol()?)
}
(Context::None, Predicate::Identifier { expect, .. }) => {
quote!(#tokenizer.expect_identifier(#expect)?)
}
(Context::Optional, Predicate::Any) => {
quote!(#tokenizer.peek()?)
}
(Context::Optional, Predicate::AnyIdentifier) => {
quote!(#tokenizer.next_if_any_identifier()?)
}
(Context::Optional, Predicate::AnyString) => {
quote!(#tokenizer.next_if_any_string()?)
}
(Context::Optional, Predicate::EndOfLine) => {
quote!(#tokenizer.next_if_eol()?)
}
(Context::Optional, Predicate::Identifier { expect, .. }) => {
quote!(#tokenizer.next_if_identifier(#expect)?)
}
(Context::Test, Predicate::Any) => {
quote!(#tokenizer.peek()?.is_some())
}
(Context::Test, Predicate::AnyIdentifier) => {
quote!(#tokenizer.peek_is_any_identifier()?)
}
(Context::Test, Predicate::AnyString) => {
quote!(#tokenizer.peek_is_any_string()?)
}
(Context::Test, Predicate::EndOfLine) => {
quote!(#tokenizer.peek_is_eol()?)
}
(Context::Test, Predicate::Identifier { expect, .. }) => {
quote!(#tokenizer.peek_is_identifier(#expect)?)
}
}
}
fn what(&self) -> &str {
match self {
Predicate::Any => "any",
Predicate::AnyIdentifier => "id",
Predicate::AnyString => "string",
Predicate::EndOfLine => "eol",
Predicate::Identifier { desc, .. } => desc,
}
}
}
#[derive(Debug)]
struct SelectCase {
predicate: Predicate,
pattern: Ast,
}
#[derive(Debug)]
enum Ast {
Code {
code: TokenStream,
},
CommaSeparated(Box<Ast>),
FnCall {
name: TokenStream,
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() {
"\\n" => Ast::Predicate(Predicate::EndOfLine),
_ => Ast::Predicate(Predicate::Identifier {
expect: literal.to_token_stream(),
desc: 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::AnyString)
} else if t.to_string() == "tok" {
Ast::Predicate(Predicate::Any)
} else if t.to_string() == "id" {
Ast::Predicate(Predicate::AnyIdentifier)
} else {
// f
// f(a, b, c)
let mut name = vec![t];
while it.peek().map_or(false, |t| t.is_punct('.')) {
name.push(it.next().unwrap());
name.push(it.expect_ident()?);
}
if it.peek().map_or(false, TokenTree::is_group) {
let group = it.expect_group()?;
let stream = group.group_stream()?;
Ast::FnCall {
name: quote!(#(#name)*),
params: quote!(, #stream),
}
} else {
Ast::FnCall {
name: quote!(#(#name)*),
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 {
// I think clippy is wrong here...
#[allow(clippy::only_used_in_recursion)]
fn collect_var_decl(&self, 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_close_operator()? {
parse_comma_list(#tokenizer, false, |#tokenizer| {
let value = #sub;
Ok(value)
})?
} else {
Vec::new()
}
}
}
Ast::OneOrMore(box sub) => {
let sub = self.emit_ast(sub, context);
quote! {
parse_comma_list(#tokenizer, false, |#tokenizer| {
let value = #sub;
Ok(value)
})?
}
}
_ => unreachable!(),
},
Ast::FnCall { name, params } => {
quote!(#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_any_token()?;
return Err(t.bail(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) })?
)
}
Ast::Predicate(Predicate::AnyString) => {
// string
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_identifier(";")? {
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 super::parse_macro;
use quote::quote;
use macro_test_util::assert_pat_eq;
use macro_test_util::assert_error;
#[test]
fn test_basic() {
assert_pat_eq(
parse_macro(quote!(t, "(")),
quote!(t.expect_identifier("(")?),
);
assert_pat_eq(
parse_macro(quote!(t, "\n")),
quote!(t.expect_eol()?),
);
assert_pat_eq(
parse_macro(quote!(t, "xyzzy")),
quote!(t.expect_identifier("xyzzy")?),
);
assert_pat_eq(
parse_macro(quote!(t, id)),
quote!(t.expect_any_identifier()?),
);
assert_pat_eq(
parse_macro(quote!(t, tok)),
quote!(t.expect_any_token()?),
);
assert_pat_eq(
parse_macro(quote!(t, string)),
quote!(t.expect_any_string()?),
);
assert_pat_eq(
parse_macro(quote!(t, "a" "b")),
quote!(t.expect_identifier("a")?; t.expect_identifier("b")?),
);
assert_pat_eq(
parse_macro(quote!(t, <e:string>)),
quote!(
#[allow(clippy::needless_late_init)]
let e;
e = t.expect_any_string()?
),
);
assert_pat_eq(
parse_macro(quote!(t, <mut e:string>)),
quote!(
#[allow(clippy::needless_late_init)]
let mut e;
e = t.expect_any_string()?
),
);
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, self.custom)),
quote!(self.custom(t)?),
);
assert_pat_eq(
parse_macro(quote!(t, self.custom(param))),
quote!(self.custom(t, param)?),
);
assert_pat_eq(
parse_macro(quote!(t, id)),
quote!(t.expect_any_identifier()?),
);
assert_pat_eq(
parse_macro(quote!(t, ".xyzzy")),
quote!(t.expect_identifier(".xyzzy")?),
);
assert_pat_eq(
parse_macro(quote!(t, @loc "xyzzy")),
quote!(
#[allow(clippy::needless_late_init)]
let loc;
loc = t.peek_loc();
t.expect_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_if_identifier("(")?
)
);
assert_pat_eq(
parse_macro(quote!(t, <e:"foo"?>)),
quote!(
#[allow(clippy::needless_late_init)]
let e;
e = t.next_if_identifier("foo")?
)
);
assert_pat_eq(
parse_macro(quote!(t, <e:".foo"?>)),
quote!(
#[allow(clippy::needless_late_init)]
let e;
e = t.next_if_identifier(".foo")?
)
);
assert_pat_eq(
parse_macro(quote!(t, <e:tok?>)),
quote!(
#[allow(clippy::needless_late_init)]
let e;
e = t.peek()?
)
);
assert_pat_eq(
parse_macro(quote!(t, <e:id?>)),
quote!(
#[allow(clippy::needless_late_init)]
let e;
e = t.next_if_any_identifier()?
)
);
assert_pat_eq(
parse_macro(quote!(t, <e:id?>)),
quote!(
#[allow(clippy::needless_late_init)]
let e;
e = t.next_if_any_identifier()?
)
);
assert_pat_eq(
parse_macro(quote!(t, <e:string?>)),
quote!(
#[allow(clippy::needless_late_init)]
let e;
e = t.next_if_any_string()?
)
);
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_any_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_identifier(";")? {
Ok(None)
} else {
Ok(Some(f(t)?))
}
})?
),
);
}
#[test]
fn test_comma() {
assert_pat_eq(
parse_macro(quote!(t, "x",+)),
quote!(parse_comma_list(t, false, |t| {
let value = t.expect_identifier("x")?;
Ok(value)
})?),
);
assert_pat_eq(
parse_macro(quote!(t, <e:"x",+>)),
quote!(
#[allow(clippy::needless_late_init)]
let e;
e = parse_comma_list(t, false, |t| {
let value = t.expect_identifier("x")?;
Ok(value)
})?
),
);
assert_pat_eq(
parse_macro(quote!(t, <e:"x",*> "]")),
quote!(
#[allow(clippy::needless_late_init)]
let e;
e = if !t.peek_is_close_operator()? {
parse_comma_list(t, false, |t| {
let value = t.expect_identifier("x")?;
Ok(value)
})?
} else {
Vec::new()
};
t.expect_identifier("]")?
),
);
}
#[test]
fn test_embedded_code() {
assert_pat_eq(
parse_macro(quote!(t, "(" { something(); } ")")),
quote!(
t.expect_identifier("(")?;
something();
/* harmless extra semicolon -> */ ;
t.expect_identifier(")")?
),
);
assert_pat_eq(
parse_macro(quote!(t, "(" <e:{ something(); }> ")")),
quote!(
#[allow(clippy::needless_late_init)]
let e;
t.expect_identifier("(")?;
e = something();
/* harmless extra semicolon -> */ ;
t.expect_identifier(")")?
),
);
}
#[test]
fn test_select() {
assert_pat_eq(
parse_macro(quote!(t, "(" [
"a": parse_a;
"b": <e:parse_b>;
"(": parse_c;
] ")")),
quote!(
t.expect_identifier("(")?;
if t.peek_is_identifier("a")? {
parse_a(t)?
} else if t.peek_is_identifier("b")? {
#[allow(clippy::needless_late_init)]
let e;
e = parse_b(t)?
} else if t.peek_is_identifier("(")? {
parse_c(t)?
} else {
let t = t.expect_any_token()?;
return Err(t.bail(format!("{} expected, not '{}'" , "'a', 'b' or '('" , t)))
}
/* harmless extra semi -> */ ;
t.expect_identifier(")")?
),
);
assert_pat_eq(
parse_macro(quote!(t, [
".a": parse_a;
else: parse_b;
])),
quote!(
if t.peek_is_identifier(".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_any_identifier()? {
parse_a(t)?
} else {
parse_b(t)?
}
),
);
assert_pat_eq(
parse_macro(quote!(t, [
tok: 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_identifier("(")?;
if t.peek_is_identifier("a")? {
parse_a(t)?
} else if t.peek_is_identifier("b")? {
parse_b(t)?
} else {
parse_c(t)?
}
/* harmless extra semi -> */ ;
t.expect_identifier(")")?
),
);
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: <token:tok> { Err(token.error("Unknown VerifyIs reason")) } ;
])),
quote!(
if tokenizer.peek_is_identifier("as")? {
tokenizer.expect_identifier("as")?;
Ok(DowncastReason::As)
} else if tokenizer.peek_is_identifier("native")? {
#[allow(clippy::needless_late_init)]
let index;
tokenizer.expect_identifier("native")?;
index = num(tokenizer)?;
Ok(DowncastReason::Native { index: index.as_int()? })
} else if tokenizer.peek_is_identifier("param")? {
#[allow(clippy::needless_late_init)]
let index;
tokenizer.expect_identifier("param")?;
index = num(tokenizer)?;
Ok(DowncastReason::Param { index: index.as_int()? })
} else if tokenizer.peek_is_identifier("return")? {
tokenizer.expect_identifier("return")?;
Ok(DowncastReason::Return)
} else {
#[allow(clippy::needless_late_init)]
let token;
token = tokenizer.expect_any_token()?;
Err(token.error("Unknown VerifyIs reason"))
}
),
);
}
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.