language
stringlengths 0
24
| filename
stringlengths 9
214
| code
stringlengths 99
9.93M
|
---|---|---|
Rust | hhvm/hphp/hack/src/hackc/print_expr/special_class_resolver.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::borrow::Cow;
use crate::HhasBodyEnv;
pub trait SpecialClassResolver {
fn resolve<'a>(&self, env: Option<&'a HhasBodyEnv<'_>>, id: &'a str) -> Cow<'a, str>;
} |
Rust | hhvm/hphp/hack/src/hackc/print_expr/write.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::fmt::Debug;
use std::io;
use std::io::Result;
use std::io::Write;
use thiserror::Error;
#[derive(Error, Debug)]
pub enum Error {
#[error("write error: {0:?}")]
WriteError(anyhow::Error),
#[error("a string may contain invalid utf-8")]
InvalidUTF8,
//TODO(hrust): This is a temp error during porting
#[error("NOT_IMPL: {0}")]
NotImpl(String),
#[error("Failed: {0}")]
Fail(String),
}
impl Error {
pub fn fail(s: impl Into<String>) -> Self {
Self::Fail(s.into())
}
}
pub(crate) fn into_error(e: io::Error) -> Error {
if e.kind() == io::ErrorKind::Other && e.get_ref().map_or(false, |e| e.is::<Error>()) {
let err: Error = *e.into_inner().unwrap().downcast::<Error>().unwrap();
return err;
}
Error::WriteError(e.into())
}
impl From<Error> for std::io::Error {
fn from(e: Error) -> Self {
io::Error::new(io::ErrorKind::Other, e)
}
}
pub(crate) fn wrap_by_<F>(w: &mut dyn Write, s: &str, e: &str, f: F) -> Result<()>
where
F: FnOnce(&mut dyn Write) -> Result<()>,
{
w.write_all(s.as_bytes())?;
f(w)?;
w.write_all(e.as_bytes())
}
pub(crate) fn wrap_by<F>(w: &mut dyn Write, s: &str, f: F) -> Result<()>
where
F: FnOnce(&mut dyn Write) -> Result<()>,
{
wrap_by_(w, s, s, f)
}
macro_rules! wrap_by {
($name:ident, $left:expr, $right:expr) => {
pub(crate) fn $name<F>(w: &mut dyn Write, f: F) -> Result<()>
where
F: FnOnce(&mut dyn Write) -> Result<()>,
{
$crate::write::wrap_by_(w, $left, $right, f)
}
};
}
wrap_by!(paren, "(", ")");
wrap_by!(square, "[", "]");
pub(crate) fn concat_str_by<I: AsRef<str>>(
w: &mut dyn Write,
sep: impl AsRef<str>,
ss: impl AsRef<[I]>,
) -> Result<()> {
concat_by(w, sep, ss, |w, s| {
w.write_all(s.as_ref().as_bytes())?;
Ok(())
})
}
pub(crate) fn concat<T, F>(w: &mut dyn Write, items: impl AsRef<[T]>, f: F) -> Result<()>
where
F: FnMut(&mut dyn Write, &T) -> Result<()>,
{
concat_by(w, "", items, f)
}
pub(crate) fn concat_by<T, F>(
w: &mut dyn Write,
sep: impl AsRef<str>,
items: impl AsRef<[T]>,
mut f: F,
) -> Result<()>
where
F: FnMut(&mut dyn Write, &T) -> Result<()>,
{
let mut first = true;
let sep = sep.as_ref();
Ok(for i in items.as_ref() {
if first {
first = false;
} else {
w.write_all(sep.as_bytes())?;
}
f(w, i)?;
})
}
pub(crate) fn option<T, F>(w: &mut dyn Write, i: impl Into<Option<T>>, mut f: F) -> Result<()>
where
F: FnMut(&mut dyn Write, T) -> Result<()>,
{
match i.into() {
None => Ok(()),
Some(i) => f(w, i),
}
} |
Rust | hhvm/hphp/hack/src/hackc/sem_diff/body.rs | use std::rc::Rc;
use anyhow::bail;
use anyhow::Context;
use anyhow::Result;
use ffi::Str;
use hash::HashMap;
use hhbc::AdataId;
use hhbc::Instruct;
use hhbc::Label;
use hhbc::Local;
use hhbc::Opcode;
use hhbc::Pseudo;
use hhbc::SrcLoc;
use hhbc::TypedValue;
use hhbc_gen::OpcodeData;
use newtype::IdVec;
use crate::code_path::CodePath;
use crate::instr_ptr::InstrPtr;
use crate::sequence::Sequence;
use crate::value::ValueBuilder;
use crate::work_queue::WorkQueue;
/// Compare two `hhbc::Body`s to figure out if they are semantically equivalent.
///
/// We don't want to simply require the two bodies to match exactly - that's
/// boring. Instead we allow their instruction sequences to drift and define
/// checkpoints where they need to match up.
///
/// We start by having a work queue that identifies pairs of related (left and
/// right side) `State`s. The most obvious starting state is at the entry IP
/// with an empty stack - but default parameters will add additional starting
/// states. We then loop until either we find a difference or the work queue is
/// empty.
///
/// At each loop step we take the pair of `State`s and use them to collect a
/// `Sequence` (see `State::collect()`) . A `Sequence` represents a series of
/// checkpoint instructions along with their abstract input values. The
/// abstract input values are defined such that a set of inputs run through the
/// same Instruct will always produce the same value.
///
/// As we collect sequences any conditional control flow (like a JmpZ) adds new
/// pairs of state to the work queue.
///
/// Finally we compare the two sequences to make sure that they're equal or we
/// return an Err (see `Sequence::compare()`).
///
pub(crate) fn compare_bodies<'arena, 'a>(
path: &CodePath<'_>,
body_a: &'arena hhbc::Body<'arena>,
a_adata: &'a HashMap<AdataId<'arena>, &'a TypedValue<'arena>>,
body_b: &'arena hhbc::Body<'arena>,
b_adata: &'a HashMap<AdataId<'arena>, &'a TypedValue<'arena>>,
) -> Result<()> {
let mut work_queue = WorkQueue::default();
let a = Body::new(body_a);
let b = Body::new(body_b);
let mut value_builder = ValueBuilder::new();
work_queue.init_from_bodies(&mut value_builder, &a, a_adata, &b, b_adata);
// If we loop more than this number of times it's almost certainly a bug.
let mut infinite_loop = std::cmp::max(body_a.body_instrs.len(), body_b.body_instrs.len()) * 5;
while let Some((a, b)) = work_queue.pop() {
let seq_a = a.collect(&mut value_builder).context("collecting a")?;
let seq_b = b.collect(&mut value_builder).context("collecting b")?;
Sequence::compare(path, seq_a.seq, seq_b.seq)?;
debug_assert_eq!(seq_a.forks.len(), seq_a.forks.len());
for (a, b) in seq_a.forks.into_iter().zip(seq_b.forks.into_iter()) {
work_queue.add(a, b);
}
match (seq_a.catch_state, seq_b.catch_state) {
(None, None) => {}
(None, Some(_)) => {
bail!("Mismatched catch blocks - 'a' doesn't have catch but 'b' does.",);
}
(Some(_), None) => {
bail!("Mismatched catch blocks - 'a' has catch but 'b' does not.",);
}
(Some(mut catch_a), Some(mut catch_b)) => {
let ex = value_builder.alloc();
catch_a.stack.push(ex);
catch_b.stack.push(ex);
work_queue.add(catch_a, catch_b);
}
}
infinite_loop -= 1;
if infinite_loop == 0 {
bail!("Looping out of control - almost certainly a sem_diff bug.");
}
}
Ok(())
}
pub(crate) struct Body<'arena> {
pub(crate) hhbc_body: &'arena hhbc::Body<'arena>,
pub(crate) label_to_ip: HashMap<Label, InstrPtr>,
/// Mapping from InstrPtr to the InstrPtr of its catch block.
try_catch: HashMap<InstrPtr, InstrPtr>,
ip_to_loc: IdVec<InstrPtr, Rc<SrcLoc>>,
}
impl<'arena> Body<'arena> {
fn new(hhbc_body: &'arena hhbc::Body<'arena>) -> Self {
let (label_to_ip, ip_to_loc) = Self::compute_per_instr_info(hhbc_body);
let try_catch = Self::compute_try_catch(hhbc_body);
Body {
hhbc_body,
label_to_ip,
ip_to_loc,
try_catch,
}
}
pub(crate) fn lookup_catch(&self, ip: InstrPtr) -> InstrPtr {
self.try_catch.get(&ip).copied().unwrap_or(InstrPtr::None)
}
pub(crate) fn local_name(&self, local: Local) -> Option<Str<'arena>> {
let mut n = local.as_usize();
let p = self.hhbc_body.params.len();
if n < p {
return Some(self.hhbc_body.params[n].name);
}
n -= p;
let v = self.hhbc_body.decl_vars.len();
if n < v {
return Some(self.hhbc_body.decl_vars[n]);
}
None
}
fn compute_per_instr_info(
hhbc_body: &'arena hhbc::Body<'arena>,
) -> (HashMap<Label, InstrPtr>, IdVec<InstrPtr, Rc<SrcLoc>>) {
let mut label_to_ip = HashMap::default();
let mut ip_to_loc = Vec::with_capacity(hhbc_body.body_instrs.len());
let mut cur_loc = Rc::new(SrcLoc::default());
for (ip, instr) in body_instrs(hhbc_body) {
match instr {
Instruct::Pseudo(Pseudo::SrcLoc(src_loc)) => cur_loc = Rc::new(src_loc.clone()),
Instruct::Pseudo(Pseudo::Label(label)) => {
label_to_ip.insert(*label, ip);
}
_ => {}
}
ip_to_loc.push(cur_loc.clone());
}
(label_to_ip, IdVec::new_from_vec(ip_to_loc))
}
/// Compute a mapping from InstrPtrs to their catch target.
fn compute_try_catch(hhbc_body: &'arena hhbc::Body<'arena>) -> HashMap<InstrPtr, InstrPtr> {
let mut cur: Vec<InstrPtr> = Vec::new();
let mut mapping: HashMap<InstrPtr, InstrPtr> = HashMap::default();
for (ip, instr) in body_instrs(hhbc_body).rev() {
match instr {
Instruct::Pseudo(Pseudo::TryCatchBegin) => {
cur.pop();
}
Instruct::Pseudo(Pseudo::TryCatchMiddle) => {
cur.push(ip);
}
Instruct::Pseudo(Pseudo::TryCatchEnd) => {}
_ => {
if let Some(cur) = cur.last() {
mapping.insert(ip, *cur);
}
}
}
}
mapping
}
pub(crate) fn ip_to_loc(&self, ip: InstrPtr) -> &Rc<SrcLoc> {
&self.ip_to_loc[ip]
}
}
fn body_instrs<'arena>(
hhbc_body: &'arena hhbc::Body<'arena>,
) -> impl Iterator<Item = (InstrPtr, &'arena Instruct<'arena>)> + DoubleEndedIterator {
hhbc_body.body_instrs.iter().enumerate().map(|(i, instr)| {
let ip = InstrPtr::from_usize(i);
(ip, instr)
})
}
pub(crate) fn lookup_data_for_opcode(opcode: &Opcode<'_>) -> &'static OpcodeData {
hhbc_gen::opcode_data().get(opcode.variant_index()).unwrap()
} |
TOML | hhvm/hphp/hack/src/hackc/sem_diff/Cargo.toml | # @generated by autocargo
[package]
name = "sem_diff"
version = "0.0.0"
edition = "2021"
[lib]
path = "lib.rs"
test = false
doctest = false
[dependencies]
anyhow = "1.0.71"
ffi = { version = "0.0.0", path = "../../utils/ffi" }
hash = { version = "0.0.0", path = "../../utils/hash" }
hhbc = { version = "0.0.0", path = "../hhbc/cargo/hhbc" }
hhbc-gen = { version = "0.0.0", path = "../../../../tools/hhbc-gen" }
itertools = "0.10.3"
log = { version = "0.4.17", features = ["kv_unstable", "kv_unstable_std"] }
newtype = { version = "0.0.0", path = "../../utils/newtype" } |
Rust | hhvm/hphp/hack/src/hackc/sem_diff/code_path.rs | use std::fmt;
pub(crate) enum CodePath<'a> {
Name(&'a str),
Qualified(&'a CodePath<'a>, &'a str),
IndexStr(&'a CodePath<'a>, &'a str),
IndexN(&'a CodePath<'a>, i64),
}
impl<'a> CodePath<'a> {
pub(crate) fn name(name: &'a str) -> Self {
Self::Name(name)
}
pub(crate) fn index_str(&'a self, idx: &'a str) -> CodePath<'a> {
Self::IndexStr(self, idx)
}
pub(crate) fn index(&'a self, idx: i64) -> CodePath<'a> {
Self::IndexN(self, idx)
}
pub(crate) fn qualified(&'a self, name: &'a str) -> CodePath<'a> {
Self::Qualified(self, name)
}
}
impl fmt::Display for CodePath<'_> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
CodePath::Name(name) => write!(fmt, "{}", name),
CodePath::IndexStr(root, idx) => write!(fmt, "{}[{}]", root, idx),
CodePath::IndexN(root, idx) => write!(fmt, "{}[{}]", root, idx),
CodePath::Qualified(root, name) => write!(fmt, "{}.{}", root, name),
}
}
} |
Rust | hhvm/hphp/hack/src/hackc/sem_diff/helpers.rs | use std::fmt;
use anyhow::bail;
use anyhow::Result;
use hash::HashMap;
use hash::HashSet;
use crate::code_path::CodePath;
pub(crate) trait MapName {
fn get_name(&self) -> &str;
}
impl MapName for hhbc::Adata<'_> {
fn get_name(&self) -> &str {
self.id.unsafe_as_str()
}
}
impl MapName for hhbc::Class<'_> {
fn get_name(&self) -> &str {
self.name.unsafe_as_str()
}
}
impl MapName for hhbc::Constant<'_> {
fn get_name(&self) -> &str {
self.name.unsafe_as_str()
}
}
impl MapName for hhbc::CtxConstant<'_> {
fn get_name(&self) -> &str {
self.name.unsafe_as_str()
}
}
impl MapName for hhbc::Function<'_> {
fn get_name(&self) -> &str {
self.name.unsafe_as_str()
}
}
impl MapName for hhbc::Method<'_> {
fn get_name(&self) -> &str {
self.name.unsafe_as_str()
}
}
impl MapName for hhbc::Module<'_> {
fn get_name(&self) -> &str {
self.name.unsafe_as_str()
}
}
impl MapName for hhbc::Property<'_> {
fn get_name(&self) -> &str {
self.name.unsafe_as_str()
}
}
impl MapName for hhbc::Typedef<'_> {
fn get_name(&self) -> &str {
self.name.unsafe_as_str()
}
}
impl MapName for hhbc::TypeConstant<'_> {
fn get_name(&self) -> &str {
self.name.unsafe_as_str()
}
}
impl MapName for hhbc::Requirement<'_> {
fn get_name(&self) -> &str {
self.name.unsafe_as_str()
}
}
impl MapName for hhbc::UpperBound<'_> {
fn get_name(&self) -> &str {
self.name.unsafe_as_str()
}
}
pub(crate) fn sem_diff_eq<Ta, Tb>(path: &CodePath<'_>, a: &Ta, b: &Tb) -> Result<()>
where
Ta: PartialEq<Tb> + fmt::Debug,
Tb: fmt::Debug,
{
if a != b {
bail!("Mismatch in {}:\n{:?}\n{:?}", path, a, b);
}
Ok(())
}
pub(crate) fn sem_diff_map_t<'a, 'b, Ta: 'a, Tb: 'b, F>(
path: &CodePath<'_>,
a: &'a [Ta],
b: &'b [Tb],
f_eq: F,
) -> Result<()>
where
Ta: MapName,
Tb: MapName,
F: Fn(&CodePath<'_>, &'a Ta, &'b Tb) -> Result<()>,
{
let a_hash: HashMap<&str, &Ta> = a.iter().map(|t| (t.get_name(), t)).collect();
let b_hash: HashMap<&str, &Tb> = b.iter().map(|t| (t.get_name(), t)).collect();
let a_keys: HashSet<&str> = a_hash.keys().copied().collect();
let b_keys: HashSet<&str> = b_hash.keys().copied().collect();
for k in &a_keys & &b_keys {
f_eq(&path.index_str(k), a_hash[k], b_hash[k])?;
}
if let Some(k) = (&a_keys - &b_keys).into_iter().next() {
bail!("In {} lhs has key {} but rhs does not", path, k.to_string());
}
if let Some(k) = (&b_keys - &a_keys).into_iter().next() {
bail!("In {} rhs has key {} but lhs does not", path, k.to_string());
}
Ok(())
}
#[allow(dead_code)]
pub(crate) fn sem_diff_set_t<'a, T>(path: &CodePath<'_>, a: &'a [T], b: &'a [T]) -> Result<()>
where
T: std::hash::Hash + Eq + std::fmt::Debug,
{
let a_keys: HashSet<&T> = a.iter().collect();
let b_keys: HashSet<&T> = b.iter().collect();
if let Some(k) = (&a_keys - &b_keys).into_iter().next() {
bail!("In {} lhs has value {:?} but rhs does not", path, k);
}
if let Some(k) = (&b_keys - &a_keys).into_iter().next() {
bail!("In {} rhs has value {:?} but lhs does not", path, k);
}
Ok(())
}
pub(crate) fn sem_diff_option<T, F>(
path: &CodePath<'_>,
a: Option<&T>,
b: Option<&T>,
f_eq: F,
) -> Result<()>
where
T: fmt::Debug,
F: FnOnce(&CodePath<'_>, &T, &T) -> Result<()>,
{
match (a, b) {
(None, None) => Ok(()),
(Some(inner), None) => bail!("Mismatch in {}:\nSome({:?})\nNone", path, inner),
(None, Some(inner)) => bail!("Mismatch in {}:\nNone\nSome({:?})", path, inner),
(Some(lhs), Some(rhs)) => f_eq(&path.qualified("unwrap()"), lhs, rhs),
}
}
pub(crate) fn sem_diff_iter<'a, V: 'a, F>(
path: &CodePath<'_>,
mut a: impl Iterator<Item = V>,
mut b: impl Iterator<Item = V>,
f_eq: F,
) -> Result<()>
where
F: Fn(&CodePath<'_>, V, V) -> Result<()>,
{
let mut idx = 0;
loop {
let ai = a.next();
let bi = b.next();
match (ai, bi) {
(None, None) => return Ok(()),
(Some(av), Some(bv)) => f_eq(&path.index(idx), av, bv)?,
(Some(_), None) => {
bail!("Mismatch in {}: A side is longer.", path);
}
(None, Some(_)) => {
bail!("Mismatch in {}: B side is longer.", path);
}
}
idx += 1;
}
}
pub(crate) fn sem_diff_slice<'a, V, F>(
path: &CodePath<'_>,
a: &'a [V],
b: &'a [V],
f_eq: F,
) -> Result<()>
where
F: Fn(&CodePath<'_>, &'a V, &'a V) -> Result<()>,
{
sem_diff_iter(path, a.iter(), b.iter(), f_eq)
} |
Rust | hhvm/hphp/hack/src/hackc/sem_diff/instr_ptr.rs | use std::fmt;
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)]
pub(crate) enum InstrPtr {
None,
Index(u32),
}
impl InstrPtr {
pub(crate) fn from_usize(n: usize) -> InstrPtr {
InstrPtr::Index(n as u32)
}
pub(crate) fn as_usize(&self) -> usize {
match *self {
InstrPtr::None => panic!("attept to unwrap none InstrPtr"),
InstrPtr::Index(n) => n as usize,
}
}
pub(crate) fn is_none(self) -> bool {
matches!(self, InstrPtr::None)
}
pub(crate) fn into_option(self) -> Option<InstrPtr> {
match self {
InstrPtr::None => None,
InstrPtr::Index(_) => Some(self),
}
}
pub(crate) fn next(&self, end: usize) -> InstrPtr {
match self {
InstrPtr::None => InstrPtr::None,
InstrPtr::Index(mut i) => {
i += 1;
if i >= end as u32 {
InstrPtr::None
} else {
InstrPtr::Index(i)
}
}
}
}
}
impl From<InstrPtr> for usize {
fn from(ip: InstrPtr) -> Self {
match ip {
InstrPtr::None => usize::MAX,
InstrPtr::Index(n) => n as usize,
}
}
}
impl fmt::Display for InstrPtr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
InstrPtr::None => write!(f, "none"),
InstrPtr::Index(idx) => write!(f, "#{}", idx),
}
}
} |
Rust | hhvm/hphp/hack/src/hackc/sem_diff/lib.rs | mod body;
mod code_path;
mod helpers;
mod instr_ptr;
mod local_info;
mod node;
mod sem_diff;
mod sequence;
mod state;
mod value;
mod work_queue;
pub use sem_diff::sem_diff_unit; |
Rust | hhvm/hphp/hack/src/hackc/sem_diff/local_info.rs | use hhbc::Local;
use hhbc::LocalRange;
use hhbc::Opcode;
use hhbc::SilenceOp;
use crate::node::NodeInstr;
pub(crate) enum LocalInfo {
None,
Read(Local),
Write(Local),
Mutate(Local),
ReadRange(LocalRange),
}
impl LocalInfo {
pub(crate) fn is_none(&self) -> bool {
matches!(self, LocalInfo::None)
}
pub(crate) fn locals(&self) -> LocalRange {
match self {
LocalInfo::None => LocalRange::EMPTY,
LocalInfo::Read(local) | LocalInfo::Write(local) | LocalInfo::Mutate(local) => {
LocalRange::from_local(*local)
}
LocalInfo::ReadRange(range) => *range,
}
}
pub(crate) fn for_opcode(opcode: &Opcode<'_>) -> LocalInfo {
match opcode {
Opcode::AwaitAll(range)
| Opcode::MemoGet(_, range)
| Opcode::MemoGetEager(_, _, range)
| Opcode::MemoSet(range)
| Opcode::MemoSetEager(range) => LocalInfo::ReadRange(*range),
Opcode::AssertRATL(local, _)
| Opcode::BaseGL(local, _)
| Opcode::BaseL(local, _, _)
| Opcode::CGetL(local)
| Opcode::CGetL2(local)
| Opcode::CGetQuietL(local)
| Opcode::CUGetL(local)
| Opcode::ClsCnsL(local)
| Opcode::GetMemoKeyL(local)
| Opcode::IsTypeL(local, _)
| Opcode::IsUnsetL(local)
| Opcode::IssetL(local)
| Opcode::LIterFree(_, local)
| Opcode::LIterInit(_, local, _)
| Opcode::LIterNext(_, local, _) => LocalInfo::Read(*local),
Opcode::PopL(local) | Opcode::SetL(local) | Opcode::UnsetL(local) => {
LocalInfo::Write(*local)
}
Opcode::SetOpL(local, _) | Opcode::IncDecL(local, _) | Opcode::PushL(local) => {
LocalInfo::Mutate(*local)
}
Opcode::Silence(local, SilenceOp::Start) => LocalInfo::Write(*local),
Opcode::Silence(local, SilenceOp::End) => LocalInfo::Read(*local),
Opcode::Silence(_, _) => unreachable!(),
Opcode::AKExists
| Opcode::Add
| Opcode::AddElemC
| Opcode::AddNewElemC
| Opcode::ArrayIdx
| Opcode::ArrayMarkLegacy
| Opcode::ArrayUnmarkLegacy
| Opcode::AssertRATStk(..)
| Opcode::Await
| Opcode::BareThis(..)
| Opcode::BaseC(..)
| Opcode::BaseGC(..)
| Opcode::BaseH
| Opcode::BaseSC(..)
| Opcode::BitAnd
| Opcode::BitNot
| Opcode::BitOr
| Opcode::BitXor
| Opcode::BreakTraceHint
| Opcode::CGetCUNop
| Opcode::CGetG
| Opcode::CGetS(..)
| Opcode::CastBool
| Opcode::CastDict
| Opcode::CastDouble
| Opcode::CastInt
| Opcode::CastKeyset
| Opcode::CastString
| Opcode::CastVec
| Opcode::ChainFaults
| Opcode::CheckProp(..)
| Opcode::CheckClsReifiedGenericMismatch
| Opcode::CheckClsRGSoft
| Opcode::CheckThis
| Opcode::ClassGetC
| Opcode::ClassGetTS
| Opcode::ClassHasReifiedGenerics
| Opcode::ClassName
| Opcode::Clone
| Opcode::ClsCns(..)
| Opcode::ClsCnsD(..)
| Opcode::Cmp
| Opcode::CnsE(..)
| Opcode::ColFromArray(..)
| Opcode::CombineAndResolveTypeStruct(..)
| Opcode::Concat
| Opcode::ConcatN(..)
| 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::Enter(..)
| Opcode::Eq
| Opcode::Eval
| Opcode::Exit
| Opcode::FCallClsMethod(..)
| Opcode::FCallClsMethodD(..)
| Opcode::FCallClsMethodM(..)
| Opcode::FCallClsMethodS(..)
| Opcode::FCallClsMethodSD(..)
| Opcode::FCallCtor(..)
| Opcode::FCallFunc(..)
| Opcode::FCallFuncD(..)
| Opcode::FCallObjMethod(..)
| Opcode::FCallObjMethodD(..)
| Opcode::False
| Opcode::Fatal(..)
| Opcode::File
| Opcode::FuncCred
| Opcode::GetClsRGProp
| Opcode::Gt
| Opcode::Gte
| Opcode::HasReifiedParent
| Opcode::Idx
| Opcode::IncDecG(..)
| Opcode::IncDecM(..)
| Opcode::IncDecS(..)
| Opcode::Incl
| Opcode::InclOnce
| Opcode::InitProp(..)
| Opcode::InstanceOf
| Opcode::InstanceOfD(..)
| Opcode::Int(..)
| Opcode::IsLateBoundCls
| Opcode::IsTypeC(..)
| Opcode::IsTypeStructC(..)
| Opcode::IssetG
| Opcode::IssetS
| Opcode::IterFree(..)
| Opcode::IterInit(..)
| Opcode::IterNext(..)
| Opcode::Jmp(..)
| Opcode::JmpNZ(..)
| Opcode::JmpZ(..)
| Opcode::Keyset(..)
| Opcode::LateBoundCls
| Opcode::LazyClass(..)
| Opcode::LazyClassFromClass
| Opcode::LockObj
| Opcode::Lt
| Opcode::Lte
| Opcode::Method
| Opcode::Mod
| Opcode::Mul
| Opcode::NSame
| Opcode::NativeImpl
| Opcode::Neq
| Opcode::NewCol(..)
| Opcode::NewDictArray(..)
| Opcode::NewKeysetArray(..)
| Opcode::NewObj
| Opcode::NewObjD(..)
| Opcode::NewObjS(..)
| Opcode::NewPair
| Opcode::NewStructDict(..)
| Opcode::NewVec(..)
| Opcode::Nop
| Opcode::Not
| Opcode::Null
| Opcode::NullUninit
| Opcode::OODeclExists(..)
| Opcode::ParentCls
| Opcode::PopC
| Opcode::PopU
| Opcode::PopU2
| Opcode::Pow
| Opcode::Print
| Opcode::QueryM(..)
| Opcode::RaiseClassStringConversionWarning
| Opcode::RecordReifiedGeneric
| Opcode::Req
| Opcode::ReqDoc
| Opcode::ReqOnce
| Opcode::ResolveClass(..)
| Opcode::ResolveClsMethod(..)
| Opcode::ResolveClsMethodD(..)
| Opcode::ResolveClsMethodS(..)
| Opcode::ResolveFunc(..)
| Opcode::ResolveMethCaller(..)
| Opcode::ResolveRClsMethod(..)
| Opcode::ResolveRClsMethodD(..)
| Opcode::ResolveRClsMethodS(..)
| Opcode::ResolveRFunc(..)
| Opcode::RetC
| Opcode::RetCSuspended
| Opcode::RetM(..)
| Opcode::SSwitch { .. }
| Opcode::Same
| Opcode::Select
| Opcode::SelfCls
| Opcode::SetG
| Opcode::SetImplicitContextByValue
| Opcode::SetM(..)
| Opcode::SetOpG(..)
| Opcode::SetOpM(..)
| Opcode::SetOpS(..)
| Opcode::SetRangeM(..)
| Opcode::SetS(..)
| Opcode::Shl
| Opcode::Shr
| Opcode::String(..)
| Opcode::Sub
| Opcode::Switch(..)
| Opcode::This
| Opcode::Throw
| Opcode::ThrowAsTypeStructException
| Opcode::ThrowNonExhaustiveSwitch
| Opcode::True
| Opcode::UGetCUNop
| Opcode::UnsetG
| Opcode::UnsetM(..)
| Opcode::Vec(..)
| Opcode::VerifyImplicitContextState
| Opcode::VerifyOutType(..)
| Opcode::VerifyParamType(..)
| Opcode::VerifyParamTypeTS(..)
| Opcode::VerifyRetNonNullC
| Opcode::VerifyRetTypeC
| Opcode::VerifyRetTypeTS
| Opcode::WHResult
| Opcode::Yield
| Opcode::YieldK => LocalInfo::None,
}
}
pub(crate) fn for_node(instr: &NodeInstr<'_>) -> LocalInfo {
match instr {
NodeInstr::Opcode(opcode) => LocalInfo::for_opcode(opcode),
NodeInstr::MemberOp(_) => LocalInfo::None,
}
}
} |
Rust | hhvm/hphp/hack/src/hackc/sem_diff/node.rs | use std::fmt;
use std::rc::Rc;
use hhbc::IncDecOp;
use hhbc::Label;
use hhbc::MOpMode;
use hhbc::MemberKey;
use hhbc::Opcode;
use hhbc::QueryMOp;
use hhbc::ReadonlyOp;
use hhbc::SetOpOp;
use hhbc::SetRangeOp;
use hhbc::SrcLoc;
use hhbc::Targets;
use hhbc::TypedValue;
#[derive(Debug, Eq, PartialEq, Clone, Hash)]
pub(crate) enum Input<'arena> {
Class(String),
Constant(u32),
ConstantArray(TypedValue<'arena>),
// A value that appears exactly once in the stack or locals.
Owned(u32),
// A value that is guaranteed to be used in a read-only context.
Read(u32),
// A value that appears more than once in the stack or locals.
Shared(u32),
Undefined,
// A value that doesn't appear in the stack or locals.
Unowned(u32),
}
impl<'arena> Input<'arena> {
pub(crate) fn to_read_only(&self) -> Input<'arena> {
match *self {
Input::Owned(idx) | Input::Read(idx) | Input::Shared(idx) | Input::Unowned(idx) => {
Input::Read(idx)
}
Input::Class(_) | Input::Constant(_) | Input::ConstantArray(_) | Input::Undefined => {
self.clone()
}
}
}
}
impl fmt::Display for Input<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Input::Class(s) => write!(f, "class({s})"),
Input::Constant(v) => write!(f, "constant(#{v})"),
Input::ConstantArray(tv) => write!(f, "constant({tv:?})"),
Input::Owned(v) => write!(f, "owned(@{v})"),
Input::Read(v) => write!(f, "read(@{v})"),
Input::Shared(v) => write!(f, "shared(@{v})"),
Input::Undefined => write!(f, "undefined"),
Input::Unowned(v) => write!(f, "unowned(@{v})"),
}
}
}
#[derive(Debug, Eq, PartialEq, Hash)]
pub(crate) enum BaseOp {
Base(MOpMode, ReadonlyOp, Rc<SrcLoc>),
BaseG(MOpMode, Rc<SrcLoc>),
BaseH(Rc<SrcLoc>),
BaseSC(MOpMode, ReadonlyOp, Rc<SrcLoc>),
}
#[derive(Debug, Eq, PartialEq, Hash)]
pub(crate) struct IntermediateOp<'a> {
pub key: MemberKey<'a>,
pub mode: MOpMode,
pub src_loc: Rc<SrcLoc>,
}
#[derive(Debug, Eq, PartialEq, Hash)]
pub(crate) enum FinalOp<'a> {
IncDecM(MemberKey<'a>, IncDecOp, Rc<SrcLoc>),
QueryM(MemberKey<'a>, QueryMOp, Rc<SrcLoc>),
SetM(MemberKey<'a>, Rc<SrcLoc>),
SetRangeM(u32, SetRangeOp, Rc<SrcLoc>),
SetOpM(MemberKey<'a>, SetOpOp, Rc<SrcLoc>),
UnsetM(MemberKey<'a>, Rc<SrcLoc>),
}
impl FinalOp<'_> {
pub(crate) fn is_write(&self) -> bool {
match self {
FinalOp::QueryM { .. } => false,
FinalOp::SetRangeM { .. }
| FinalOp::UnsetM { .. }
| FinalOp::IncDecM { .. }
| FinalOp::SetM { .. }
| FinalOp::SetOpM { .. } => true,
}
}
pub(crate) fn pushes_value(&self) -> bool {
match self {
FinalOp::IncDecM(..)
| FinalOp::QueryM(..)
| FinalOp::SetM(..)
| FinalOp::SetOpM(..) => true,
FinalOp::SetRangeM(..) | FinalOp::UnsetM(..) => false,
}
}
}
#[derive(Debug, Eq, PartialEq, Hash)]
pub(crate) struct MemberOp<'a> {
pub(crate) base_op: BaseOp,
pub(crate) intermediate_ops: Vec<IntermediateOp<'a>>,
pub(crate) final_op: FinalOp<'a>,
}
#[derive(Debug, Eq, PartialEq, Hash)]
pub(crate) enum NodeInstr<'arena> {
Opcode(Opcode<'arena>),
MemberOp(MemberOp<'arena>),
}
impl Targets for NodeInstr<'_> {
fn targets(&self) -> &[Label] {
match self {
NodeInstr::MemberOp(_) => &[],
NodeInstr::Opcode(o) => o.targets(),
}
}
}
#[derive(Debug)]
pub(crate) struct Node<'arena> {
pub(crate) instr: NodeInstr<'arena>,
pub(crate) inputs: Box<[Input<'arena>]>,
pub(crate) src_loc: Rc<SrcLoc>,
} |
Rust | hhvm/hphp/hack/src/hackc/sem_diff/sem_diff.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use anyhow::Result;
use hash::HashMap;
use hhbc::Adata;
use hhbc::AdataId;
use hhbc::Attribute;
use hhbc::Body;
use hhbc::Class;
use hhbc::Constant;
use hhbc::Fatal;
use hhbc::Function;
use hhbc::Method;
use hhbc::Module;
use hhbc::Param;
use hhbc::Rule;
use hhbc::SymbolRefs;
use hhbc::TypeConstant;
use hhbc::TypedValue;
use hhbc::Typedef;
use hhbc::Unit;
use crate::code_path::CodePath;
use crate::helpers::*;
/// Compare two hhbc::Units semantically.
///
/// For a semantic comparison we don't care about any bytecode differences as
/// long as:
///
/// 1. Instructs with side-effects exist and are in the same order.
///
/// 2. Instructs that can mutate COW datatypes (dict, vec, keyset, string)
/// have the same COW behavior (if a datatype would have been mutated in-place
/// in a_unit it should be mutated in-place in b_unit).
///
/// 3. An exception thrown from an instruction will be handled the same way
///
/// In general most of the hhbc::Unit is compared using Eq - although structs are
/// destructured so an error can report where the difference occurred.
///
/// The "interesting" bit happens in `body::compare_bodies()`.
///
pub fn sem_diff_unit<'arena>(a_unit: &Unit<'arena>, b_unit: &Unit<'arena>) -> Result<()> {
let Unit {
adata: a_adata,
functions: a_functions,
classes: a_classes,
modules: a_modules,
typedefs: a_typedefs,
file_attributes: a_file_attributes,
module_use: a_module_use,
symbol_refs: a_symbol_refs,
constants: a_constants,
fatal: a_fatal,
error_symbols: _,
missing_symbols: _,
} = a_unit;
let Unit {
adata: b_adata,
functions: b_functions,
classes: b_classes,
modules: b_modules,
typedefs: b_typedefs,
file_attributes: b_file_attributes,
module_use: b_module_use,
symbol_refs: b_symbol_refs,
constants: b_constants,
fatal: b_fatal,
error_symbols: _,
missing_symbols: _,
} = b_unit;
let path = CodePath::name("Unit");
// Ignore adata for now - when we use it we'll compare that the values are
// the same at that time (because the key names may be different).
let a_adata = a_adata
.iter()
.map(|Adata { id, value }| (*id, value))
.collect();
let b_adata = b_adata
.iter()
.map(|Adata { id, value }| (*id, value))
.collect();
sem_diff_map_t(
&path.qualified("typedefs"),
a_typedefs,
b_typedefs,
sem_diff_typedef,
)?;
sem_diff_attributes(
&path.qualified("file_attributes"),
a_file_attributes,
b_file_attributes,
)?;
sem_diff_option(
&path.qualified("fatal"),
a_fatal.as_ref().into_option(),
b_fatal.as_ref().into_option(),
sem_diff_fatal,
)?;
sem_diff_map_t(
&path.qualified("constants"),
a_constants,
b_constants,
sem_diff_constant,
)?;
sem_diff_symbol_refs(&path.qualified("symbol_refs"), a_symbol_refs, b_symbol_refs)?;
sem_diff_map_t(
&path.qualified("modules"),
a_modules,
b_modules,
sem_diff_module,
)?;
sem_diff_option(
&path.qualified("module_use"),
a_module_use.as_ref().into_option(),
b_module_use.as_ref().into_option(),
sem_diff_eq,
)?;
sem_diff_map_t(
&path.qualified("functions"),
a_functions.as_arena_ref(),
b_functions.as_arena_ref(),
|path, a, b| sem_diff_function(path, a, &a_adata, b, &b_adata),
)?;
sem_diff_map_t(
&path.qualified("classes"),
a_classes.as_arena_ref(),
b_classes.as_arena_ref(),
|path, a, b| sem_diff_class(path, a, &a_adata, b, &b_adata),
)?;
Ok(())
}
fn sem_diff_attribute(path: &CodePath<'_>, a: &Attribute<'_>, b: &Attribute<'_>) -> Result<()> {
let Attribute {
name: a_name,
arguments: a_arguments,
} = a;
let Attribute {
name: b_name,
arguments: b_arguments,
} = b;
sem_diff_eq(&path.qualified("name"), a_name, b_name)?;
sem_diff_slice(
&path.qualified("arguments"),
a_arguments,
b_arguments,
sem_diff_eq,
)?;
Ok(())
}
fn sem_diff_attributes(
path: &CodePath<'_>,
a: &[Attribute<'_>],
b: &[Attribute<'_>],
) -> Result<()> {
sem_diff_slice(path, a, b, sem_diff_attribute)
}
fn sem_diff_body<'arena, 'a>(
path: &CodePath<'_>,
a: &'arena Body<'arena>,
a_adata: &'a HashMap<AdataId<'arena>, &'a TypedValue<'arena>>,
b: &'arena Body<'arena>,
b_adata: &'a HashMap<AdataId<'arena>, &'a TypedValue<'arena>>,
) -> Result<()> {
let Body {
body_instrs: _,
decl_vars: _,
num_iters: a_num_iters,
is_memoize_wrapper: a_is_memoize_wrapper,
is_memoize_wrapper_lsb: a_is_memoize_wrapper_lsb,
upper_bounds: a_upper_bounds,
shadowed_tparams: a_shadowed_tparams,
params: a_params,
return_type_info: a_return_type_info,
doc_comment: a_doc_comment,
stack_depth: _,
} = a;
let Body {
body_instrs: _,
decl_vars: _,
num_iters: b_num_iters,
is_memoize_wrapper: b_is_memoize_wrapper,
is_memoize_wrapper_lsb: b_is_memoize_wrapper_lsb,
upper_bounds: b_upper_bounds,
shadowed_tparams: b_shadowed_tparams,
params: b_params,
return_type_info: b_return_type_info,
doc_comment: b_doc_comment,
stack_depth: _,
} = b;
sem_diff_eq(&path.qualified("num_iters"), a_num_iters, b_num_iters)?;
sem_diff_slice(
&path.qualified("params"),
a_params,
b_params,
sem_diff_param,
)?;
sem_diff_eq(
&path.qualified("is_memoize_wrapper"),
a_is_memoize_wrapper,
b_is_memoize_wrapper,
)?;
sem_diff_eq(
&path.qualified("is_memoize_wrapper_lsb"),
a_is_memoize_wrapper_lsb,
b_is_memoize_wrapper_lsb,
)?;
sem_diff_eq(&path.qualified("doc_comment"), a_doc_comment, b_doc_comment)?;
sem_diff_eq(
&path.qualified("return_type_info"),
a_return_type_info,
b_return_type_info,
)?;
sem_diff_eq(
&path.qualified("upper_bounds"),
a_upper_bounds,
b_upper_bounds,
)?;
sem_diff_eq(
&path.qualified("shadowed_tparams"),
a_shadowed_tparams,
b_shadowed_tparams,
)?;
// Don't bother comparing decl_vars - when we use named vars later we'll
// compare the names to ensure we're using the same ones.
// sem_diff_set_t(&path.qualified("decl_vars"), a_decl_vars, b_decl_vars)?;
// Don't bother comparing stack_depth - for a semantic compare it's fine for
// them to be different.
// This compares the instrs themselves.
crate::body::compare_bodies(path, a, a_adata, b, b_adata)
}
fn sem_diff_param<'arena>(
path: &CodePath<'_>,
a: &'arena Param<'arena>,
b: &'arena Param<'arena>,
) -> Result<()> {
let Param {
name: a_name,
is_variadic: a_is_variadic,
is_inout: a_is_inout,
is_readonly: a_is_readonly,
user_attributes: a_user_attributes,
type_info: a_type_info,
default_value: a_default_value,
} = a;
let Param {
name: b_name,
is_variadic: b_is_variadic,
is_inout: b_is_inout,
is_readonly: b_is_readonly,
user_attributes: b_user_attributes,
type_info: b_type_info,
default_value: b_default_value,
} = b;
sem_diff_eq(&path.qualified("name"), a_name, b_name)?;
sem_diff_eq(&path.qualified("is_variadic"), a_is_variadic, b_is_variadic)?;
sem_diff_eq(&path.qualified("is_inout"), a_is_inout, b_is_inout)?;
sem_diff_eq(&path.qualified("is_readonly"), a_is_readonly, b_is_readonly)?;
sem_diff_eq(
&path.qualified("user_attributes"),
a_user_attributes,
b_user_attributes,
)?;
sem_diff_eq(&path.qualified("type_info"), a_type_info, b_type_info)?;
sem_diff_option(
&path.qualified("default_value"),
a_default_value.as_ref().into_option(),
b_default_value.as_ref().into_option(),
|path, a, b| sem_diff_eq(path, &a.expr, &b.expr),
)?;
Ok(())
}
fn sem_diff_class<'arena, 'a>(
path: &CodePath<'_>,
a: &'arena Class<'arena>,
a_adata: &'a HashMap<AdataId<'arena>, &'a TypedValue<'arena>>,
b: &'arena Class<'arena>,
b_adata: &'a HashMap<AdataId<'arena>, &'a TypedValue<'arena>>,
) -> Result<()> {
let Class {
attributes: a_attributes,
base: a_base,
implements: a_implements,
enum_includes: a_enum_includes,
name: a_name,
span: a_span,
uses: a_uses,
enum_type: a_enum_type,
methods: a_methods,
properties: a_properties,
constants: a_constants,
type_constants: a_type_constants,
ctx_constants: a_ctx_constants,
requirements: a_requirements,
upper_bounds: a_upper_bounds,
doc_comment: a_doc_comment,
flags: a_flags,
} = a;
let Class {
attributes: b_attributes,
base: b_base,
implements: b_implements,
enum_includes: b_enum_includes,
name: b_name,
span: b_span,
uses: b_uses,
enum_type: b_enum_type,
methods: b_methods,
properties: b_properties,
constants: b_constants,
type_constants: b_type_constants,
ctx_constants: b_ctx_constants,
requirements: b_requirements,
upper_bounds: b_upper_bounds,
doc_comment: b_doc_comment,
flags: b_flags,
} = b;
sem_diff_eq(&path.qualified("name"), a_name, b_name)?;
sem_diff_attributes(&path.qualified("attributes"), a_attributes, b_attributes)?;
sem_diff_eq(&path.qualified("base"), a_base, b_base)?;
sem_diff_eq(&path.qualified("implements"), a_implements, b_implements)?;
sem_diff_eq(
&path.qualified("enum_includes"),
a_enum_includes,
b_enum_includes,
)?;
sem_diff_eq(&path.qualified("span"), a_span, b_span)?;
sem_diff_eq(&path.qualified("uses"), a_uses, b_uses)?;
sem_diff_option(
&path.qualified("enum_type"),
a_enum_type.as_ref().into_option(),
b_enum_type.as_ref().into_option(),
sem_diff_eq,
)?;
sem_diff_map_t(
&path.qualified("properties"),
a_properties,
b_properties,
sem_diff_eq,
)?;
sem_diff_map_t(
&path.qualified("constants"),
a_constants,
b_constants,
sem_diff_constant,
)?;
sem_diff_map_t(
&path.qualified("type_constants"),
a_type_constants,
b_type_constants,
sem_diff_type_constant,
)?;
sem_diff_map_t(
&path.qualified("ctx_constants"),
a_ctx_constants,
b_ctx_constants,
sem_diff_eq,
)?;
sem_diff_map_t(
&path.qualified("requirements"),
a_requirements,
b_requirements,
|path, a, b| sem_diff_eq(path, &a.kind, &b.kind),
)?;
sem_diff_map_t(
&path.qualified("upper_bounds"),
a_upper_bounds,
b_upper_bounds,
|path, a, b| sem_diff_slice(path, &a.bounds, &b.bounds, sem_diff_eq),
)?;
sem_diff_eq(&path.qualified("doc_comment"), a_doc_comment, b_doc_comment)?;
sem_diff_eq(&path.qualified("flags"), a_flags, b_flags)?;
sem_diff_map_t(
&path.qualified("methods"),
a_methods,
b_methods,
|path, a, b| sem_diff_method(path, a, a_adata, b, b_adata),
)?;
Ok(())
}
fn sem_diff_constant(path: &CodePath<'_>, a: &Constant<'_>, b: &Constant<'_>) -> Result<()> {
let Constant {
name: a_name,
value: a_value,
attrs: a_attrs,
} = a;
let Constant {
name: b_name,
value: b_value,
attrs: b_attrs,
} = b;
sem_diff_eq(&path.qualified("name"), a_name, b_name)?;
sem_diff_option(
&path.qualified("value"),
a_value.as_ref().into_option(),
b_value.as_ref().into_option(),
sem_diff_eq,
)?;
sem_diff_eq(&path.qualified("attrs"), a_attrs, b_attrs)?;
Ok(())
}
fn sem_diff_type_constant(
path: &CodePath<'_>,
a: &TypeConstant<'_>,
b: &TypeConstant<'_>,
) -> Result<()> {
let TypeConstant {
name: a_name,
initializer: a_initializer,
is_abstract: a_is_abstract,
} = a;
let TypeConstant {
name: b_name,
initializer: b_initializer,
is_abstract: b_is_abstract,
} = b;
sem_diff_eq(&path.qualified("name"), a_name, b_name)?;
sem_diff_option(
&path.qualified("initializer"),
a_initializer.as_ref().into_option(),
b_initializer.as_ref().into_option(),
sem_diff_typed_value,
)?;
sem_diff_eq(&path.qualified("is_abstract"), a_is_abstract, b_is_abstract)?;
Ok(())
}
fn sem_diff_typed_value(path: &CodePath<'_>, a: &TypedValue<'_>, b: &TypedValue<'_>) -> Result<()> {
match (a, b) {
(TypedValue::Vec(av), TypedValue::Vec(bv)) => {
sem_diff_iter(path, av.iter(), bv.iter(), sem_diff_typed_value)
}
(TypedValue::Keyset(ak), TypedValue::Keyset(bk)) => {
// Because Keyset is represented as a Vec we
// need to actually remove duplicate keys while we compare. The
// order is based on the first occurance. The value is based on the
// last occurance - this matches IndexSet::insert() (and thus
// collect()).
let ad: hash::IndexSet<&TypedValue<'_>> = ak.iter().collect();
let bd: hash::IndexSet<&TypedValue<'_>> = bk.iter().collect();
sem_diff_iter(
path,
ad.iter().copied(),
bd.iter().copied(),
sem_diff_typed_value,
)
}
(TypedValue::Dict(ad), TypedValue::Dict(bd)) => {
// Because Dict is represented as a Vec of (key, value) pairs we
// need to actually remove duplicate keys while we compare. The
// order is based on the first occurance. The value is based on the
// last occurance - this matches IndexMap::insert() (and thus
// collect()).
let ad: hash::IndexMap<&TypedValue<'_>, &TypedValue<'_>> = ad
.iter()
.map(|hhbc::Entry { key, value }| (key, value))
.collect();
let bd: hash::IndexMap<&TypedValue<'_>, &TypedValue<'_>> = bd
.iter()
.map(|hhbc::Entry { key, value }| (key, value))
.collect();
sem_diff_iter(path, ad.iter(), bd.iter(), |path, a, b| {
sem_diff_typed_value(path, a.0, b.0)?;
sem_diff_typed_value(path, a.1, b.1)?;
Ok(())
})
}
_ => sem_diff_eq(path, a, b),
}
}
fn sem_diff_fatal(path: &CodePath<'_>, a: &Fatal<'_>, b: &Fatal<'_>) -> Result<()> {
sem_diff_eq(&path.index(0), &a.op, &b.op)?;
sem_diff_eq(&path.index(1), &a.loc, &b.loc)?;
sem_diff_eq(&path.index(2), &a.message, &b.message)?;
Ok(())
}
fn sem_diff_function<'arena, 'a>(
path: &CodePath<'_>,
a: &'arena Function<'arena>,
a_adata: &'a HashMap<AdataId<'arena>, &'a TypedValue<'arena>>,
b: &'arena Function<'arena>,
b_adata: &'a HashMap<AdataId<'arena>, &'a TypedValue<'arena>>,
) -> Result<()> {
let Function {
attributes: a_attributes,
name: a_name,
body: a_body,
span: a_span,
coeffects: a_coeffects,
flags: a_flags,
attrs: a_attrs,
} = a;
let Function {
attributes: b_attributes,
name: b_name,
body: b_body,
span: b_span,
coeffects: b_coeffects,
flags: b_flags,
attrs: b_attrs,
} = b;
sem_diff_eq(&path.qualified("name"), a_name, b_name)?;
sem_diff_attributes(&path.qualified("attributes"), a_attributes, b_attributes)?;
sem_diff_body(&path.qualified("body"), a_body, a_adata, b_body, b_adata)?;
sem_diff_eq(&path.qualified("span"), a_span, b_span)?;
sem_diff_eq(&path.qualified("coeffects"), a_coeffects, b_coeffects)?;
sem_diff_eq(&path.qualified("flags"), a_flags, b_flags)?;
sem_diff_eq(&path.qualified("attrs"), a_attrs, b_attrs)?;
Ok(())
}
fn sem_diff_method<'arena, 'a>(
path: &CodePath<'_>,
a: &'arena Method<'arena>,
a_adata: &'a HashMap<AdataId<'arena>, &'a TypedValue<'arena>>,
b: &'arena Method<'arena>,
b_adata: &'a HashMap<AdataId<'arena>, &'a TypedValue<'arena>>,
) -> Result<()> {
let Method {
attributes: a_attributes,
visibility: a_visibility,
name: a_name,
body: a_body,
span: a_span,
coeffects: a_coeffects,
flags: a_flags,
attrs: a_attrs,
} = a;
let Method {
attributes: b_attributes,
visibility: b_visibility,
name: b_name,
body: b_body,
span: b_span,
coeffects: b_coeffects,
flags: b_flags,
attrs: b_attrs,
} = b;
sem_diff_attributes(&path.qualified("attributes"), a_attributes, b_attributes)?;
sem_diff_eq(&path.qualified("visibility"), a_visibility, b_visibility)?;
sem_diff_eq(&path.qualified("name"), a_name, b_name)?;
sem_diff_body(&path.qualified("body"), a_body, a_adata, b_body, b_adata)?;
sem_diff_eq(&path.qualified("span"), a_span, b_span)?;
sem_diff_eq(&path.qualified("coeffects"), a_coeffects, b_coeffects)?;
sem_diff_eq(&path.qualified("flags"), a_flags, b_flags)?;
sem_diff_eq(&path.qualified("attrs"), a_attrs, b_attrs)?;
Ok(())
}
fn sem_diff_rule<'arena>(path: &CodePath<'_>, a: &Rule<'arena>, b: &Rule<'arena>) -> Result<()> {
let Rule {
kind: a_kind,
name: a_name,
} = a;
let Rule {
kind: b_kind,
name: b_name,
} = b;
sem_diff_eq(&path.qualified("kind"), a_kind, b_kind)?;
sem_diff_eq(&path.qualified("name"), a_name, b_name)?;
Ok(())
}
fn sem_diff_module<'arena>(
path: &CodePath<'_>,
a: &Module<'arena>,
b: &Module<'arena>,
) -> Result<()> {
let Module {
attributes: a_attributes,
name: a_name,
span: a_span,
doc_comment: a_doc_comment,
exports: a_exports,
imports: a_imports,
} = a;
let Module {
attributes: b_attributes,
name: b_name,
span: b_span,
doc_comment: b_doc_comment,
exports: b_exports,
imports: b_imports,
} = b;
sem_diff_eq(&path.qualified("name"), a_name, b_name)?;
sem_diff_attributes(&path.qualified("attributes"), a_attributes, b_attributes)?;
sem_diff_eq(&path.qualified("span"), a_span, b_span)?;
sem_diff_eq(&path.qualified("doc_comment"), a_doc_comment, b_doc_comment)?;
sem_diff_option(
&path.qualified("exports"),
a_exports.as_ref().into_option(),
b_exports.as_ref().into_option(),
|c, a, b| sem_diff_slice(c, a, b, sem_diff_rule),
)?;
sem_diff_option(
&path.qualified("imports"),
a_imports.as_ref().into_option(),
b_imports.as_ref().into_option(),
|c, a, b| sem_diff_slice(c, a, b, sem_diff_rule),
)?;
Ok(())
}
fn sem_diff_symbol_refs<'arena>(
path: &CodePath<'_>,
a: &SymbolRefs<'arena>,
b: &SymbolRefs<'arena>,
) -> Result<()> {
let SymbolRefs {
includes: a_includes,
constants: a_constants,
functions: a_functions,
classes: a_classes,
} = a;
let SymbolRefs {
includes: b_includes,
constants: b_constants,
functions: b_functions,
classes: b_classes,
} = b;
sem_diff_slice(
&path.qualified("includes"),
a_includes,
b_includes,
sem_diff_eq,
)?;
sem_diff_slice(
&path.qualified("constants"),
a_constants,
b_constants,
sem_diff_eq,
)?;
sem_diff_slice(
&path.qualified("functions"),
a_functions,
b_functions,
sem_diff_eq,
)?;
sem_diff_slice(
&path.qualified("classes"),
a_classes,
b_classes,
sem_diff_eq,
)?;
Ok(())
}
fn sem_diff_typedef<'arena>(
path: &CodePath<'_>,
a: &Typedef<'arena>,
b: &Typedef<'arena>,
) -> Result<()> {
let Typedef {
name: a_name,
attributes: a_attributes,
type_info_union: a_type_info_union,
type_structure: a_type_structure,
span: a_span,
attrs: a_attrs,
case_type: a_case_type,
} = a;
let Typedef {
name: b_name,
attributes: b_attributes,
type_info_union: b_type_info_union,
type_structure: b_type_structure,
span: b_span,
attrs: b_attrs,
case_type: b_case_type,
} = b;
sem_diff_eq(&path.qualified("name"), a_name, b_name)?;
sem_diff_attributes(&path.qualified("attributes"), a_attributes, b_attributes)?;
sem_diff_eq(
&path.qualified("type_info"),
a_type_info_union,
b_type_info_union,
)?;
sem_diff_eq(
&path.qualified("type_structure"),
a_type_structure,
b_type_structure,
)?;
sem_diff_eq(&path.qualified("span"), a_span, b_span)?;
sem_diff_eq(&path.qualified("attrs"), a_attrs, b_attrs)?;
sem_diff_eq(&path.qualified("cast_type"), a_case_type, b_case_type)?;
Ok(())
} |
Rust | hhvm/hphp/hack/src/hackc/sem_diff/sequence.rs | use anyhow::bail;
use anyhow::Result;
use ffi::Slice;
use hhbc::Opcode;
use itertools::Itertools;
use log::trace;
use crate::code_path::CodePath;
use crate::helpers::*;
use crate::node::Input;
use crate::node::Node;
use crate::node::NodeInstr;
pub(crate) struct Sequence<'arena> {
pub(crate) debug_name: String,
pub(crate) instrs: Vec<Node<'arena>>,
// If the sequence ends on a loopback (so we terminate it early to avoid
// infinite loops) then this tells us where it looped back to.
pub(crate) loopback: Option<usize>,
}
impl<'arena> Sequence<'arena> {
pub(crate) fn compare(path: &CodePath<'_>, a: Self, b: Self) -> Result<()> {
trace!("--- Compare {} and {}", a.debug_name, b.debug_name);
let seq_a = collect_sequence(&a, b.instrs.len());
let seq_b = collect_sequence(&b, a.instrs.len());
let mut it_a = seq_a.iter().copied();
let mut it_b = seq_b.iter().copied();
let mut idx = 0;
loop {
let instr_a = it_a.next();
let instr_b = it_b.next();
let (instr_a, instr_b) = match (instr_a, instr_b) {
(None, None) => break,
(Some(_), None) | (None, Some(_)) => return bail_early_end(path, instr_a, instr_b),
(Some(a), Some(b)) => (a, b),
};
trace!(" COMPARE\n {:?}\n {:?}", instr_a, instr_b);
compare_instrs(&path.index(idx), &instr_a.instr, &instr_b.instr)?;
let cow_inputs = is_cow_instr(&instr_a.instr);
sem_diff_slice(
&path.index(idx).qualified("inputs"),
&instr_a.inputs,
&instr_b.inputs,
|p, a, b| sem_diff_input(p, a, b, cow_inputs),
)?;
sem_diff_eq(
&path.index(idx).qualified("src_loc"),
&instr_a.src_loc,
&instr_b.src_loc,
)?;
idx += 1;
}
trace!(" - compare done");
Ok(())
}
}
fn compare_instrs<'arena>(
path: &CodePath<'_>,
a: &NodeInstr<'arena>,
b: &NodeInstr<'arena>,
) -> Result<()> {
// Note: If the thing that's different is a Label that's
// actually okay because we track labels independently.
if std::mem::discriminant(a) != std::mem::discriminant(b) {
bail!("Mismatch in {}:\n{:?}\n{:?}", path, a, b);
}
use NodeInstr as I;
use Opcode as O;
match (a, b) {
(I::Opcode(O::Enter(_)), I::Opcode(O::Enter(_)))
| (I::Opcode(O::Jmp(_)), I::Opcode(O::Jmp(_)))
| (I::Opcode(O::JmpNZ(_)), I::Opcode(O::JmpNZ(_)))
| (I::Opcode(O::JmpZ(_)), I::Opcode(O::JmpZ(_))) => Ok(()),
(I::Opcode(O::IterInit(a0, _)), I::Opcode(O::IterInit(a1, _))) => sem_diff_eq(path, a0, a1),
(I::Opcode(O::IterNext(a0, _)), I::Opcode(O::IterNext(a1, _))) => sem_diff_eq(path, a0, a1),
(I::Opcode(O::LIterInit(a0, b0, _)), I::Opcode(O::LIterInit(a1, b1, _))) => {
sem_diff_eq(path, &(a0, b0), &(a1, b1))
}
(I::Opcode(O::LIterNext(a0, b0, _)), I::Opcode(O::LIterNext(a1, b1, _))) => {
sem_diff_eq(path, &(a0, b0), &(a1, b1))
}
(I::Opcode(O::MemoGet(_, a0)), I::Opcode(O::MemoGet(_, a1))) => sem_diff_eq(path, a0, a1),
(I::Opcode(O::MemoGetEager(_, _, a0)), I::Opcode(O::MemoGetEager(_, _, a1))) => {
sem_diff_eq(path, a0, a1)
}
(I::Opcode(O::Switch(a0, b0, _)), I::Opcode(O::Switch(a1, b1, _))) => {
sem_diff_eq(path, &(a0, b0), &(a1, b1))
}
(
I::Opcode(O::FCallClsMethod(fca0, a0, b0)),
I::Opcode(O::FCallClsMethod(fca1, a1, b1)),
) => {
sem_diff_fca(path, fca0, fca1)?;
sem_diff_eq(path, &(a0, b0), &(a1, b1))
}
(
I::Opcode(O::FCallClsMethodD(fca0, a0, b0)),
I::Opcode(O::FCallClsMethodD(fca1, a1, b1)),
) => {
sem_diff_fca(path, fca0, fca1)?;
sem_diff_eq(path, &(a0, b0), &(a1, b1))
}
(
I::Opcode(O::FCallClsMethodS(fca0, a0, b0)),
I::Opcode(O::FCallClsMethodS(fca1, a1, b1)),
) => {
sem_diff_fca(path, fca0, fca1)?;
sem_diff_eq(path, &(a0, b0), &(a1, b1))
}
(
I::Opcode(O::FCallClsMethodSD(fca0, a0, b0, c0)),
I::Opcode(O::FCallClsMethodSD(fca1, a1, b1, c1)),
) => {
sem_diff_fca(path, fca0, fca1)?;
sem_diff_eq(path, &(a0, b0, c0), &(a1, b1, c1))
}
(I::Opcode(O::FCallCtor(fca0, a0)), I::Opcode(O::FCallCtor(fca1, a1))) => {
sem_diff_fca(path, fca0, fca1)?;
sem_diff_eq(path, a0, a1)
}
(I::Opcode(O::FCallFunc(fca0)), I::Opcode(O::FCallFunc(fca1))) => {
sem_diff_fca(path, fca0, fca1)
}
(I::Opcode(O::FCallFuncD(fca0, a0)), I::Opcode(O::FCallFuncD(fca1, a1))) => {
sem_diff_fca(path, fca0, fca1)?;
sem_diff_eq(path, a0, a1)
}
(
I::Opcode(O::FCallObjMethod(fca0, a0, b0)),
I::Opcode(O::FCallObjMethod(fca1, a1, b1)),
) => {
sem_diff_fca(path, fca0, fca1)?;
sem_diff_eq(path, &(a0, b0), &(a1, b1))
}
(
I::Opcode(O::FCallObjMethodD(fca0, a0, b0, c0)),
I::Opcode(O::FCallObjMethodD(fca1, a1, b1, c1)),
) => {
sem_diff_fca(path, fca0, fca1)?;
sem_diff_eq(path, &(a0, b0, c0), &(a1, b1, c1))
}
(
I::Opcode(O::SSwitch {
cases: a0,
targets: _,
_0: _,
}),
I::Opcode(O::SSwitch {
cases: a1,
targets: _,
_0: _,
}),
) => sem_diff_eq(path, a0, a1),
(a, b) => {
match a {
I::Opcode(a) => {
use hhbc::Targets;
debug_assert!(
a.targets().iter().all(|target| !target.is_valid()),
"This instr has a target that should have been ignored"
);
}
_ => {}
}
sem_diff_eq(path, a, b)
}
}
}
fn sem_diff_input(
path: &CodePath<'_>,
input0: &Input<'_>,
input1: &Input<'_>,
check_cow: bool,
) -> Result<()> {
if check_cow {
match (input0, input1) {
(Input::Read(a), Input::Read(b))
| (Input::Unowned(a), Input::Unowned(b))
| (Input::Owned(a), Input::Owned(b) | Input::Unowned(b))
| (Input::Shared(a), Input::Shared(b) | Input::Owned(b) | Input::Unowned(b)) => {
// We allow 'b' to be 'less owned' than 'a'.
sem_diff_eq(path, a, b)
}
(a, b) => sem_diff_eq(path, a, b),
}
} else {
match (input0, input1) {
(
Input::Read(a) | Input::Unowned(a) | Input::Owned(a) | Input::Shared(a),
Input::Read(b) | Input::Unowned(b) | Input::Owned(b) | Input::Shared(b),
) => sem_diff_eq(path, a, b),
(a, b) => sem_diff_eq(path, a, b),
}
}
}
/// Returns true if this is an instruction that could cause a COW.
fn is_cow_instr(instr: &NodeInstr<'_>) -> bool {
match instr {
// Constants
NodeInstr::Opcode(
Opcode::Dict(..)
| Opcode::Dir
| Opcode::Double(..)
| Opcode::False
| Opcode::File
| Opcode::FuncCred
| Opcode::Int(..)
| Opcode::Keyset(..)
| Opcode::LazyClass(..)
| Opcode::LazyClassFromClass
| Opcode::NewCol(..)
| Opcode::Null
| Opcode::NullUninit
| Opcode::String(..)
| Opcode::This
| Opcode::True
| Opcode::Vec(..),
) => false,
// Stack/Local manipulation
NodeInstr::Opcode(
Opcode::CGetL(..)
| Opcode::CGetL2(..)
| Opcode::CnsE(..)
| Opcode::Dup
| Opcode::Lt
| Opcode::Mod
| Opcode::PopC
| Opcode::PopL(..)
| Opcode::PushL(..)
| Opcode::Same
| Opcode::SetL(..)
| Opcode::UnsetL(..)
| Opcode::CGetCUNop
| Opcode::CGetG
| Opcode::CGetQuietL(..)
| Opcode::CGetS(..)
| Opcode::CUGetL(..),
) => false,
// Is operations
NodeInstr::Opcode(
Opcode::InstanceOf
| Opcode::InstanceOfD(..)
| Opcode::IsLateBoundCls
| Opcode::IsTypeC(..)
| Opcode::IsTypeL(..)
| Opcode::IsTypeStructC(..)
| Opcode::IsUnsetL(..)
| Opcode::IssetG
| Opcode::IssetL(..)
| Opcode::IssetS,
) => false,
// Control flow
NodeInstr::Opcode(
Opcode::Enter(_)
| Opcode::Jmp(_)
| Opcode::Nop
| Opcode::JmpNZ(..)
| Opcode::JmpZ(..)
| Opcode::RetC
| Opcode::RetCSuspended
| Opcode::RetM(..)
| Opcode::SSwitch { .. }
| Opcode::Switch(..)
| Opcode::Throw
| Opcode::ThrowAsTypeStructException
| Opcode::ThrowNonExhaustiveSwitch,
) => false,
// Other Opcodes
NodeInstr::Opcode(Opcode::Concat | Opcode::ConcatN(..)) => false,
// Operators
NodeInstr::Opcode(
Opcode::Add
| Opcode::BitAnd
| Opcode::BitNot
| Opcode::BitOr
| Opcode::BitXor
| Opcode::Cmp
| Opcode::Div
| Opcode::Eq
| Opcode::Gt
| Opcode::Gte
| Opcode::Idx
| Opcode::Lte
| Opcode::Mul
| Opcode::NSame
| Opcode::Neq
| Opcode::Not
| Opcode::Pow
| Opcode::Print
| Opcode::Select
| Opcode::Shl
| Opcode::Shr
| Opcode::Sub
| Opcode::AKExists
| Opcode::ArrayIdx
| Opcode::AssertRATL(..)
| Opcode::AssertRATStk(..)
| Opcode::Await
| Opcode::AwaitAll(..)
| Opcode::BareThis(..)
| Opcode::BreakTraceHint
| Opcode::CheckProp(..)
| Opcode::CheckClsReifiedGenericMismatch
| Opcode::CheckClsRGSoft
| Opcode::CheckThis
| Opcode::ClassGetC
| Opcode::ClassGetTS
| Opcode::ClassHasReifiedGenerics
| Opcode::ClassName
| Opcode::ClsCns(..)
| Opcode::ClsCnsD(..)
| Opcode::ClsCnsL(..)
| Opcode::ContCheck(..)
| Opcode::ContCurrent
| Opcode::ContEnter
| Opcode::ContGetReturn
| Opcode::ContKey
| Opcode::ContRaise
| Opcode::ContValid
| Opcode::CreateCont
| Opcode::CreateSpecialImplicitContext
| Opcode::DblAsBits
| Opcode::Exit
| Opcode::GetClsRGProp
| Opcode::GetMemoKeyL(..)
| Opcode::MemoGet(..)
| Opcode::MemoGetEager(..)
| Opcode::ParentCls
| Opcode::PopU
| Opcode::PopU2,
) => false,
// Casting
NodeInstr::Opcode(
Opcode::CastBool
| Opcode::CastDict
| Opcode::CastDouble
| Opcode::CastInt
| Opcode::CastKeyset
| Opcode::CastString
| Opcode::CastVec,
) => false,
// Verify
NodeInstr::Opcode(
Opcode::VerifyImplicitContextState
| Opcode::VerifyOutType(..)
| Opcode::VerifyParamType(..)
| Opcode::VerifyParamTypeTS(..)
| Opcode::VerifyRetNonNullC
| Opcode::VerifyRetTypeC
| Opcode::VerifyRetTypeTS,
) => false,
NodeInstr::Opcode(
Opcode::AddElemC
| Opcode::AddNewElemC
| Opcode::ArrayMarkLegacy
| Opcode::ArrayUnmarkLegacy
| Opcode::BaseC(..)
| Opcode::BaseGC(..)
| Opcode::BaseGL(..)
| Opcode::BaseH
| Opcode::BaseL(..)
| Opcode::BaseSC(..)
| Opcode::ChainFaults
| Opcode::Clone
| Opcode::ColFromArray(..)
| Opcode::CombineAndResolveTypeStruct(..)
| Opcode::CreateCl(..)
| Opcode::Dim(..)
| Opcode::Eval
| Opcode::FCallClsMethod(..)
| Opcode::FCallClsMethodD(..)
| Opcode::FCallClsMethodM(..)
| Opcode::FCallClsMethodS(..)
| Opcode::FCallClsMethodSD(..)
| Opcode::FCallCtor(..)
| Opcode::FCallFunc(..)
| Opcode::FCallFuncD(..)
| Opcode::FCallObjMethod(..)
| Opcode::FCallObjMethodD(..)
| Opcode::Fatal(..)
| Opcode::HasReifiedParent
| Opcode::IncDecG(..)
| Opcode::IncDecL(..)
| Opcode::IncDecM(..)
| Opcode::IncDecS(..)
| Opcode::Incl
| Opcode::InclOnce
| Opcode::InitProp(..)
| Opcode::IterFree(..)
| Opcode::IterInit(..)
| Opcode::IterNext(..)
| Opcode::LIterFree(..)
| Opcode::LIterInit(..)
| Opcode::LIterNext(..)
| Opcode::LateBoundCls
| Opcode::LockObj
| Opcode::MemoSet(..)
| Opcode::MemoSetEager(..)
| Opcode::Method
| Opcode::NativeImpl
| Opcode::NewDictArray(..)
| Opcode::NewKeysetArray(..)
| Opcode::NewObj
| Opcode::NewObjD(..)
| Opcode::NewObjS(..)
| Opcode::NewPair
| Opcode::NewStructDict(..)
| Opcode::NewVec(..)
| Opcode::OODeclExists(..)
| Opcode::QueryM(..)
| Opcode::RaiseClassStringConversionWarning
| Opcode::RecordReifiedGeneric
| Opcode::Req
| Opcode::ReqDoc
| Opcode::ReqOnce
| Opcode::ResolveClass(..)
| Opcode::ResolveClsMethod(..)
| Opcode::ResolveClsMethodD(..)
| Opcode::ResolveClsMethodS(..)
| Opcode::ResolveFunc(..)
| Opcode::ResolveMethCaller(..)
| Opcode::ResolveRClsMethod(..)
| Opcode::ResolveRClsMethodD(..)
| Opcode::ResolveRClsMethodS(..)
| Opcode::ResolveRFunc(..)
| Opcode::SelfCls
| Opcode::SetG
| Opcode::SetImplicitContextByValue
| Opcode::SetM(..)
| Opcode::SetOpG(..)
| Opcode::SetOpL(..)
| Opcode::SetOpM(..)
| Opcode::SetOpS(..)
| Opcode::SetRangeM(..)
| Opcode::SetS(..)
| Opcode::Silence(..)
| Opcode::UGetCUNop
| Opcode::UnsetG
| Opcode::UnsetM(..)
| Opcode::WHResult
| Opcode::Yield
| Opcode::YieldK,
) => true,
NodeInstr::MemberOp(_) => true,
}
}
fn sem_diff_fca<'arena>(
path: &CodePath<'_>,
fca0: &hhbc::FCallArgs<'arena>,
fca1: &hhbc::FCallArgs<'arena>,
) -> Result<()> {
let hhbc::FCallArgs {
flags: flags0,
async_eager_target: _,
num_args: num_args0,
num_rets: num_rets0,
inouts: inouts0,
readonly: readonly0,
context: context0,
} = fca0;
let hhbc::FCallArgs {
flags: flags1,
async_eager_target: _,
num_args: num_args1,
num_rets: num_rets1,
inouts: inouts1,
readonly: readonly1,
context: context1,
} = fca1;
fn cmp_slice_where_empty_is_all_false(
path: &CodePath<'_>,
a: &Slice<'_, bool>,
b: &Slice<'_, bool>,
) -> Result<()> {
match (a.is_empty(), b.is_empty()) {
(true, true) => {}
(true, false) => {
if b.iter().any(|x| *x) {
bail!("Mismatch in {}:\n{:?}\n{:?}", path, a, b);
}
}
(false, true) => {
if a.iter().any(|x| *x) {
bail!("Mismatch in {}:\n{:?}\n{:?}", path, a, b);
}
}
(false, false) => sem_diff_eq(path, a, b)?,
}
Ok(())
}
cmp_slice_where_empty_is_all_false(&path.qualified("inouts"), inouts0, inouts1)?;
cmp_slice_where_empty_is_all_false(&path.qualified("readonly"), readonly0, readonly1)?;
sem_diff_eq(
path,
&(flags0, num_args0, num_rets0, context0),
&(flags1, num_args1, num_rets1, context1),
)
}
fn bail_early_end(
path: &CodePath<'_>,
instr_a: Option<&Node<'_>>,
instr_b: Option<&Node<'_>>,
) -> Result<()> {
bail!(
"Mismatch in {}:
{:?}
{:?}
One side ended before the other. This can happen due to a bytecode mismatch or
due to a try/catch mismatch",
path,
instr_a,
instr_b
);
}
fn collect_sequence<'arena, 'a>(
seq: &'a Sequence<'arena>,
min_len: usize,
) -> Vec<&'a Node<'arena>> {
if min_len <= seq.instrs.len() || seq.loopback.is_none() {
return seq.instrs.iter().collect_vec();
}
let loopback = seq.loopback.unwrap();
seq.instrs
.iter()
.chain(seq.instrs[loopback..].iter().cycle())
.take(min_len)
.collect_vec()
} |
Rust | hhvm/hphp/hack/src/hackc/sem_diff/state.rs | use std::collections::hash_map::Entry;
use std::rc::Rc;
use anyhow::anyhow;
use anyhow::bail;
use anyhow::Result;
use ffi::Slice;
use ffi::Str;
use hash::HashMap;
use hhbc::AdataId;
use hhbc::ClassName;
use hhbc::Dummy;
use hhbc::FCallArgs;
use hhbc::IncDecOp;
use hhbc::Instruct;
use hhbc::IterArgs;
use hhbc::IterId;
use hhbc::Label;
use hhbc::Local;
use hhbc::LocalRange;
use hhbc::MemberKey;
use hhbc::NumParams;
use hhbc::Opcode;
use hhbc::Pseudo;
use hhbc::ReadonlyOp;
use hhbc::SetOpOp;
use hhbc::SrcLoc;
use hhbc::SwitchKind;
use hhbc::Targets;
use hhbc::TypedValue;
use hhbc_gen::InstrFlags;
use hhbc_gen::Outputs;
use itertools::Itertools;
use log::trace;
use newtype::BuildIdHasher;
use crate::body::Body;
use crate::instr_ptr::InstrPtr;
use crate::local_info::LocalInfo;
use crate::node;
use crate::node::Input;
use crate::node::Node;
use crate::node::NodeInstr;
use crate::sequence::Sequence;
use crate::value::Value;
use crate::value::ValueBuilder;
/// A State is an abstract interpreter over HHVM bytecode.
#[derive(Clone)]
pub(crate) struct State<'arena, 'a> {
body: &'a Body<'arena>,
debug_name: &'static str,
pub(crate) ip: InstrPtr,
pub(crate) iterators: IterIdMap<IterState>,
pub(crate) locals: HashMap<Local, Value>,
pub(crate) stack: Vec<Value>,
adata: &'a HashMap<AdataId<'arena>, &'a TypedValue<'arena>>,
}
impl<'arena, 'a> State<'arena, 'a> {
pub(crate) fn new(
body: &'a Body<'arena>,
debug_name: &'static str,
adata: &'a HashMap<AdataId<'arena>, &'a TypedValue<'arena>>,
) -> Self {
Self {
body,
debug_name,
ip: InstrPtr::from_usize(0),
iterators: Default::default(),
locals: Default::default(),
stack: Default::default(),
adata,
}
}
/// Return an Input for a Value where the Input represents a non-COW
/// datatype.
fn non_cow(&self, value: Value) -> Input<'arena> {
match value {
Value::Constant(c) => Input::Constant(c),
Value::Defined(v) => Input::Read(v),
Value::Undefined => Input::Undefined,
}
}
/// Compute the ownership for a Value and return an Input representing that
/// Value with its ownership.
fn reffy(&self, value: Value) -> Input<'arena> {
match value {
Value::Constant(c) => Input::Constant(c),
Value::Defined(v) => {
let mut count = 0;
for &sv in &self.stack {
count += (sv == value) as usize;
}
for &lv in self.locals.values() {
count += (lv == value) as usize;
}
match count {
0 => Input::Unowned(v),
1 => Input::Owned(v),
_ => Input::Shared(v),
}
}
Value::Undefined => Input::Undefined,
}
}
/// Run the abstract interpreter and collect a sequence of checkpoint
/// instructions along with their abstract inputs. The sequence ends when
/// the interpreter reaches a terminal instruction (like a RetC) or a
/// try/catch change. Any conditional control flows (like JmpZ or throws)
/// are also returned.
pub(crate) fn collect(
mut self,
value_builder: &mut ValueBuilder<'arena>,
) -> Result<StateCollect<'arena, 'a>> {
let debug_name = format!("{}{}", self.debug_name, self.ip);
trace!("--- Collecting sequence {}", debug_name);
self.debug_state();
let mut builder = InstrSeqBuilder {
seq: Default::default(),
forks: Default::default(),
value_builder,
};
let mut seen_ip: HashMap<InstrPtr, usize> = HashMap::default();
let mut catch_ip = self.body.lookup_catch(self.ip);
let mut loopback = None;
loop {
if self.is_done() {
trace!(" - ends at {} with is_done()", self.ip);
break;
}
match seen_ip.entry(self.ip) {
Entry::Occupied(e) => {
// If we've already seen this IP then record where we looped
// back to.
let target = *e.get();
loopback = Some(target);
trace!(" - ends at {} with loopback to {}", self.ip, target);
break;
}
Entry::Vacant(e) => {
// Record where this IP ends up in the sequence.
e.insert(builder.seq.len());
}
}
// A Sequence must not cross try/catch blocks BUT if we haven't
// actually recorded any instrs yet then we can restart with the new
// catch block.
let new_catch_ip = self.body.lookup_catch(self.ip);
if catch_ip != new_catch_ip {
if builder.seq.is_empty() {
catch_ip = new_catch_ip;
} else {
trace!(" - ends at {} with new Catch Block", self.ip);
builder.forks.push(self.clone());
break;
}
}
self.debug();
self.step(&mut builder)?;
self.debug_state();
}
trace!(
" - Forks: [{}]",
builder
.forks
.iter()
.map(|state| state.ip.to_string())
.join(", ")
);
let seq = Sequence {
instrs: builder.seq,
debug_name,
loopback,
};
let catch_state = if !catch_ip.is_none() {
let state = self.clone_for_catch(catch_ip);
trace!(" - Catch State:");
state.debug_state();
Some(state)
} else {
None
};
Ok(StateCollect {
seq,
forks: builder.forks,
catch_state,
})
}
fn fork(&self, builder: &mut InstrSeqBuilder<'arena, 'a, '_>, targets: &[Label]) {
self.fork_and_adjust(builder, targets, |_, _, _| {})
}
fn fork_and_adjust<F>(
&self,
builder: &mut InstrSeqBuilder<'arena, 'a, '_>,
targets: &[Label],
and_then: F,
) where
F: Fn(&mut Self, &mut InstrSeqBuilder<'arena, 'a, '_>, usize),
{
for (idx, target) in targets.iter().enumerate() {
let mut fork = self.clone_with_jmp(target);
// Some Instructs modify the stack on the receiving end
and_then(&mut fork, builder, idx);
trace!(
" FORK to label {} ({})",
target,
self.body.label_to_ip.get(target).unwrap()
);
fork.debug_state();
builder.forks.push(fork);
}
}
pub(crate) fn clone_with_jmp(&self, target: &Label) -> Self {
let ip = *self.body.label_to_ip.get(target).unwrap();
Self {
body: self.body,
debug_name: self.debug_name,
ip,
iterators: self.iterators.clone(),
locals: self.locals.clone(),
stack: self.stack.clone(),
adata: self.adata,
}
}
pub(crate) fn clone_for_catch(&self, ip: InstrPtr) -> Self {
Self {
body: self.body,
debug_name: self.debug_name,
ip,
iterators: self.iterators.clone(),
locals: self.locals.clone(),
stack: vec![],
adata: self.adata,
}
}
pub(crate) fn is_done(&self) -> bool {
self.ip.is_none()
}
pub(crate) fn debug(&self) {
if let Some(instr) = self.instr() {
let catch = if let Some(ip) = self.body.lookup_catch(self.ip).into_option() {
format!(", catch {ip}")
} else {
"".to_string()
};
trace!(" {ip:4} INSTR: {instr:?}{catch}", ip = self.ip.to_string(),);
} else {
trace!(" DONE");
}
}
fn debug_local_name(&self, local: Local) -> String {
if !local.is_valid() {
"NV".to_string()
} else if let Some(name) = self.body.local_name(local) {
format!("{}({})", name.as_bstr(), local)
} else {
format!("{}", local)
}
}
pub(crate) fn debug_state(&self) {
trace!(
" STACK: [{}], LOCALS: [{}], ITER: [{}]",
self.stack.iter().map(ToString::to_string).join(", "),
self.locals
.iter()
.sorted_by_key(|k| k.0)
.map(|(k, v)| { format!("{} => {}", self.debug_local_name(*k), v) })
.join(", "),
self.iterators
.iter()
.sorted_by_key(|x| x.0)
.map(|(idx, iter_state)| {
let key = self.debug_local_name(iter_state.key);
let value = self.debug_local_name(iter_state.value);
let base = iter_state.base;
format!("{idx} => {{ K: {key}, V: {value}, B: {base} }}")
})
.join(", "),
);
}
/// Step the abstract virtual machine forward one instruction. See
/// Self::step_default_handler() for the common handler.
fn step(&mut self, builder: &mut InstrSeqBuilder<'arena, 'a, '_>) -> Result<()> {
let instr = self.instr().unwrap();
match *instr {
Instruct::Opcode(
ref opcode @ Opcode::ClsCnsD(_, _)
| ref opcode @ Opcode::CnsE(_)
| ref opcode @ Opcode::Dict(_)
| ref opcode @ Opcode::Dir
| ref opcode @ Opcode::Double(_)
| ref opcode @ Opcode::False
| ref opcode @ Opcode::File
| ref opcode @ Opcode::FuncCred
| ref opcode @ Opcode::Int(_)
| ref opcode @ Opcode::Keyset(_)
| ref opcode @ Opcode::LateBoundCls
| ref opcode @ Opcode::LazyClass(..)
| ref opcode @ Opcode::Method
| ref opcode @ Opcode::NewCol(..)
| ref opcode @ Opcode::NewDictArray(_)
| ref opcode @ Opcode::Null
| ref opcode @ Opcode::NullUninit
| ref opcode @ Opcode::ParentCls
| ref opcode @ Opcode::SelfCls
| ref opcode @ Opcode::String(_)
| ref opcode @ Opcode::This
| ref opcode @ Opcode::True
| ref opcode @ Opcode::Vec(_),
) => self.step_constant(builder, opcode)?,
Instruct::Opcode(
Opcode::BaseC(..)
| Opcode::BaseGC(..)
| Opcode::BaseH
| Opcode::BaseGL(..)
| Opcode::BaseL(..)
| Opcode::BaseSC(..),
) => self.step_member_op(builder)?,
Instruct::Opcode(Opcode::CreateCl(num_params, classname)) => {
self.step_create_cl(builder, num_params, &classname)?;
}
Instruct::Opcode(
Opcode::Dim(..)
| Opcode::QueryM(..)
| Opcode::SetM(..)
| Opcode::IncDecM(..)
| Opcode::SetOpM(..)
| Opcode::UnsetM(..)
| Opcode::SetRangeM(..),
) => {
unreachable!();
}
Instruct::Opcode(Opcode::Dup) => {
let tmp = self.stack_pop();
self.stack_push(tmp);
self.stack_push(tmp);
}
Instruct::Opcode(Opcode::CGetL(local)) => {
self.stack_push(self.local_get(&local));
}
Instruct::Opcode(Opcode::CGetL2(local)) => {
let tmp = self.stack_pop();
self.stack_push(self.local_get(&local));
self.stack_push(tmp);
}
Instruct::Opcode(Opcode::CGetQuietL(local)) => {
self.stack_push(self.local_get(&local));
}
Instruct::Opcode(Opcode::CUGetL(local)) => {
self.stack_push(self.local_get(&local));
}
Instruct::Opcode(Opcode::IncDecL(local, op)) => {
self.step_inc_dec_l(builder, local, op);
}
Instruct::Opcode(Opcode::IsUnsetL(_local)) => todo!(),
Instruct::Opcode(Opcode::PopL(local)) => {
self.step_pop_l(builder, local);
}
Instruct::Opcode(Opcode::PushL(local)) => {
self.step_push_l(local);
}
Instruct::Opcode(Opcode::SetL(local)) => {
self.step_set_l(builder, local);
}
Instruct::Opcode(Opcode::SetOpL(local, set_op_op)) => {
self.step_set_op_l(builder, local, set_op_op);
}
Instruct::Opcode(Opcode::UnsetL(local)) => {
self.locals.remove(&local);
}
Instruct::Opcode(Opcode::LIterFree(..)) => todo!(),
Instruct::Opcode(Opcode::LIterInit(..)) => todo!(),
Instruct::Opcode(Opcode::LIterNext(..)) => todo!(),
Instruct::Opcode(Opcode::MemoGetEager(targets, _, range)) => {
self.step_memo_get_eager(builder, targets, range)?;
}
Instruct::Opcode(Opcode::IterInit(ref iter_args, target)) => {
self.step_iter_init(builder, iter_args, target);
}
Instruct::Opcode(Opcode::IterFree(iter_id)) => self.step_iter_free(iter_id),
Instruct::Opcode(Opcode::IterNext(ref iter_args, target)) => {
self.step_iter_next(builder, iter_args, target)
}
Instruct::Opcode(Opcode::Switch(bounded, base, ref targets)) => {
self.step_switch(builder, bounded, base, targets)
}
Instruct::Opcode(Opcode::SSwitch {
ref cases,
ref targets,
_0: _,
}) => self.step_s_switch(builder, cases, targets),
Instruct::Opcode(Opcode::Enter(label) | Opcode::Jmp(label)) => {
// Jmp and JmpNS need to update the next IP.
// TODO: We should probably store the fact that a surprise check
// jump occurred during the Sequence.
let ip = *self.body.label_to_ip.get(&label).unwrap();
self.ip = ip;
return Ok(());
}
Instruct::Opcode(
ref opcode @ Opcode::FCallClsMethod(..)
| ref opcode @ Opcode::FCallClsMethodD(..)
| ref opcode @ Opcode::FCallClsMethodM(..)
| ref opcode @ Opcode::FCallClsMethodS(..)
| ref opcode @ Opcode::FCallClsMethodSD(..)
| ref opcode @ Opcode::FCallCtor(..)
| ref opcode @ Opcode::FCallFunc(..)
| ref opcode @ Opcode::FCallFuncD(..)
| ref opcode @ Opcode::FCallObjMethod(..)
| ref opcode @ Opcode::FCallObjMethodD(..),
) => self.step_fcall_handler(builder, opcode)?,
Instruct::Opcode(ref opcode) => self.step_default_handler(builder, opcode)?,
Instruct::Pseudo(
Pseudo::TryCatchBegin | Pseudo::TryCatchMiddle | Pseudo::TryCatchEnd,
) => {}
Instruct::Pseudo(Pseudo::SrcLoc(_)) => {}
Instruct::Pseudo(Pseudo::Break) => todo!(),
Instruct::Pseudo(Pseudo::Comment(..)) => todo!(),
Instruct::Pseudo(Pseudo::Continue) => todo!(),
Instruct::Pseudo(Pseudo::Label(..)) => {}
Instruct::Pseudo(Pseudo::TypedValue { .. }) => todo!(),
}
debug_assert!(
match instr {
Instruct::Opcode(opcode) => {
let data = crate::body::lookup_data_for_opcode(opcode);
self.ip.is_none() || !data.flags.contains(InstrFlags::TF)
}
Instruct::Pseudo(_) => true,
},
"Instr {:?} is marked as TF but didn't clear 'ip'",
instr
);
self.ip = self.next_ip(self.ip);
Ok(())
}
fn step_member_op(&mut self, builder: &mut InstrSeqBuilder<'arena, 'a, '_>) -> Result<()> {
let mut inputs = Vec::new();
let src_loc = Rc::clone(self.body.ip_to_loc(self.ip));
//-- let mutates_stack_base = self.member_op_mutates_stack_base();
let base_op = self.step_base(builder, &mut inputs)?;
trace!(
" + {ip:4} INSTR: {instr:?}",
ip = self.ip.to_string(),
instr = self.instr()
);
let mut intermediate_ops = Vec::new();
while let Some(iop) = self.step_dim(&mut inputs)? {
intermediate_ops.push(iop);
trace!(
" + {ip:4} INSTR: {instr:?}",
ip = self.ip.to_string(),
instr = self.instr()
);
}
let final_op = self.step_final(&mut inputs)?;
let is_write = final_op.is_write();
if !is_write {
inputs[0] = inputs[0].to_read_only();
}
let pushes_value = final_op.pushes_value();
// TODO: if it's a COW then we probably should have the base replace its
// stack/local value with a new computed value.
let instr = NodeInstr::MemberOp(node::MemberOp {
base_op,
intermediate_ops,
final_op,
});
if pushes_value {
let output = builder.compute_value(&instr, 0, &inputs);
self.stack_push(output);
}
self.seq_push_with_loc(builder, instr, inputs, src_loc);
Ok(())
}
fn next_ip(&self, ip: InstrPtr) -> InstrPtr {
ip.next(self.body.hhbc_body.body_instrs.len())
}
fn step_base(
&mut self,
builder: &mut InstrSeqBuilder<'arena, 'a, '_>,
inputs: &mut Vec<Input<'arena>>,
) -> Result<node::BaseOp> {
let instr = self.instr().unwrap();
let src_loc = Rc::clone(self.body.ip_to_loc(self.ip));
self.ip = self.next_ip(self.ip);
Ok(match *instr {
Instruct::Opcode(Opcode::BaseC(idx, mode)) => {
// Get base from value.
let base = self.stack_get_n(idx as usize)?;
inputs.push(self.reffy(base));
node::BaseOp::Base(mode, ReadonlyOp::Any, src_loc)
}
Instruct::Opcode(Opcode::BaseGC(idx, mode)) => {
// Get base from global name.
let base = self.stack_get_n(idx as usize)?;
inputs.push(self.reffy(base));
node::BaseOp::BaseG(mode, src_loc)
}
Instruct::Opcode(Opcode::BaseL(local, mode, readonly)) => {
// Get base from local.
let base = self.local_get(&local);
inputs.push(self.reffy(base));
node::BaseOp::Base(mode, readonly, src_loc)
}
Instruct::Opcode(Opcode::BaseH) => {
// Get base from $this.
let base = builder.compute_value(&NodeInstr::Opcode(Opcode::This), 0, &[]);
inputs.push(self.reffy(base));
node::BaseOp::BaseH(src_loc)
}
Instruct::Opcode(Opcode::BaseSC(prop, cls, mode, readonly)) => {
// Get base from static property.
let prop = self.stack_get_n(prop as usize)?;
let cls = self.stack_get_n(cls as usize)?;
inputs.push(self.non_cow(prop));
inputs.push(self.non_cow(cls));
node::BaseOp::BaseSC(mode, readonly, src_loc)
}
_ => todo!("Op: {instr:?}"),
})
}
fn step_dim(
&mut self,
inputs: &mut Vec<Input<'arena>>,
) -> Result<Option<node::IntermediateOp<'arena>>> {
// Loop because we may have to skip intermediate SrcLoc.
loop {
let instr = self.instr();
match instr {
Some(Instruct::Pseudo(Pseudo::SrcLoc(..))) => {
self.ip = self.next_ip(self.ip);
}
Some(Instruct::Opcode(Opcode::Dim(mode, key))) => {
let src_loc = Rc::clone(self.body.ip_to_loc(self.ip));
self.ip = self.next_ip(self.ip);
let key = self.push_member_key_inputs(inputs, key)?;
return Ok(Some(node::IntermediateOp {
key,
mode: *mode,
src_loc,
}));
}
_ => return Ok(None),
}
}
}
fn step_final(&mut self, inputs: &mut Vec<Input<'arena>>) -> Result<node::FinalOp<'arena>> {
let instr = self
.instr()
.ok_or_else(|| anyhow!("Early end in MemberOp sequence"))?;
let src_loc = Rc::clone(self.body.ip_to_loc(self.ip));
// purposely don't increment self.ip - it will be incremented by the
// outer 'step' fn.
let final_op = match *instr {
Instruct::Opcode(Opcode::QueryM(n_stack, query_op, ref key)) => {
let key = self.push_member_key_inputs(inputs, key)?;
self.stack_pop_n(n_stack as usize)?;
node::FinalOp::QueryM(key, query_op, src_loc)
}
Instruct::Opcode(Opcode::SetM(n_stack, ref key)) => {
let key = self.push_member_key_inputs(inputs, key)?;
let value = self.stack_pop();
inputs.push(self.reffy(value));
self.stack_pop_n(n_stack as usize)?;
node::FinalOp::SetM(key, src_loc)
}
Instruct::Opcode(Opcode::SetOpM(n_stack, op, ref key)) => {
let key = self.push_member_key_inputs(inputs, key)?;
let value = self.stack_pop();
inputs.push(self.reffy(value));
self.stack_pop_n(n_stack as usize)?;
node::FinalOp::SetOpM(key, op, src_loc)
}
Instruct::Opcode(Opcode::SetRangeM(n_stack, sz, op)) => {
let s1 = self.stack_pop();
inputs.push(self.reffy(s1));
let s2 = self.stack_pop();
inputs.push(self.reffy(s2));
let s3 = self.stack_pop();
inputs.push(self.reffy(s3));
self.stack_pop_n(n_stack as usize)?;
node::FinalOp::SetRangeM(sz, op, src_loc)
}
Instruct::Opcode(Opcode::IncDecM(n_stack, op, ref key)) => {
let key = self.push_member_key_inputs(inputs, key)?;
self.stack_pop_n(n_stack as usize)?;
node::FinalOp::IncDecM(key, op, src_loc)
}
Instruct::Opcode(Opcode::UnsetM(n_stack, ref key)) => {
let key = self.push_member_key_inputs(inputs, key)?;
self.stack_pop_n(n_stack as usize)?;
node::FinalOp::UnsetM(key, src_loc)
}
_ => todo!("Op: {instr:?}"),
};
Ok(final_op)
}
fn step_create_cl(
&mut self,
builder: &mut InstrSeqBuilder<'arena, 'a, '_>,
num_params: NumParams,
classname: &ClassName<'arena>,
) -> Result<()> {
let mut inputs = self
.stack_pop_n(num_params as usize)?
.into_iter()
.map(|v| self.reffy(v))
.collect_vec();
inputs.push(Input::Class(classname.unsafe_into_string()));
let instr = NodeInstr::Opcode(Opcode::CreateCl(num_params, classname.clone()));
let output = builder.compute_value(&instr, 0, &inputs);
self.stack_push(output);
Ok(())
}
fn step_constant(
&mut self,
builder: &mut InstrSeqBuilder<'arena, 'a, '_>,
opcode: &Opcode<'arena>,
) -> Result<()> {
let clean_instr = NodeInstr::Opcode(clean_opcode(opcode));
debug_assert_eq!(opcode.num_inputs(), 0);
debug_assert!(matches!(LocalInfo::for_opcode(opcode), LocalInfo::None));
debug_assert!(opcode.targets().is_empty());
let data = crate::body::lookup_data_for_opcode(opcode);
debug_assert!(match &data.outputs {
Outputs::Fixed(n) => n.len() == 1,
_ => false,
});
debug_assert!(
!is_checkpoint_instr(&clean_instr),
"checkpoint: {clean_instr:?}",
);
debug_assert!(!data.flags.contains(InstrFlags::TF));
// For a constant the outputs are based entirely on the input instr.
let output = match opcode {
Opcode::Dict(id) | Opcode::Keyset(id) | Opcode::Vec(id) => {
// But for an array-based constant we want to use the array data as an input.
let tv = self.adata[id];
builder.compute_value(&clean_instr, 0, &[Input::ConstantArray(tv.clone())])
}
_ => builder.compute_constant(&clean_instr),
};
self.stack_push(output);
Ok(())
}
fn step_default_handler(
&mut self,
builder: &mut InstrSeqBuilder<'arena, 'a, '_>,
opcode: &Opcode<'arena>,
) -> Result<()> {
// Start by computing the inputs for this opcode. For a 'default'
// opcode we can handle stack and locals.
let mut inputs: Vec<Input<'arena>> = self
.stack_pop_n(opcode.num_inputs())?
.into_iter()
.map(|v| self.reffy(v))
.collect_vec();
let local_info = LocalInfo::for_opcode(opcode);
match local_info {
LocalInfo::None | LocalInfo::Write(_) => {}
LocalInfo::Read(ref local) | LocalInfo::Mutate(ref local) => {
inputs.push(self.reffy(self.local_get(local)));
}
LocalInfo::ReadRange(range) => {
for local in range.iter() {
inputs.push(self.reffy(self.local_get(&local)));
}
}
}
// For any targets that the opcode refers to, create a state fork to
// handle that later.
self.fork(builder, opcode.targets());
// Mock up a "clean" version of the Instruct with the Locals and Labels
// removed (set to Local::INVALID and Label::INVALID).
let clean_instr = NodeInstr::Opcode(clean_opcode(opcode));
// Figure out how many stack outputs we'll need. For 'default'
// instructions this should be 0 or 1.
let data = crate::body::lookup_data_for_opcode(opcode);
let n = match &data.outputs {
Outputs::NOV => 0,
Outputs::Fixed(outputs) => outputs.len(),
Outputs::FCall => unreachable!(),
};
// The outputs are based on: (the "cleaned" instr, inputs, the output
// index)
let outputs: Vec<Value> = (0..n)
.map(|i| builder.compute_value(&clean_instr, i, &inputs))
.collect();
self.stack_push_n(&outputs);
// If the instr writes to a local then do that now.
match local_info {
LocalInfo::None | LocalInfo::Read(_) | LocalInfo::ReadRange(_) => {}
LocalInfo::Write(ref local) | LocalInfo::Mutate(ref local) => {
let output = builder.compute_value(&clean_instr, n, &inputs);
self.local_set(local, output);
}
}
// Finally if this is a checkpoint instr (where the two sequences must
// match up) then push it onto the sequence list.
if is_checkpoint_instr(&clean_instr) {
self.seq_push(builder, clean_instr, inputs);
}
if data.flags.contains(InstrFlags::TF) {
// This opcode ends the sequence (like RetC).
self.ip = InstrPtr::None;
}
Ok(())
}
fn push_member_key_inputs(
&mut self,
inputs: &mut Vec<Input<'arena>>,
member_key: &MemberKey<'arena>,
) -> Result<MemberKey<'arena>> {
match *member_key {
MemberKey::EI(..)
| MemberKey::ET(..)
| MemberKey::PT(..)
| MemberKey::QT(..)
| MemberKey::W => {}
MemberKey::EC(idx, _) | MemberKey::PC(idx, _) => {
inputs.push(self.non_cow(self.stack_get_n(idx as usize)?));
}
MemberKey::EL(local, _) | MemberKey::PL(local, _) => {
inputs.push(self.non_cow(self.local_get(&local)));
}
}
Ok(clean_member_key(member_key))
}
fn step_fcall_handler(
&mut self,
builder: &mut InstrSeqBuilder<'arena, 'a, '_>,
opcode: &Opcode<'arena>,
) -> Result<()> {
let data = crate::body::lookup_data_for_opcode(opcode);
fn sanitize_fca<'arena>(
FCallArgs {
flags,
async_eager_target: _,
num_args,
num_rets,
inouts,
readonly,
context,
}: &FCallArgs<'arena>,
) -> FCallArgs<'arena> {
// Turn a non-empty, all-false slice into an empty slice.
let inouts = if !inouts.is_empty() && !inouts.iter().any(|x| *x) {
Slice::from(&[][..])
} else {
*inouts
};
// Turn a non-empty, all-false slice into an empty slice.
let readonly = if !readonly.is_empty() && !readonly.iter().any(|x| *x) {
Slice::from(&[][..])
} else {
*readonly
};
FCallArgs {
flags: *flags,
async_eager_target: Label::INVALID,
num_args: *num_args,
num_rets: *num_rets,
inouts,
readonly,
context: *context,
}
}
let (fca, opcode) = match *opcode {
Opcode::FCallClsMethod(ref fca, hint, log) => {
(fca, Opcode::FCallClsMethod(sanitize_fca(fca), hint, log))
}
Opcode::FCallClsMethodD(ref fca, class, method) => (
fca,
Opcode::FCallClsMethodD(sanitize_fca(fca), class, method),
),
Opcode::FCallClsMethodM(ref fca, hint, log, method) => (
fca,
Opcode::FCallClsMethodM(sanitize_fca(fca), hint, log, method),
),
Opcode::FCallClsMethodS(ref fca, hint, clsref) => (
fca,
Opcode::FCallClsMethodS(sanitize_fca(fca), hint, clsref),
),
Opcode::FCallClsMethodSD(ref fca, hint, clsref, method) => (
fca,
Opcode::FCallClsMethodSD(sanitize_fca(fca), hint, clsref, method),
),
Opcode::FCallCtor(ref fca, hint) => (fca, Opcode::FCallCtor(sanitize_fca(fca), hint)),
Opcode::FCallFunc(ref fca) => (fca, Opcode::FCallFunc(sanitize_fca(fca))),
Opcode::FCallFuncD(ref fca, name) => (fca, Opcode::FCallFuncD(sanitize_fca(fca), name)),
Opcode::FCallObjMethod(ref fca, hint, obj_method_op) => (
fca,
Opcode::FCallObjMethod(sanitize_fca(fca), hint, obj_method_op),
),
Opcode::FCallObjMethodD(ref fca, hint, obj_method_op, method) => (
fca,
Opcode::FCallObjMethodD(sanitize_fca(fca), hint, obj_method_op, method),
),
_ => unreachable!(),
};
let num_inouts = fca.num_inouts();
let num_inputs = opcode.num_inputs();
let inputs = self
.stack_pop_n(num_inputs)?
.into_iter()
.take(num_inputs - num_inouts)
.map(|v| self.reffy(v))
.collect_vec();
let instr = NodeInstr::Opcode(opcode);
if fca.async_eager_target != Label::INVALID {
// We're an async call...
self.fork_and_adjust(
builder,
&[fca.async_eager_target],
|fork, builder, target_idx| {
// Async will push the eager value onto the stack before
// returning.
// (target_idx == 0..num_rets) are the "normal" fcall return.
// (target_idx == num_rets) is the "eager async" fcall return.
let value =
builder.compute_value(&instr, target_idx + fca.num_rets as usize, &inputs);
fork.stack_push(value);
},
);
}
let n = match &data.outputs {
Outputs::NOV => 0,
Outputs::Fixed(outputs) => outputs.len(),
Outputs::FCall => fca.num_rets as usize,
};
let outputs: Vec<Value> = (0..n)
.map(|i| builder.compute_value(&instr, i, &inputs))
.collect();
self.stack_push_n(&outputs);
self.seq_push(builder, instr, inputs);
Ok(())
}
fn step_inc_dec_l(
&mut self,
builder: &mut InstrSeqBuilder<'arena, 'a, '_>,
local: Local,
inc_dec_op: IncDecOp,
) {
let pre_value = self.local_get(&local);
// For comparison we need to strip the local itself out of the opcode.
let instr = NodeInstr::Opcode(Opcode::IncDecL(Local::INVALID, inc_dec_op));
let post_value = builder.compute_value(&instr, 0, &[self.reffy(pre_value)]);
self.local_set(&local, post_value);
let value = apply_inc_dec_op(inc_dec_op, pre_value, post_value);
self.stack_push(value);
let inputs = vec![self.reffy(pre_value)];
self.seq_push(builder, instr, inputs);
}
fn step_iter_free(&mut self, iter_id: IterId) {
// IterFree just clears the iterator state - we don't need the
// two sides to clear the iterator at the same time.
self.iterators.remove(&iter_id);
}
fn step_iter_init(
&mut self,
builder: &mut InstrSeqBuilder<'arena, 'a, '_>,
iter_args: &IterArgs,
target: Label,
) {
// IterArgs { iter_id: IterId, key_id: Local, val_id: Local }
let base = self.stack_pop();
let inputs = vec![self.reffy(base)];
self.fork_and_adjust(builder, &[target], |_, _, _| {
// The fork implicitly does a IterFree - but we haven't yet
// registered our iterator - so we don't have to clear it.
});
let instr = NodeInstr::Opcode(Opcode::IterInit(IterArgs::default(), Label::INVALID));
let key_value = builder.compute_value(&instr, 0, &inputs);
let value_value = builder.compute_value(&instr, 1, &inputs);
self.seq_push(builder, instr, inputs);
self.iterators.insert(
iter_args.iter_id,
IterState {
key: iter_args.key_id,
value: iter_args.val_id,
base,
},
);
if iter_args.key_id != Local::INVALID {
self.local_set(&iter_args.key_id, key_value);
}
self.local_set(&iter_args.val_id, value_value);
}
fn step_iter_next(
&mut self,
builder: &mut InstrSeqBuilder<'arena, 'a, '_>,
iter_args: &IterArgs,
target: Label,
) {
if let Some(iterator) = self.iterators.get(&iter_args.iter_id) {
let inputs = vec![self.reffy(iterator.base)];
let instr = NodeInstr::Opcode(Opcode::IterNext(IterArgs::default(), Label::INVALID));
self.fork_and_adjust(builder, &[target], |fork, builder, _| {
if iter_args.key_id != Local::INVALID {
let key_value = builder.compute_value(&instr, 0, &inputs);
fork.local_set(&iter_args.key_id, key_value);
}
let value_value = builder.compute_value(&instr, 1, &inputs);
fork.local_set(&iter_args.val_id, value_value);
});
self.seq_push(builder, instr, inputs);
// Implicit IterFree...
self.iterators.remove(&iter_args.iter_id);
}
}
fn step_memo_get_eager(
&mut self,
builder: &mut InstrSeqBuilder<'arena, 'a, '_>,
targets: [Label; 2],
range: LocalRange,
) -> Result<()> {
let inputs = range
.iter()
.map(|local| self.reffy(self.local_get(&local)))
.collect_vec();
let clean_instr = NodeInstr::Opcode(Opcode::MemoGetEager(
[Label::INVALID, Label::INVALID],
Dummy::DEFAULT,
LocalRange::EMPTY,
));
self.fork_and_adjust(builder, &targets, |fork, builder, target_idx| {
// target_idx == 0 - no value present
// target_idx == 1 - suspended wait-handle
if target_idx == 1 {
let output = builder.compute_value(&clean_instr, 1 + target_idx, &inputs);
fork.stack_push(output);
}
});
// no fork - eagerly returned value present
let output = builder.compute_value(&clean_instr, 0, &inputs);
self.stack_push(output);
self.seq_push(builder, clean_instr, inputs);
Ok(())
}
fn step_pop_l(&mut self, builder: &mut InstrSeqBuilder<'arena, 'a, '_>, local: Local) {
let value = self.stack_pop();
self.local_set(&local, value);
if self.is_decl_var(&local) {
let inputs = vec![self.reffy(value)];
let instr = NodeInstr::Opcode(Opcode::SetL(Local::INVALID));
self.seq_push(builder, instr, inputs);
}
}
fn step_push_l(&mut self, local: Local) {
let value = self.local_get(&local);
self.stack_push(value);
self.local_set(&local, Value::Undefined);
}
fn step_s_switch(
&mut self,
builder: &mut InstrSeqBuilder<'arena, 'a, '_>,
cases: &Slice<'arena, Str<'arena>>,
targets: &Slice<'arena, Label>,
) {
let value = self.stack_pop();
self.fork(builder, targets.as_ref());
let inputs = vec![self.reffy(value)];
let instr = NodeInstr::Opcode(Opcode::SSwitch {
cases: cases.clone(),
targets: Slice::empty(),
_0: Dummy::DEFAULT,
});
self.seq_push(builder, instr, inputs);
self.ip = InstrPtr::None;
}
fn step_switch(
&mut self,
builder: &mut InstrSeqBuilder<'arena, 'a, '_>,
bounded: SwitchKind,
base: i64,
targets: &Slice<'arena, Label>,
) {
let value = self.stack_pop();
self.fork(builder, targets.as_ref());
let inputs = vec![self.reffy(value)];
let instr = NodeInstr::Opcode(Opcode::Switch(bounded, base, Slice::empty()));
self.seq_push(builder, instr, inputs);
self.ip = InstrPtr::None;
}
fn step_set_l(&mut self, builder: &mut InstrSeqBuilder<'arena, 'a, '_>, local: Local) {
let value = self.stack_top();
self.local_set(&local, value);
if self.is_decl_var(&local) {
let inputs = vec![self.reffy(value)];
let instr = NodeInstr::Opcode(Opcode::SetL(Local::INVALID));
self.seq_push(builder, instr, inputs);
}
}
fn step_set_op_l(
&mut self,
builder: &mut InstrSeqBuilder<'arena, 'a, '_>,
local: Local,
set_op_op: SetOpOp,
) {
let value = self.stack_pop();
let local_value = self.local_get(&local);
let inputs = vec![self.reffy(local_value), self.reffy(value)];
let instr = NodeInstr::Opcode(Opcode::SetOpL(Local::INVALID, set_op_op));
let output = builder.compute_value(&instr, 0, &inputs);
self.seq_push(builder, instr, inputs);
self.local_set(&local, output);
self.stack_push(output);
}
fn seq_push(
&self,
builder: &mut InstrSeqBuilder<'arena, 'a, '_>,
instr: NodeInstr<'arena>,
inputs: impl Into<Box<[Input<'arena>]>>,
) {
let src_loc = Rc::clone(self.body.ip_to_loc(self.ip));
self.seq_push_with_loc(builder, instr, inputs, src_loc);
}
fn seq_push_with_loc(
&self,
builder: &mut InstrSeqBuilder<'arena, 'a, '_>,
instr: NodeInstr<'arena>,
inputs: impl Into<Box<[Input<'arena>]>>,
src_loc: Rc<SrcLoc>,
) {
let inputs = inputs.into();
trace!(
" SEQ w/ INPUTS [{}]",
inputs.iter().map(|inp| inp.to_string()).join(", ")
);
builder.seq.push(Node {
instr,
inputs,
src_loc,
});
}
pub(crate) fn instr(&self) -> Option<&'arena Instruct<'arena>> {
self.instr_at(self.ip)
}
pub(crate) fn instr_at(&self, ip: InstrPtr) -> Option<&'arena Instruct<'arena>> {
ip.into_option().and_then(|ip| {
let idx = ip.as_usize();
let instrs = self.body.hhbc_body.body_instrs.as_arena_ref();
instrs.get(idx)
})
}
pub(crate) fn stack_get_n(&self, n: usize) -> Result<Value> {
let idx = self.stack.len() - 1 - n;
self.stack
.get(idx)
.copied()
.ok_or_else(|| anyhow!("Invalid stack index {idx} (max {})", self.stack.len()))
}
pub(crate) fn stack_push(&mut self, value: Value) {
self.stack.push(value);
}
pub(crate) fn stack_push_n(&mut self, v: &[Value]) {
self.stack.extend(v);
}
pub(crate) fn stack_pop(&mut self) -> Value {
self.stack.pop().unwrap()
}
pub(crate) fn stack_pop_n(&mut self, n: usize) -> Result<Vec<Value>> {
if n > self.stack.len() {
bail!("Invalid stack length {n} (max {})", self.stack.len());
}
Ok(self.stack.split_off(self.stack.len() - n))
}
pub(crate) fn stack_top(&self) -> Value {
self.stack.last().copied().unwrap_or(Value::Undefined)
}
pub(crate) fn local_set(&mut self, local: &Local, value: Value) {
assert!(local != &Local::INVALID);
if value.is_undefined() {
self.locals.remove(local);
} else {
self.locals.insert(*local, value);
}
}
pub(crate) fn local_get(&self, local: &Local) -> Value {
self.locals.get(local).copied().unwrap_or(Value::Undefined)
}
fn is_decl_var(&self, local: &Local) -> bool {
let idx = local.idx as usize;
let params_len = self.body.hhbc_body.params.len();
let decl_vars_len = self.body.hhbc_body.decl_vars.len();
params_len <= idx && idx < params_len + decl_vars_len
}
}
#[derive(Clone)]
pub(crate) struct IterState {
pub(crate) key: Local,
pub(crate) value: Local,
pub(crate) base: Value,
}
type IterIdMap<V> = std::collections::HashMap<IterId, V, BuildIdHasher<u32>>;
struct InstrSeqBuilder<'arena, 'a, 'b> {
seq: Vec<Node<'arena>>,
forks: Vec<State<'arena, 'a>>,
value_builder: &'b mut ValueBuilder<'arena>,
}
impl<'arena, 'a, 'b> InstrSeqBuilder<'arena, 'a, 'b> {
fn compute_value(
&mut self,
instr: &NodeInstr<'arena>,
idx: usize,
inputs: &[Input<'arena>],
) -> Value {
// The Instruct used to compute the value shouldn't have any
// non-comparable bits: Local or Target
for local in LocalInfo::for_node(instr).locals().iter() {
assert!(!local.is_valid());
}
for target in instr.targets() {
assert!(!target.is_valid());
}
self.value_builder
.compute_value(instr, idx, inputs.to_vec().into_boxed_slice())
}
fn compute_constant(&mut self, instr: &NodeInstr<'arena>) -> Value {
// The Instruct used to compute the value shouldn't have any
// non-comparable bits: Local or Target
for local in LocalInfo::for_node(instr).locals().iter() {
assert!(!local.is_valid());
}
for target in instr.targets() {
assert!(!target.is_valid());
}
self.value_builder.compute_constant(instr)
}
}
pub(crate) struct StateCollect<'arena, 'a> {
pub(crate) seq: Sequence<'arena>,
pub(crate) forks: Vec<State<'arena, 'a>>,
pub(crate) catch_state: Option<State<'arena, 'a>>,
}
/// Returns true if the Instruct is one where we should stop and compare state
/// between the two sides. Common examples are places where non-local
/// side-effects happen such as calls.
///
/// Some guiding principals:
/// - Instructs that push constants onto the stack should return false.
/// - Instructs that simply manipulate the stack and/or locals (PopC, SetL)
/// should return false.
/// - By default other Instructs should return true.
fn is_checkpoint_instr(instr: &NodeInstr<'_>) -> bool {
match instr {
// Constants
NodeInstr::Opcode(
Opcode::ClsCnsD(_, _)
| Opcode::CnsE(_)
| Opcode::CreateSpecialImplicitContext
| Opcode::Dict(..)
| Opcode::Dir
| Opcode::Double(..)
| Opcode::False
| Opcode::File
| Opcode::FuncCred
| Opcode::Int(..)
| Opcode::Keyset(..)
| Opcode::LateBoundCls
| Opcode::LazyClass(..)
| Opcode::LazyClassFromClass
| Opcode::Method
| Opcode::NewCol(..)
| Opcode::NewDictArray(_)
| Opcode::Null
| Opcode::NullUninit
| Opcode::ParentCls
| Opcode::SelfCls
| Opcode::String(..)
| Opcode::This
| Opcode::True
| Opcode::Vec(..),
) => false,
// Stack/Local manipulation
NodeInstr::Opcode(
Opcode::CGetL(..)
| Opcode::CGetL2(..)
| Opcode::Dup
| Opcode::Lt
| Opcode::Mod
| Opcode::PopC
| Opcode::PopL(..)
| Opcode::PushL(..)
| Opcode::Same
| Opcode::SetL(..)
| Opcode::UnsetL(..),
) => false,
// Is operations
NodeInstr::Opcode(
Opcode::InstanceOf
| Opcode::InstanceOfD(..)
| Opcode::IsLateBoundCls
| Opcode::IsTypeC(..)
| Opcode::IsTypeL(..)
| Opcode::IsTypeStructC(..)
| Opcode::IsUnsetL(..)
| Opcode::IssetG
| Opcode::IssetL(..)
| Opcode::IssetS,
) => false,
// Simple control flow
NodeInstr::Opcode(Opcode::Enter(_) | Opcode::Jmp(_) | Opcode::Nop) => false,
// Verify Instructions
NodeInstr::Opcode(
Opcode::VerifyImplicitContextState
| Opcode::VerifyOutType(..)
| Opcode::VerifyParamType(..)
| Opcode::VerifyParamTypeTS(..)
| Opcode::VerifyRetNonNullC
| Opcode::VerifyRetTypeC
| Opcode::VerifyRetTypeTS,
) => true,
// Other Opcodes
NodeInstr::Opcode(Opcode::Concat | Opcode::ConcatN(..)) => false,
NodeInstr::Opcode(
Opcode::AKExists
| Opcode::Add
| Opcode::AddElemC
| Opcode::AddNewElemC
| Opcode::ArrayIdx
| Opcode::ArrayMarkLegacy
| Opcode::ArrayUnmarkLegacy
| Opcode::AssertRATL(..)
| Opcode::AssertRATStk(..)
| Opcode::Await
| Opcode::AwaitAll(..)
| 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::CGetQuietL(..)
| Opcode::CGetS(..)
| Opcode::CUGetL(..)
| Opcode::CastBool
| Opcode::CastDict
| Opcode::CastDouble
| Opcode::CastInt
| Opcode::CastKeyset
| Opcode::CastString
| Opcode::CastVec
| Opcode::ChainFaults
| Opcode::CheckProp(..)
| Opcode::CheckClsReifiedGenericMismatch
| Opcode::CheckClsRGSoft
| Opcode::CheckThis
| Opcode::ClassGetC
| Opcode::ClassGetTS
| Opcode::ClassHasReifiedGenerics
| Opcode::ClassName
| Opcode::Clone
| Opcode::ClsCns(..)
| Opcode::ClsCnsL(..)
| Opcode::Cmp
| Opcode::ColFromArray(..)
| Opcode::CombineAndResolveTypeStruct(..)
| Opcode::ContCheck(..)
| Opcode::ContCurrent
| Opcode::ContEnter
| Opcode::ContGetReturn
| Opcode::ContKey
| Opcode::ContRaise
| Opcode::ContValid
| Opcode::CreateCl(..)
| Opcode::CreateCont
| Opcode::DblAsBits
| Opcode::Dim(..)
| Opcode::Div
| Opcode::Eq
| Opcode::Eval
| Opcode::Exit
| Opcode::FCallClsMethod(..)
| Opcode::FCallClsMethodD(..)
| Opcode::FCallClsMethodM(..)
| Opcode::FCallClsMethodS(..)
| Opcode::FCallClsMethodSD(..)
| Opcode::FCallCtor(..)
| Opcode::FCallFunc(..)
| Opcode::FCallFuncD(..)
| Opcode::FCallObjMethod(..)
| Opcode::FCallObjMethodD(..)
| Opcode::Fatal(..)
| Opcode::GetClsRGProp
| Opcode::GetMemoKeyL(..)
| Opcode::Gt
| Opcode::Gte
| Opcode::HasReifiedParent
| Opcode::Idx
| Opcode::IncDecG(..)
| Opcode::IncDecL(..)
| Opcode::IncDecM(..)
| Opcode::IncDecS(..)
| Opcode::Incl
| Opcode::InclOnce
| Opcode::InitProp(..)
| Opcode::IterFree(..)
| Opcode::IterInit(..)
| Opcode::IterNext(..)
| Opcode::JmpNZ(..)
| Opcode::JmpZ(..)
| Opcode::LIterFree(..)
| Opcode::LIterInit(..)
| Opcode::LIterNext(..)
| Opcode::LockObj
| Opcode::Lte
| Opcode::MemoGet(..)
| Opcode::MemoGetEager(..)
| Opcode::MemoSet(..)
| Opcode::MemoSetEager(..)
| Opcode::Mul
| Opcode::NSame
| Opcode::NativeImpl
| Opcode::Neq
| Opcode::NewKeysetArray(..)
| Opcode::NewObj
| Opcode::NewObjD(..)
| Opcode::NewObjS(..)
| Opcode::NewPair
| Opcode::NewStructDict(..)
| Opcode::NewVec(..)
| Opcode::Not
| Opcode::OODeclExists(..)
| Opcode::PopU
| Opcode::PopU2
| Opcode::Pow
| Opcode::Print
| Opcode::QueryM(..)
| Opcode::RaiseClassStringConversionWarning
| Opcode::RecordReifiedGeneric
| Opcode::Req
| Opcode::ReqDoc
| Opcode::ReqOnce
| Opcode::ResolveClass(..)
| Opcode::ResolveClsMethod(..)
| Opcode::ResolveClsMethodD(..)
| Opcode::ResolveClsMethodS(..)
| Opcode::ResolveFunc(..)
| Opcode::ResolveMethCaller(..)
| Opcode::ResolveRClsMethod(..)
| Opcode::ResolveRClsMethodD(..)
| Opcode::ResolveRClsMethodS(..)
| Opcode::ResolveRFunc(..)
| Opcode::RetC
| Opcode::RetCSuspended
| Opcode::RetM(..)
| Opcode::SSwitch { .. }
| Opcode::Select
| Opcode::SetG
| Opcode::SetImplicitContextByValue
| Opcode::SetM(..)
| Opcode::SetOpG(..)
| Opcode::SetOpL(..)
| Opcode::SetOpM(..)
| Opcode::SetOpS(..)
| Opcode::SetRangeM(..)
| Opcode::SetS(..)
| Opcode::Shl
| Opcode::Shr
| Opcode::Silence(..)
| Opcode::Sub
| Opcode::Switch(..)
| Opcode::Throw
| Opcode::ThrowAsTypeStructException
| Opcode::ThrowNonExhaustiveSwitch
| Opcode::UGetCUNop
| Opcode::UnsetG
| Opcode::UnsetM(..)
| Opcode::WHResult
| Opcode::Yield
| Opcode::YieldK,
) => true,
NodeInstr::MemberOp(_) => true,
}
}
fn apply_inc_dec_op(inc_dec_op: IncDecOp, pre_value: Value, post_value: Value) -> Value {
match inc_dec_op {
IncDecOp::PreInc | IncDecOp::PreDec => post_value,
IncDecOp::PostInc | IncDecOp::PostDec => pre_value,
_ => unreachable!(),
}
}
fn clean_member_key<'a>(key: &MemberKey<'a>) -> MemberKey<'a> {
match *key {
MemberKey::EI(..)
| MemberKey::ET(..)
| MemberKey::PT(..)
| MemberKey::QT(..)
| MemberKey::W => *key,
MemberKey::EC(_, op) | MemberKey::EL(_, op) => {
// Clean EL -> EC because once we've scrubbed the input we don't
// care where the value came from.
MemberKey::EC(0, op)
}
MemberKey::PC(_, op) | MemberKey::PL(_, op) => {
// Clean EL -> EC because once we've scrubbed the input we don't
// care where the value came from.
MemberKey::PC(0, op)
}
}
}
fn clean_opcode<'arena>(opcode: &Opcode<'arena>) -> Opcode<'arena> {
match *opcode {
Opcode::ClsCnsL(_) => Opcode::ClsCnsL(Local::INVALID),
Opcode::IsTypeL(_, op) => Opcode::IsTypeL(Local::INVALID, op),
Opcode::JmpZ(_) => Opcode::JmpZ(Label::INVALID),
Opcode::JmpNZ(_) => Opcode::JmpNZ(Label::INVALID),
Opcode::MemoGet(_, _) => Opcode::MemoGet(Label::INVALID, LocalRange::EMPTY),
Opcode::MemoSet(_) => Opcode::MemoSet(LocalRange::EMPTY),
// Opcodes with no immediates are already clean.
Opcode::AKExists
| Opcode::Add
| Opcode::AddElemC
| Opcode::AddNewElemC
| Opcode::ArrayIdx
| Opcode::ArrayMarkLegacy
| Opcode::ArrayUnmarkLegacy
| Opcode::Await
| Opcode::BaseH
| Opcode::BitAnd
| Opcode::BitNot
| Opcode::BitOr
| Opcode::BitXor
| Opcode::BreakTraceHint
| Opcode::CGetCUNop
| Opcode::CGetG
| Opcode::CastBool
| Opcode::CastDict
| Opcode::CastDouble
| Opcode::CastInt
| Opcode::CastKeyset
| Opcode::CastString
| Opcode::CastVec
| Opcode::ChainFaults
| Opcode::CheckClsReifiedGenericMismatch
| Opcode::CheckClsRGSoft
| Opcode::CheckThis
| Opcode::ClassGetC
| Opcode::ClassGetTS
| Opcode::ClassHasReifiedGenerics
| Opcode::ClassName
| Opcode::Clone
| Opcode::Cmp
| Opcode::Concat
| Opcode::ContCurrent
| Opcode::ContEnter
| Opcode::ContGetReturn
| Opcode::ContKey
| Opcode::ContRaise
| Opcode::ContValid
| Opcode::CreateCont
| Opcode::CreateSpecialImplicitContext
| Opcode::DblAsBits
| Opcode::Dir
| Opcode::Div
| Opcode::Dup
| Opcode::Eq
| Opcode::Eval
| Opcode::Exit
| Opcode::False
| Opcode::File
| Opcode::FuncCred
| Opcode::GetClsRGProp
| Opcode::Gt
| Opcode::Gte
| Opcode::HasReifiedParent
| Opcode::Idx
| Opcode::Incl
| Opcode::InclOnce
| Opcode::InstanceOf
| Opcode::IsLateBoundCls
| Opcode::IssetG
| Opcode::IssetS
| Opcode::LateBoundCls
| Opcode::LazyClassFromClass
| Opcode::LockObj
| Opcode::Lt
| Opcode::Lte
| Opcode::Method
| Opcode::Mod
| Opcode::Mul
| Opcode::NSame
| Opcode::NativeImpl
| Opcode::Neq
| Opcode::NewObj
| Opcode::NewPair
| Opcode::Nop
| Opcode::Not
| Opcode::Null
| Opcode::NullUninit
| Opcode::ParentCls
| Opcode::PopC
| Opcode::PopU
| Opcode::PopU2
| Opcode::Pow
| Opcode::Print
| Opcode::RaiseClassStringConversionWarning
| Opcode::RecordReifiedGeneric
| Opcode::Req
| Opcode::ReqDoc
| Opcode::ReqOnce
| Opcode::RetC
| Opcode::RetCSuspended
| Opcode::Same
| Opcode::Select
| Opcode::SelfCls
| Opcode::SetG
| Opcode::SetImplicitContextByValue
| Opcode::Shl
| Opcode::Shr
| Opcode::Sub
| Opcode::This
| Opcode::Throw
| Opcode::ThrowAsTypeStructException
| Opcode::ThrowNonExhaustiveSwitch
| Opcode::True
| Opcode::UGetCUNop
| Opcode::UnsetG
| Opcode::VerifyImplicitContextState
| Opcode::VerifyRetNonNullC
| Opcode::VerifyRetTypeC
| Opcode::VerifyRetTypeTS
| Opcode::WHResult
| Opcode::Yield
| Opcode::YieldK => opcode.clone(),
Opcode::CGetL(_) => Opcode::CGetL(Local::INVALID),
Opcode::CGetL2(_) => Opcode::CGetL2(Local::INVALID),
Opcode::CGetQuietL(_) => Opcode::CGetQuietL(Local::INVALID),
Opcode::CUGetL(_) => Opcode::CUGetL(Local::INVALID),
Opcode::GetMemoKeyL(_) => Opcode::GetMemoKeyL(Local::INVALID),
Opcode::IsUnsetL(_) => Opcode::IsUnsetL(Local::INVALID),
Opcode::IssetL(_) => Opcode::IssetL(Local::INVALID),
Opcode::PopL(_) => Opcode::PopL(Local::INVALID),
Opcode::PushL(_) => Opcode::PushL(Local::INVALID),
Opcode::SetL(_) => Opcode::SetL(Local::INVALID),
Opcode::UnsetL(_) => Opcode::UnsetL(Local::INVALID),
Opcode::AwaitAll(_) => Opcode::AwaitAll(LocalRange::EMPTY),
Opcode::Enter(_) => Opcode::Enter(Label::INVALID),
Opcode::Jmp(_) => Opcode::Jmp(Label::INVALID),
Opcode::MemoSetEager(_) => Opcode::MemoSetEager(LocalRange::EMPTY),
Opcode::BareThis(_)
| Opcode::CGetS(_)
| Opcode::CheckProp(_)
| Opcode::ClsCns(_)
| Opcode::CnsE(_)
| Opcode::ColFromArray(_)
| Opcode::CombineAndResolveTypeStruct(_)
| Opcode::ConcatN(_)
| Opcode::ContCheck(_)
| Opcode::Double(_)
| Opcode::FCallFunc(_)
| Opcode::Fatal(_)
| Opcode::IncDecG(_)
| Opcode::IncDecS(_)
| Opcode::InstanceOfD(_)
| Opcode::Int(_)
| Opcode::IsTypeC(_)
| Opcode::IsTypeStructC(_)
| Opcode::IterFree(_)
| Opcode::LazyClass(_)
| Opcode::NewCol(_)
| Opcode::NewDictArray(_)
| Opcode::NewKeysetArray(_)
| Opcode::NewObjD(_)
| Opcode::NewObjS(_)
| Opcode::NewStructDict(_)
| Opcode::NewVec(_)
| Opcode::OODeclExists(_)
| Opcode::ResolveClass(_)
| Opcode::ResolveClsMethod(_)
| Opcode::ResolveFunc(_)
| Opcode::ResolveMethCaller(_)
| Opcode::ResolveRClsMethod(_)
| Opcode::ResolveRFunc(_)
| Opcode::RetM(_)
| Opcode::SetOpG(_)
| Opcode::SetOpS(_)
| Opcode::SetS(_)
| Opcode::String(_)
| Opcode::VerifyOutType(_)
| Opcode::VerifyParamType(_)
| Opcode::VerifyParamTypeTS(_) => opcode.clone(),
Opcode::Dict(_) => Opcode::Dict(AdataId::empty()),
Opcode::Keyset(_) => Opcode::Keyset(AdataId::empty()),
Opcode::Vec(_) => Opcode::Vec(AdataId::empty()),
Opcode::MemoGetEager(_, dummy, _) => {
Opcode::MemoGetEager([Label::INVALID, Label::INVALID], dummy, LocalRange::EMPTY)
}
Opcode::Silence(_, op) => Opcode::Silence(Local::INVALID, op),
Opcode::BaseC(_, m_op_mode) => Opcode::BaseC(0, m_op_mode),
Opcode::BaseGC(_, m_op_mode) | Opcode::BaseGL(_, m_op_mode) => {
// BaseGC and BaseGL are equal if the base ends up with the same
// value.
Opcode::BaseGL(Local::INVALID, m_op_mode)
}
Opcode::BaseL(_, m_op_mode, ro_op) => Opcode::BaseL(Local::INVALID, m_op_mode, ro_op),
Opcode::BaseSC(_, _, m_op_mode, ro_op) => Opcode::BaseSC(0, 0, m_op_mode, ro_op),
Opcode::Dim(m_op_mode, ref key) => Opcode::Dim(m_op_mode, clean_member_key(key)),
Opcode::IncDecM(_, inc_dec_op, ref key) => {
Opcode::IncDecM(0, inc_dec_op, clean_member_key(key))
}
Opcode::QueryM(_, query_m_op, ref key) => {
Opcode::QueryM(0, query_m_op, clean_member_key(key))
}
Opcode::SetM(_, ref key) => Opcode::SetM(0, clean_member_key(key)),
Opcode::SetOpM(_, set_op_op, ref key) => {
Opcode::SetOpM(0, set_op_op, clean_member_key(key))
}
Opcode::UnsetM(_, ref key) => Opcode::UnsetM(0, clean_member_key(key)),
Opcode::AssertRATL(_, _)
| Opcode::AssertRATStk(_, _)
| Opcode::ClsCnsD(_, _)
| Opcode::CreateCl(_, _)
| Opcode::FCallClsMethod(_, _, _)
| Opcode::FCallClsMethodD(_, _, _)
| Opcode::FCallClsMethodM(_, _, _, _)
| Opcode::FCallClsMethodS(_, _, _)
| Opcode::FCallClsMethodSD(_, _, _, _)
| Opcode::FCallCtor(_, _)
| Opcode::FCallFuncD(_, _)
| Opcode::FCallObjMethod(_, _, _)
| Opcode::FCallObjMethodD(_, _, _, _)
| Opcode::IncDecL(_, _)
| Opcode::InitProp(_, _)
| Opcode::IterInit(_, _)
| Opcode::IterNext(_, _)
| Opcode::LIterFree(_, _)
| Opcode::LIterInit(_, _, _)
| Opcode::LIterNext(_, _, _)
| Opcode::ResolveClsMethodD(_, _)
| Opcode::ResolveClsMethodS(_, _)
| Opcode::ResolveRClsMethodD(_, _)
| Opcode::ResolveRClsMethodS(_, _)
| Opcode::SetOpL(_, _)
| Opcode::SetRangeM(_, _, _)
| Opcode::Switch(_, _, _)
| Opcode::SSwitch { .. } => {
debug_assert!(
LocalInfo::for_opcode(opcode).is_none(),
"opcode: {:?}",
opcode
);
debug_assert!(opcode.targets().is_empty(), "opcode: {:?}", opcode);
opcode.clone()
}
}
} |
Rust | hhvm/hphp/hack/src/hackc/sem_diff/value.rs | use std::fmt;
use hash::HashMap;
use crate::node::Input;
use crate::node::NodeInstr;
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub(crate) enum Value {
Constant(u32),
Defined(u32),
Undefined,
}
impl Value {
pub(crate) fn is_undefined(&self) -> bool {
matches!(self, Value::Undefined)
}
#[allow(dead_code)]
pub(crate) fn is_constant(&self) -> bool {
matches!(self, Value::Constant(_))
}
}
impl fmt::Display for Value {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Value::Constant(n) => write!(f, "#{}", n),
Value::Defined(n) => write!(f, "@{}", n),
Value::Undefined => write!(f, "@undefined"),
}
}
}
#[derive(Clone)]
pub(crate) struct ValueBuilder<'arena> {
next_value_idx: u32,
// Store a hash to the Instruct instead of ref so that we don't run into
// lifetime annoyances.
values: HashMap<(u64, usize, Box<[Input<'arena>]>), Value>,
}
impl<'arena> ValueBuilder<'arena> {
pub(crate) fn new() -> Self {
Self {
next_value_idx: 0,
values: Default::default(),
}
}
pub(crate) fn alloc(&mut self) -> Value {
Self::alloc_internal(&mut self.next_value_idx, false)
}
pub(crate) fn compute_constant(&mut self, instr: &NodeInstr<'arena>) -> Value {
// Instruct doesn't support `==`. :(
let hash = compute_hash(instr);
*self
.values
.entry((hash, 0, [].into()))
.or_insert_with(|| Self::alloc_internal(&mut self.next_value_idx, true))
}
pub(crate) fn compute_value(
&mut self,
instr: &NodeInstr<'arena>,
output_idx: usize,
mut inputs: Box<[Input<'arena>]>,
) -> Value {
// Instruct doesn't support `==`. :(
let hash = compute_hash(instr);
// Strip reffyness out of the inputs.
inputs.iter_mut().for_each(|i| match *i {
Input::Shared(n) | Input::Owned(n) => *i = Input::Unowned(n),
_ => {}
});
*self
.values
.entry((hash, output_idx, inputs))
.or_insert_with(|| Self::alloc_internal(&mut self.next_value_idx, false))
}
fn alloc_internal(next_value_idx: &mut u32, constant: bool) -> Value {
let idx = *next_value_idx;
*next_value_idx += 1;
if constant {
Value::Constant(idx)
} else {
Value::Defined(idx)
}
}
}
fn compute_hash<T: std::hash::Hash>(value: T) -> u64 {
use std::hash::Hasher;
let mut hasher = std::collections::hash_map::DefaultHasher::new();
value.hash(&mut hasher);
hasher.finish()
} |
Rust | hhvm/hphp/hack/src/hackc/sem_diff/work_queue.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 hash::HashMap;
use hash::HashSet;
use hhbc::AdataId;
use hhbc::Local;
use hhbc::TypedValue;
use log::trace;
use crate::body::Body;
use crate::instr_ptr::InstrPtr;
use crate::state::State;
use crate::value::ValueBuilder;
#[derive(Default)]
pub(crate) struct WorkQueue<'arena, 'a> {
queue: Vec<(State<'arena, 'a>, State<'arena, 'a>)>,
processed: HashSet<(InstrPtr, InstrPtr)>,
}
impl<'arena, 'a> WorkQueue<'arena, 'a> {
pub(crate) fn init_from_bodies(
&mut self,
value_builder: &mut ValueBuilder<'arena>,
a: &'a Body<'arena>,
a_adata: &'a HashMap<AdataId<'arena>, &'a TypedValue<'arena>>,
b: &'a Body<'arena>,
b_adata: &'a HashMap<AdataId<'arena>, &'a TypedValue<'arena>>,
) {
let mut a_state = State::new(a, "A", a_adata);
let mut b_state = State::new(b, "B", b_adata);
// Also need to handle entrypoints for defaults!
for (idx, (param_a, param_b)) in a
.hhbc_body
.params
.iter()
.zip(b.hhbc_body.params.iter())
.enumerate()
{
// Initialize parameter values
let value = value_builder.alloc();
let local = Local::from_usize(idx);
a_state.local_set(&local, value);
b_state.local_set(&local, value);
match (¶m_a.default_value, ¶m_b.default_value) {
(Maybe::Just(a), Maybe::Just(b)) => {
// The text should have already been compared.
let a_state = a_state.clone_with_jmp(&a.label);
let b_state = b_state.clone_with_jmp(&b.label);
self.add(a_state, b_state);
}
(Maybe::Nothing, Maybe::Nothing) => {}
_ => {
// We should have already checked that the params at least
// both have a default or not.
unreachable!()
}
}
}
self.add(a_state, b_state);
}
pub(crate) fn add(&mut self, a: State<'arena, 'a>, b: State<'arena, 'a>) {
if self.processed.insert((a.ip, b.ip)) {
trace!("Added");
self.queue.push((a, b));
} else {
trace!("Skipped");
}
}
pub(crate) fn pop(&mut self) -> Option<(State<'arena, 'a>, State<'arena, 'a>)> {
self.queue.pop()
}
} |
Hack | hhvm/hphp/hack/src/hackc/test/infer/async.hack | // RUN: %hackc compile-infer %s | FileCheck %s
// TEST-CHECK-BAL: define .async $root.test_async
// CHECK: define .async $root.test_async($this: *void) : *HackInt {
// CHECK: local $a: *void, $a2: *void, $b: *void
// CHECK: #b0:
// CHECK: n0 = $root.bar(null)
// CHECK: n1 = $builtins.hhbc_await(n0)
// CHECK: store &$a <- n1: *HackMixed
// CHECK: n2 = $root.baz(null, n1)
// CHECK: n3 = $builtins.hhbc_await(n2)
// CHECK: store &$b <- n3: *HackMixed
// CHECK: n4 = $root.bar(null)
// CHECK: store &$a2 <- n4: *HackMixed
// CHECK: n5 = $builtins.hhbc_is_type_null(n4)
// CHECK: jmp b1, b2
// CHECK: #b1:
// CHECK: prune $builtins.hack_is_true(n5)
// CHECK: jmp b3(n4)
// CHECK: #b2:
// CHECK: prune ! $builtins.hack_is_true(n5)
// CHECK: n6 = $builtins.hhbc_await(n4)
// CHECK: jmp b3(n6)
// CHECK: #b3(n7: *HackMixed):
// CHECK: n8: *HackMixed = load &$b
// CHECK: n9 = $builtins.hhbc_is_type_int(n8)
// CHECK: n10 = $builtins.hhbc_verify_type_pred(n8, n9)
// CHECK: ret n8
// CHECK: }
async function test_async(): Awaitable<int> {
$a = await bar();
$b = await baz($a);
$a2 = bar();
await $a2;
return $b;
}
async function bar(): Awaitable<int> { return 5; }
async function baz(int $a): Awaitable<int> { return 6; } |
Hack | hhvm/hphp/hack/src/hackc/test/infer/basic.hack | // RUN: %hackc compile-infer %s | FileCheck %s
// TEST-CHECK-IGN:
// CHECK: .source_language = "hack"
// TEST-CHECK-BAL: define $root.main
// CHECK: define $root.main($this: *void) : *void {
// CHECK: #b0:
// CHECK: n0 = $builtins.hhbc_print($builtins.hack_string("Hello, World!\n"))
// CHECK: ret null
// CHECK: }
function main(): void {
echo "Hello, World!\n";
}
// TEST-CHECK-BAL: define $root.escaped_string
// CHECK: define $root.escaped_string($this: *void) : *void {
// CHECK: #b0:
// CHECK: n0 = $builtins.hhbc_print($builtins.hack_string("This string has \042 a quote"))
// CHECK: ret null
// CHECK: }
function escaped_string(): void {
echo 'This string has " a quote';
}
// TEST-CHECK-BAL: define $root.cmp
// CHECK: define $root.cmp($this: *void, $a: *HackMixed, $b: *HackMixed) : *void {
// CHECK: #b0:
// CHECK: n0: *HackMixed = load &$b
// CHECK: n1: *HackMixed = load &$a
// CHECK: n2 = $builtins.hhbc_cmp_eq(n1, n0)
// CHECK: jmp b1, b2
// CHECK: #b1:
// CHECK: prune ! $builtins.hack_is_true(n2)
// CHECK: n3 = $builtins.hhbc_print($builtins.hack_string("unequal"))
// CHECK: jmp b3
// CHECK: #b2:
// CHECK: prune $builtins.hack_is_true(n2)
// CHECK: n4 = $builtins.hhbc_print($builtins.hack_string("equal"))
// CHECK: jmp b3
// CHECK: #b3:
// CHECK: ret null
// CHECK: }
function cmp(mixed $a, mixed $b): void {
if ($a == $b) {
echo "equal";
} else {
echo "unequal";
}
}
// TEST-CHECK-BAL: define $root.cmp2
// CHECK: define $root.cmp2($this: *void, $a: *HackInt, $b: *HackInt) : *void {
// CHECK: #b0:
// CHECK: n0: *HackMixed = load &$b
// CHECK: n1: *HackMixed = load &$a
// CHECK: n2 = $builtins.hhbc_cmp_eq(n1, n0)
// CHECK: jmp b1, b2
// CHECK: #b1:
// CHECK: prune ! $builtins.hack_is_true(n2)
// CHECK: n3 = $builtins.hhbc_print($builtins.hack_string("unequal"))
// CHECK: jmp b3
// CHECK: #b2:
// CHECK: prune $builtins.hack_is_true(n2)
// CHECK: n4 = $builtins.hhbc_print($builtins.hack_string("equal"))
// CHECK: jmp b3
// CHECK: #b3:
// CHECK: ret null
// CHECK: }
function cmp2(int $a, int $b): void {
if ($a == $b) {
echo "equal";
} else {
echo "unequal";
}
}
// TEST-CHECK-BAL: define $root.ret_str
// CHECK: define $root.ret_str($this: *void) : *HackString {
// CHECK: #b0:
// CHECK: n0 = $builtins.hhbc_is_type_str($builtins.hack_string("hello, world\n"))
// CHECK: n1 = $builtins.hhbc_verify_type_pred($builtins.hack_string("hello, world\n"), n0)
// CHECK: ret $builtins.hack_string("hello, world\n")
// CHECK: }
function ret_str(): string {
return "hello, world\n";
}
// TEST-CHECK-BAL: define $root.bool_call
// CHECK: define $root.bool_call($this: *void) : *void {
// CHECK: #b0:
// CHECK: n0 = $root.f_bool(null, $builtins.hack_bool(false))
// CHECK: n1 = $root.f_bool(null, $builtins.hack_bool(true))
// CHECK: ret null
// CHECK: }
function bool_call(): void {
f_bool(false);
f_bool(true);
}
// TEST-CHECK-BAL: define $root.test_const
// CHECK: define $root.test_const($this: *void) : *void {
// CHECK: local $a: *void, $b: *void, $c: *void
// CHECK: #b0:
// CHECK: n0 = $builtins.hhbc_new_vec($builtins.hack_string("x"), $builtins.hack_float(2.0), $builtins.hack_int(3), $builtins.hack_bool(true))
// CHECK: n1 = $builtins.hhbc_new_keyset_array($builtins.hack_string("xyzzy"), $builtins.hack_int(2))
// CHECK: n2 = $builtins.hack_new_dict($builtins.hack_string("a"), $builtins.hack_string("b"), $builtins.hack_int(5), $builtins.hack_float(2.0))
// CHECK: store &$a <- n0: *HackMixed
// CHECK: store &$b <- n2: *HackMixed
// CHECK: store &$c <- n1: *HackMixed
// CHECK: ret null
// CHECK: }
function test_const(): void {
$a = vec["x", 2.0, 3, true];
$b = dict["a" => "b", 5 => 2.0];
$c = keyset["xyzzy", 2];
}
// TEST-CHECK-BAL: define $root.float_arg
// CHECK: define $root.float_arg($this: *void) : *void {
// CHECK: #b0:
// CHECK: n0 = $root.f_float(null, $builtins.hack_float(3.14))
// CHECK: n1 = $root.f_float(null, $builtins.hack_float(3.0))
// CHECK: ret null
// CHECK: }
function float_arg(): void {
f_float(3.14);
f_float(3.0);
}
// TEST-CHECK-BAL: define $root.check_param_types
// CHECK: define $root.check_param_types($this: *void, $a: *HackInt, $b: *HackFloat, $c: *HackString) : *void {
// CHECK: #b0:
// CHECK: ret null
// CHECK: }
function check_param_types(int $a, float $b, string $c): void {
}
// TEST-CHECK-BAL: define $root.check_is_class
// CHECK: define $root.check_is_class($this: *void, $a: *HackMixed) : *HackBool {
// CHECK: #b0:
// CHECK: n0: *HackMixed = load &$a
// CHECK: n1 = $builtins.hack_bool(__sil_instanceof(n0, <C>))
// CHECK: n2 = $builtins.hhbc_is_type_bool(n1)
// CHECK: n3 = $builtins.hhbc_verify_type_pred(n1, n2)
// CHECK: ret n1
// CHECK: }
function check_is_class(mixed $a): bool {
return $a is C;
}
// TEST-CHECK-BAL: define $root.check_global
// CHECK: define $root.check_global($this: *void) : *void {
// CHECK: local $global_server: *void
// CHECK: #b0:
// CHECK: n0: *HackMixed = load &global::_SERVER
// CHECK: store &$global_server <- n0: *HackMixed
// CHECK: n1 = $root.sink(null, n0)
// CHECK: ret null
// CHECK: }
function check_global(): void {
$global_server = HH\global_get('_SERVER');
sink($global_server);
}
// TEST-CHECK-BAL: define $root.check_constant
// CHECK: define $root.check_constant($this: *void) : *void {
// CHECK: #b0:
// CHECK: n0: *HackMixed = load &gconst::GLOBAL_CONSTANT
// CHECK: n1 = $builtins.hhbc_print(n0)
// CHECK: ret null
// CHECK: }
function check_constant(): void {
echo GLOBAL_CONSTANT;
}
// TEST-CHECK-BAL: define $root.check_file
// CHECK: define $root.check_file($this: *void) : *void {
// CHECK: #b0:
// CHECK: n0 = $root.printf(null, $builtins.hack_string("FILE: %s\n"), $builtins.hack_string("__FILE__"))
// CHECK: ret null
// CHECK: }
function check_file(): void {
printf("FILE: %s\n", __FILE__);
}
// TEST-CHECK-1: global global::_SERVER
// CHECK: global global::_SERVER : *HackMixed
// TEST-CHECK-1: global gconst::GLOBAL_CONSTANT
// CHECK: global gconst::GLOBAL_CONSTANT : *HackMixed |
Hack | hhvm/hphp/hack/src/hackc/test/infer/basic_tc.hack | // Typecheck Helpers
function f_bool(bool $_): void { }
function f_float(float $_): void { }
function sink(mixed $a): void { }
class C { }
const int GLOBAL_CONSTANT = 42; |
Hack | hhvm/hphp/hack/src/hackc/test/infer/class.hack | // RUN: %hackc compile-infer %s | FileCheck %s
// TEST-CHECK-BAL: type C$static
// CHECK: type C$static = .kind="class" .static {
// CHECK: prop3: .public *HackFloat;
// CHECK: prop4: .public .SomeAttribute *HackMixed;
// CHECK: MY_CONSTANT: .public .__Infer_Constant__ *HackInt
// CHECK: }
// TEST-CHECK-BAL: "type C "
// CHECK: type C = .kind="class" {
// CHECK: prop1: .public *HackInt;
// CHECK: prop2: .public *HackString;
// CHECK: prop5: .public *HackInt;
// CHECK: type_: .public *HackInt
// CHECK: }
<<__ConsistentConstruct>>
class C {
public int $prop1 = 42;
public string $prop2 = "hello";
public static float $prop3 = 3.14;
<<SomeAttribute>>
public static mixed $prop4 = null;
public int $prop5 = D::C;
const int MY_CONSTANT = 7;
// Test reserved token.
public int $type = 2;
// TEST-CHECK-BAL: define C$static.__factory
// CHECK: define C$static.__factory($this: *C$static) : *C {
// CHECK: #b0:
// CHECK: n0 = __sil_allocate(<C>)
// CHECK: ret n0
// CHECK: }
// TEST-CHECK-BAL: define C.__construct
// CHECK: define C.__construct($this: *C, $a: *HackInt, $b: *HackString, $c: *HackInt) : *HackMixed {
// CHECK: #b0:
// CHECK: ret null
// CHECK: }
public function __construct(int $a, string $b, int $c) {
}
// TEST-CHECK-BAL: define C.cons_static
// CHECK: define C.cons_static($this: *C) : *void {
// CHECK: local $a: *void, $0: *void, $1: *void, $2: *void
// CHECK: #b0:
// CHECK: jmp b1
// CHECK: #b1:
// CHECK: n0: *C = load &$this
// CHECK: n1 = $builtins.hack_get_static_class(n0)
// CHECK: store &$0 <- n1: *HackMixed
// CHECK: n2 = $builtins.hack_get_static_class(n0)
// CHECK: n3 = n2.?.__factory()
// CHECK: store &$2 <- n3: *HackMixed
// CHECK: jmp b2
// CHECK: .handlers b8
// CHECK: #b2:
// CHECK: jmp b3
// CHECK: #b3:
// CHECK: n4: *HackMixed = load &$0
// CHECK: jmp b4
// CHECK: .handlers b8
// CHECK: #b4:
// CHECK: jmp b5
// CHECK: #b5:
// CHECK: n5: *HackMixed = load &$0
// CHECK: jmp b6
// CHECK: .handlers b8
// CHECK: #b6:
// CHECK: jmp b7
// CHECK: #b7:
// CHECK: n6: *HackMixed = load &$2
// CHECK: jmp b9
// CHECK: .handlers b8
// CHECK: #b8(n7: *HackMixed):
// CHECK: store &$0 <- null: *HackMixed
// CHECK: store &$1 <- null: *HackMixed
// CHECK: store &$2 <- null: *HackMixed
// CHECK: n8 = $builtins.hhbc_throw(n7)
// CHECK: unreachable
// CHECK: #b9:
// CHECK: store &$0 <- null: *HackMixed
// CHECK: store &$1 <- null: *HackMixed
// CHECK: store &$2 <- null: *HackMixed
// CHECK: n9 = n6.?.__construct($builtins.hack_int(1), $builtins.hack_string("x"), $builtins.hack_int(3))
// CHECK: n10 = $builtins.hhbc_lock_obj(n6)
// CHECK: store &$a <- n6: *HackMixed
// CHECK: ret null
// CHECK: }
public function cons_static(): void {
$a = new static(1, "x", 3);
}
// TEST-CHECK-BAL: define C.cons_self
// CHECK: define C.cons_self($this: *C) : *void {
// CHECK: local $a: *void, $0: *void, $1: *void, $2: *void
// CHECK: #b0:
// CHECK: jmp b1
// CHECK: #b1:
// CHECK: n0: *C = load &$this
// CHECK: n1 = $builtins.hack_get_static_class(n0)
// CHECK: store &$0 <- n1: *HackMixed
// CHECK: n2 = __sil_allocate(<C>)
// CHECK: n3 = C._86pinit(n2)
// CHECK: store &$2 <- n2: *HackMixed
// CHECK: jmp b2
// CHECK: .handlers b4
// CHECK: #b2:
// CHECK: jmp b3
// CHECK: #b3:
// CHECK: n4: *HackMixed = load &$2
// CHECK: jmp b5
// CHECK: .handlers b4
// CHECK: #b4(n5: *HackMixed):
// CHECK: store &$0 <- null: *HackMixed
// CHECK: store &$1 <- null: *HackMixed
// CHECK: store &$2 <- null: *HackMixed
// CHECK: n6 = $builtins.hhbc_throw(n5)
// CHECK: unreachable
// CHECK: #b5:
// CHECK: store &$0 <- null: *HackMixed
// CHECK: store &$1 <- null: *HackMixed
// CHECK: store &$2 <- null: *HackMixed
// CHECK: n7 = n4.?.__construct($builtins.hack_int(1), $builtins.hack_string("x"), $builtins.hack_int(3))
// CHECK: n8 = $builtins.hhbc_lock_obj(n4)
// CHECK: store &$a <- n4: *HackMixed
// CHECK: ret null
// CHECK: }
public function cons_self(): void {
$a = new self(1, "x", 3);
}
// TEST-CHECK-BAL: define C.cons_inst
// CHECK: define C.cons_inst($this: *C) : *void {
// CHECK: local $a: *void, $0: *void, $1: *void, $2: *void
// CHECK: #b0:
// CHECK: jmp b1
// CHECK: #b1:
// CHECK: n0: *C = load &$this
// CHECK: n1 = $builtins.hack_get_static_class(n0)
// CHECK: store &$0 <- n1: *HackMixed
// CHECK: n2 = __sil_allocate(<C>)
// CHECK: n3 = C._86pinit(n2)
// CHECK: store &$2 <- n2: *HackMixed
// CHECK: jmp b2
// CHECK: .handlers b4
// CHECK: #b2:
// CHECK: jmp b3
// CHECK: #b3:
// CHECK: n4: *HackMixed = load &$2
// CHECK: jmp b5
// CHECK: .handlers b4
// CHECK: #b4(n5: *HackMixed):
// CHECK: store &$0 <- null: *HackMixed
// CHECK: store &$1 <- null: *HackMixed
// CHECK: store &$2 <- null: *HackMixed
// CHECK: n6 = $builtins.hhbc_throw(n5)
// CHECK: unreachable
// CHECK: #b5:
// CHECK: store &$0 <- null: *HackMixed
// CHECK: store &$1 <- null: *HackMixed
// CHECK: store &$2 <- null: *HackMixed
// CHECK: n7 = n4.?.__construct($builtins.hack_int(1), $builtins.hack_string("x"), $builtins.hack_int(3))
// CHECK: n8 = $builtins.hhbc_lock_obj(n4)
// CHECK: store &$a <- n4: *HackMixed
// CHECK: ret null
// CHECK: }
public function cons_inst(): void {
$a = new C(1, "x", 3);
}
// TEST-CHECK-BAL: define C$static.static_signature
// CHECK: define C$static.static_signature($this: *C$static, $a: *HackMixed, $b: *HackMixed) : *void {
// CHECK: #b0:
// CHECK: n0: *HackMixed = load &$b
// CHECK: n1: *HackMixed = load &$a
// CHECK: n2 = $builtins.hhbc_cmp_eq(n1, n0)
// CHECK: jmp b1, b2
// CHECK: #b1:
// CHECK: prune ! $builtins.hack_is_true(n2)
// CHECK: n3 = $builtins.hhbc_print($builtins.hack_string("unequal"))
// CHECK: jmp b3
// CHECK: #b2:
// CHECK: prune $builtins.hack_is_true(n2)
// CHECK: n4 = $builtins.hhbc_print($builtins.hack_string("equal"))
// CHECK: jmp b3
// CHECK: #b3:
// CHECK: ret null
// CHECK: }
// TEST-CHECK-BAL: define C.static_signature
// CHECK: define C.static_signature($this: *C, $a: *HackMixed, $b: *HackMixed) : *void {
// CHECK: #b0:
// CHECK: // forward to the static method
// CHECK: n0: *C = load &$this
// CHECK: n1 = $builtins.hack_get_static_class(n0)
// CHECK: n2: *HackMixed = load &$a
// CHECK: n3: *HackMixed = load &$b
// CHECK: n4 = C$static.static_signature(n1, n2, n3)
// CHECK: ret n4
// CHECK: }
public static function static_signature(mixed $a, mixed $b): void {
if ($a == $b) {
echo "equal";
} else {
echo "unequal";
}
}
// TEST-CHECK-BAL: define .final C.test_const
// CHECK: define .final C.test_const($this: *C) : *void {
// CHECK: local $x: *void
// CHECK: #b0:
// CHECK: n0: *C = load &$this
// CHECK: n1 = $builtins.hack_get_static_class(n0)
// CHECK: n2 = $builtins.hack_field_get(n1, "MY_CONSTANT")
// CHECK: store &$x <- n2: *HackMixed
// CHECK: ret null
// CHECK: }
public final function test_const(): void {
$x = C::MY_CONSTANT;
}
public static function test_static(): void {}
// TEST-CHECK-BAL: define C._86pinit
// CHECK: define C._86pinit($this: *C) : *HackMixed {
// CHECK: #b0:
// CHECK: n0: *HackMixed = load &$this
// CHECK: n1 = $builtins.hack_int(42)
// CHECK: store n0.?.prop1 <- n1: *HackMixed
// CHECK: n2 = $builtins.hack_string("hello")
// CHECK: store n0.?.prop2 <- n2: *HackMixed
// CHECK: n3 = null
// CHECK: store n0.?.prop5 <- n3: *HackMixed
// CHECK: n4 = $builtins.hack_int(2)
// CHECK: store n0.?.type <- n4: *HackMixed
// CHECK: n5 = __sil_lazy_class_initialize(<D>)
// CHECK: n6 = $builtins.hack_field_get(n5, "C")
// CHECK: store n0.?.prop5 <- n6: *HackMixed
// CHECK: ret null
// CHECK: }
}
// TEST-CHECK-BAL: define C$static._86sinit
// CHECK: define C$static._86sinit($this: *C$static) : *HackMixed {
// CHECK: #b0:
// CHECK: n0 = $builtins.hhbc_class_get_c($builtins.hack_string("C"))
// CHECK: n1 = $builtins.hack_set_static_prop($builtins.hack_string("C"), $builtins.hack_string("prop3"), $builtins.hack_float(3.14))
// CHECK: n2 = $builtins.hack_set_static_prop($builtins.hack_string("C"), $builtins.hack_string("prop4"), null)
// CHECK: n3 = $builtins.hack_set_static_prop($builtins.hack_string("C"), $builtins.hack_string("MY_CONSTANT"), $builtins.hack_int(7))
// CHECK: ret null
// CHECK: }
abstract class AbstractClass {
// TEST-CHECK-BAL: declare AbstractClass$static.abs_static_func
// CHECK: declare AbstractClass$static.abs_static_func(*AbstractClass$static, *HackInt, *HackFloat): *HackString
public static abstract function abs_static_func(int $a, float $b): string;
// TEST-CHECK-BAL: declare AbstractClass.abs_func
// CHECK: declare AbstractClass.abs_func(*AbstractClass, *HackInt, *HackFloat): *HackString
public abstract function abs_func(int $a, float $b): string;
}
trait T0 {
// TEST-CHECK-BAL: define T0.trait_parent_caller
// CHECK: define T0.trait_parent_caller($this: *T0, self: *HackMixed) : *void {
// CHECK: #b0:
// CHECK: n0: *T0 = load &$this
// CHECK: n1 = __parent__.test_const(n0)
// CHECK: ret null
// CHECK: }
public function trait_parent_caller(): void {
/* HH_FIXME[4074] This isn't valid Hack but actually occurs in www */
parent::test_const();
}
}
trait T1 {
require extends C;
// TEST-CHECK-BAL: define T1.trait_parent_caller
// CHECK: define T1.trait_parent_caller($this: *T1, self: *HackMixed) : *void {
// CHECK: #b0:
// CHECK: n0: *T1 = load &$this
// CHECK: n1 = __parent__.test_const(n0)
// CHECK: ret null
// CHECK: }
public function trait_parent_caller(): void {
parent::test_const();
}
// TEST-CHECK-BAL: define T1.trait_parent_static_caller
// CHECK: define T1.trait_parent_static_caller($this: *T1, self: *HackMixed) : *void {
// CHECK: #b0:
// CHECK: n0: *T1 = load &$this
// CHECK: n1 = __parent__.test_static(n0)
// CHECK: ret null
// CHECK: }
public function trait_parent_static_caller(): void {
parent::test_static();
}
}
trait T2 {
// TEST-CHECK-BAL: define T2$static.trait_self_caller
// CHECK: define T2$static.trait_self_caller($this: *T2$static, self: *HackMixed) : *void {
// CHECK: #b0:
// CHECK: n0: *T2$static = load &$this
// CHECK: n1 = __self__$static.f(n0)
// CHECK: ret null
// CHECK: }
public static function trait_self_caller(): void {
self::f();
}
public static function f(): void {}
}
trait T3 {
// TEST-CHECK-BAL: define T3.trait_self_caller
// CHECK: define T3.trait_self_caller($this: *T3, self: *HackMixed) : *void {
// CHECK: #b0:
// CHECK: n0: *T3 = load &$this
// CHECK: n1 = __self__.f(n0)
// CHECK: n2 = __self__.g(n0)
// CHECK: ret null
// CHECK: }
public function trait_self_caller(): void {
self::f();
/* HH_FIXME[4090] This isn't valid Hack but actually occurs in www */
self::g();
}
public static function f(): void {}
public function g(): void {}
}
// TEST-CHECK-BAL: define $root.dynamic_const
// CHECK: define $root.dynamic_const($this: *void, $c: *C) : *void {
// CHECK: #b0:
// CHECK: n0: *HackMixed = load &$c
// CHECK: n1 = $builtins.hhbc_class_get_c(n0)
// CHECK: n2 = $builtins.hhbc_cls_cns(n1, $builtins.hack_string("MY_CONSTANT"))
// CHECK: n3 = $builtins.hhbc_print(n2)
// CHECK: ret null
// CHECK: }
function dynamic_const(C $c): void {
echo $c::MY_CONSTANT;
}
// TEST-CHECK-BAL: define $root.cgets
// CHECK: define $root.cgets($this: *void) : *void {
// CHECK: #b0:
// CHECK: n0 = $builtins.hhbc_class_get_c($builtins.hack_string("C"))
// CHECK: n1 = $builtins.hack_field_get(n0, "prop3")
// CHECK: n2 = $root.sink(null, n1)
// CHECK: ret null
// CHECK: }
function cgets(): void {
sink(C::$prop3);
}
// TEST-CHECK-BAL: define $root.sets
// CHECK: define $root.sets($this: *void) : *void {
// CHECK: local $0: *void, $1: *void
// CHECK: #b0:
// CHECK: n0 = $builtins.hack_new_dict($builtins.hack_string("kind"), $builtins.hack_int(3))
// CHECK: n1 = $builtins.hhbc_class_get_c($builtins.hack_string("C"))
// CHECK: n2 = $root.source(null)
// CHECK: store &$0 <- n2: *HackMixed
// CHECK: store &$1 <- n0: *HackMixed
// CHECK: n3 = $builtins.hhbc_is_type_struct_c(n2, n0, $builtins.hack_int(1))
// CHECK: jmp b1, b2
// CHECK: #b1:
// CHECK: prune $builtins.hack_is_true(n3)
// CHECK: n4: *HackMixed = load &$0
// CHECK: store &$1 <- null: *HackMixed
// CHECK: n5 = $builtins.hack_set_static_prop($builtins.hack_string("C"), $builtins.hack_string("prop3"), n4)
// CHECK: ret null
// CHECK: #b2:
// CHECK: prune ! $builtins.hack_is_true(n3)
// CHECK: n6: *HackMixed = load &$0
// CHECK: n7: *HackMixed = load &$1
// CHECK: n8 = $builtins.hhbc_throw_as_type_struct_exception(n6, n7)
// CHECK: unreachable
// CHECK: }
function sets(): void {
C::$prop3 = source() as float;
} |
Hack | hhvm/hphp/hack/src/hackc/test/infer/class1.hack | // RUN: %hackc compile-infer %s | FileCheck %s
// TEST-CHECK-BAL: define C._86pinit
// CHECK: define C._86pinit($this: *C) : *HackMixed {
// CHECK: #b0:
// CHECK: ret null
// CHECK: }
class C {
const A = 5;
}
// TEST-CHECK-BAL: define D._86pinit
// CHECK: define D._86pinit($this: *D) : *HackMixed {
// CHECK: #b0:
// CHECK: n0: *D = load &$this
// CHECK: n1 = C._86pinit(n0)
// CHECK: ret null
// CHECK: }
class D extends C { }
// TEST-CHECK-BAL: define E._86pinit
// CHECK: define E._86pinit($this: *E) : *HackMixed {
// CHECK: #b0:
// CHECK: n0: *E = load &$this
// CHECK: n1 = D._86pinit(n0)
// CHECK: n2 = null
// CHECK: store n0.?.prop <- n2: *HackMixed
// CHECK: n3 = __sil_lazy_class_initialize(<C>)
// CHECK: n4 = $builtins.hack_field_get(n3, "A")
// CHECK: store n0.?.prop <- n4: *HackMixed
// CHECK: ret null
// CHECK: }
class E extends D {
public int $prop = C::A;
} |
Hack | hhvm/hphp/hack/src/hackc/test/infer/class_static.hack | // RUN: %hackc compile-infer %s | FileCheck %s
// TEST-CHECK-BAL: type C$static
// CHECK: type C$static = .kind="class" .static {
// CHECK: a: .public *HackInt
// CHECK: }
// TEST-CHECK-BAL: define C$static.foo
// CHECK: define C$static.foo($this: *C$static) : *void {
// CHECK: #b0:
// CHECK: n0 = $builtins.hhbc_class_get_c($builtins.hack_string("C"))
// CHECK: n1 = $builtins.hack_set_static_prop($builtins.hack_string("C"), $builtins.hack_string("a"), $builtins.hack_int(6))
// CHECK: ret null
// CHECK: }
class C {
public static int $a = 5;
public static function foo(): void {
C::$a = 6;
}
} |
Hack | hhvm/hphp/hack/src/hackc/test/infer/class_tc.hack | interface SomeAttribute extends HH\StaticPropertyAttribute { }
class D {
const int C = 5;
}
function sink(mixed $x): void { }
function source(): mixed { return 0; } |
Hack | hhvm/hphp/hack/src/hackc/test/infer/closure.hack | // RUN: %hackc compile-infer %s | FileCheck %s
// TEST-CHECK-BAL: define Closure$closure1.__invoke
// CHECK: define Closure$closure1.__invoke($this: *Closure$closure1) : *HackMixed {
// CHECK: local $x: *void
// CHECK: #b0:
// CHECK: n0: *HackMixed = load &$this
// CHECK: n1: *HackMixed = load n0.?.x
// CHECK: store &$x <- n1: *HackMixed
// CHECK: n2 = $builtins.hhbc_print(n1)
// CHECK: ret n2
// CHECK: }
// TEST-CHECK-BAL: define Closure$closure1.__construct
// CHECK: define Closure$closure1.__construct($this: *Closure$closure1, x: *HackMixed) : *HackMixed {
// CHECK: #b0:
// CHECK: n0: *HackMixed = load &x
// CHECK: n1: *HackMixed = load &$this
// CHECK: store n1.?.x <- n0: *HackMixed
// CHECK: ret null
// CHECK: }
// TEST-CHECK-BAL: define $root.closure1
// CHECK: define $root.closure1($this: *void, $x: *HackString) : *HackMixed {
// CHECK: local $y: *void
// CHECK: #b0:
// CHECK: n0: *HackMixed = load &$x
// CHECK: n1 = __sil_allocate(<Closure$closure1>)
// CHECK: n2 = Closure$closure1.__construct(n1, n0)
// CHECK: store &$y <- n1: *HackMixed
// CHECK: ret n1
// CHECK: }
function closure1(string $x): mixed {
$y = () ==> print($x);
return $y;
} |
Hack | hhvm/hphp/hack/src/hackc/test/infer/concurrent.hack | // RUN: %hackc compile-infer %s | FileCheck %s
namespace Concurrent {
async function genGetInt(): Awaitable<int> {
return 42;
}
async function genGetString(): Awaitable<string> {
return "Hello";
}
async function genVoid1(): Awaitable<void> {
return;
}
async function genVoid2(): Awaitable<void> {
return;
}
async function genGetVecInt(): Awaitable<vec<int>> {
return vec[23, 42];
}
// TEST-CHECK-BAL: define .async $root.Concurrent::genTest1
// CHECK: define .async $root.Concurrent::genTest1($this: *void) : *HackString {
// CHECK: local $f1: *void, $f2: *void
// CHECK: #b0:
// CHECK: n0 = $root.Concurrent::genGetInt(null)
// CHECK: n1 = $builtins.hhbc_await(n0)
// CHECK: store &$f1 <- n1: *HackMixed
// CHECK: n2 = $root.Concurrent::genVoid1(null)
// CHECK: n3 = $builtins.hhbc_await(n2)
// CHECK: n4 = $root.Concurrent::genGetString(null)
// CHECK: n5 = $builtins.hhbc_await(n4)
// CHECK: store &$f2 <- n5: *HackMixed
// CHECK: n6 = $builtins.hhbc_concat(n5, n1)
// CHECK: n7 = $builtins.hhbc_is_type_str(n6)
// CHECK: n8 = $builtins.hhbc_verify_type_pred(n6, n7)
// CHECK: ret n6
// CHECK: }
async function genTest1(): Awaitable<string> {
concurrent {
$f1 = await genGetInt();
await genVoid1();
$f2 = await genGetString();
}
return $f2.$f1;
}
// TEST-CHECK-BAL: define .async $root.Concurrent::genTest2
// CHECK: define .async $root.Concurrent::genTest2($this: *void) : *HackMixed {
// CHECK: #b0:
// CHECK: n0 = $root.Concurrent::genVoid1(null)
// CHECK: n1 = $builtins.hhbc_await(n0)
// CHECK: n2 = $root.Concurrent::genVoid2(null)
// CHECK: n3 = $builtins.hhbc_await(n2)
// CHECK: ret null
// CHECK: }
async function genTest2(): Awaitable<void> {
concurrent {
await genVoid1();
await genVoid2();
}
}
// TEST-CHECK-BAL: define .async $root.Concurrent::genTest3
// CHECK: define .async $root.Concurrent::genTest3($this: *void) : *HackInt {
// CHECK: local $x: *void, $y: *void, $z: *void, $0: *void
// CHECK: #b0:
// CHECK: n0 = $root.Concurrent::genGetVecInt(null)
// CHECK: n1 = $builtins.hhbc_await(n0)
// CHECK: store &$0 <- n1: *HackMixed
// CHECK: jmp b1
// CHECK: #b1:
// CHECK: n2 = $builtins.hack_int(1)
// CHECK: n3: *HackMixed = load &$0
// CHECK: n4 = $builtins.hack_array_get(n3, n2)
// CHECK: store &$y <- n4: *HackMixed
// CHECK: n5 = $builtins.hack_int(0)
// CHECK: n6 = $builtins.hack_array_get(n3, n5)
// CHECK: store &$x <- n6: *HackMixed
// CHECK: jmp b3
// CHECK: .handlers b2
// CHECK: #b2(n7: *HackMixed):
// CHECK: store &$0 <- null: *HackMixed
// CHECK: n8 = $builtins.hhbc_throw(n7)
// CHECK: unreachable
// CHECK: #b3:
// CHECK: store &$0 <- null: *HackMixed
// CHECK: n9 = $root.Concurrent::genGetInt(null)
// CHECK: n10 = $builtins.hhbc_await(n9)
// CHECK: store &$z <- n10: *HackMixed
// CHECK: n11: *HackMixed = load &$y
// CHECK: n12: *HackMixed = load &$x
// CHECK: n13 = $builtins.hhbc_add(n12, n11)
// CHECK: n14 = $builtins.hhbc_add(n13, n10)
// CHECK: n15 = $builtins.hhbc_is_type_int(n14)
// CHECK: n16 = $builtins.hhbc_verify_type_pred(n14, n15)
// CHECK: ret n14
// CHECK: }
async function genTest3(): Awaitable<int> {
concurrent {
list($x, $y) = await genGetVecInt();
$z = await genGetInt();
}
return $x + $y + $z;
}
function intToString(int $x): string {
return "".$x;
}
// TEST-CHECK-BAL: define .async $root.Concurrent::genTest4
// CHECK: define .async $root.Concurrent::genTest4($this: *void) : *HackString {
// CHECK: local $x: *void, $y: *void, $0: *void
// CHECK: #b0:
// CHECK: n0 = $root.Concurrent::genGetInt(null)
// CHECK: n1 = $builtins.hhbc_await(n0)
// CHECK: store &$0 <- n1: *HackMixed
// CHECK: jmp b1
// CHECK: #b1:
// CHECK: n2: *HackMixed = load &$0
// CHECK: n3 = $root.Concurrent::intToString(null, n2)
// CHECK: store &$x <- n3: *HackMixed
// CHECK: jmp b3
// CHECK: .handlers b2
// CHECK: #b2(n4: *HackMixed):
// CHECK: store &$0 <- null: *HackMixed
// CHECK: n5 = $builtins.hhbc_throw(n4)
// CHECK: unreachable
// CHECK: #b3:
// CHECK: store &$0 <- null: *HackMixed
// CHECK: n6 = $root.Concurrent::genGetString(null)
// CHECK: n7 = $builtins.hhbc_await(n6)
// CHECK: store &$y <- n7: *HackMixed
// CHECK: n8: *HackMixed = load &$x
// CHECK: n9 = $builtins.hhbc_concat(n8, n7)
// CHECK: n10 = $builtins.hhbc_is_type_str(n9)
// CHECK: n11 = $builtins.hhbc_verify_type_pred(n9, n10)
// CHECK: ret n9
// CHECK: }
async function genTest4(): Awaitable<string> {
concurrent {
$x = intToString(await genGetInt());
$y = await genGetString();
}
return $x.$y;
}
} |
Hack | hhvm/hphp/hack/src/hackc/test/infer/constructor.hack | // RUN: %hackc compile-infer %s | FileCheck %s
class A {
public function a() : void {}
}
// TEST-CHECK-BAL: define $root.f1
// CHECK: define $root.f1($this: *void) : *void {
// CHECK: local $0: *void, $1: *void, $2: *void
// CHECK: #b0:
// CHECK: jmp b1
// CHECK: #b1:
// CHECK: n0 = __sil_lazy_class_initialize(<A>)
// CHECK: store &$0 <- n0: *HackMixed
// CHECK: n1 = __sil_allocate(<A>)
// CHECK: n2 = A._86pinit(n1)
// CHECK: store &$2 <- n1: *HackMixed
// CHECK: jmp b2
// CHECK: .handlers b4
// CHECK: #b2:
// CHECK: jmp b3
// CHECK: #b3:
// CHECK: n3: *HackMixed = load &$2
// CHECK: jmp b5
// CHECK: .handlers b4
// CHECK: #b4(n4: *HackMixed):
// CHECK: store &$0 <- null: *HackMixed
// CHECK: store &$1 <- null: *HackMixed
// CHECK: store &$2 <- null: *HackMixed
// CHECK: n5 = $builtins.hhbc_throw(n4)
// CHECK: unreachable
// CHECK: #b5:
// CHECK: store &$0 <- null: *HackMixed
// CHECK: store &$1 <- null: *HackMixed
// CHECK: store &$2 <- null: *HackMixed
// CHECK: n6 = n3.?.__construct()
// CHECK: n7 = $builtins.hhbc_lock_obj(n3)
// CHECK: n8 = n3.?.a()
// CHECK: ret null
// CHECK: }
function f1() : void {
(new A())->a();
} |
Hack | hhvm/hphp/hack/src/hackc/test/infer/enum.hack | // RUN: %hackc compile-infer %s | FileCheck %s
// TEST-CHECK-BAL: "type A "
// CHECK: type A extends HH::BuiltinEnum = .kind="class" {
// CHECK: }
// TEST-CHECK-BAL: define A$static._86sinit
// CHECK: define A$static._86sinit($this: *A$static) : *HackMixed {
// CHECK: #b0:
// CHECK: n0: *A$static = load &$this
// CHECK: n1 = HH::BuiltinEnum$static._86sinit(n0)
// CHECK: n2 = $builtins.hhbc_class_get_c($builtins.hack_string("A"))
// CHECK: n3 = $builtins.hack_set_static_prop($builtins.hack_string("A"), $builtins.hack_string("V"), $builtins.hack_int(1))
// CHECK: ret null
// CHECK: }
enum A: int {
V = 1;
}
// TEST-CHECK-BAL: define $root.main
// CHECK: define $root.main($this: *void) : *void {
// CHECK: #b0:
// CHECK: n0 = $builtins.hhbc_print($builtins.hack_string("A::V = "))
// CHECK: n1 = __sil_lazy_class_initialize(<A>)
// CHECK: n2 = $builtins.hack_field_get(n1, "V")
// CHECK: n3 = $builtins.hhbc_print(n2)
// CHECK: n4 = $builtins.hhbc_print($builtins.hack_string("\n"))
// CHECK: n5 = $builtins.hhbc_print($builtins.hack_string("B::V = "))
// CHECK: n6 = __sil_lazy_class_initialize(<B>)
// CHECK: n7 = $builtins.hack_field_get(n6, "V")
// CHECK: n8 = $builtins.hhbc_print(n7)
// CHECK: n9 = $builtins.hhbc_print($builtins.hack_string("\n"))
// CHECK: ret null
// CHECK: }
function main(): void {
echo "A::V = ", A::V, "\n";
echo "B::V = ", B::V, "\n";
} |
Hack | hhvm/hphp/hack/src/hackc/test/infer/fcall.hack | // RUN: %hackc compile-infer %s | FileCheck %s
class D extends B {
// TEST-CHECK-BAL: define D.inst_fcall_self
// CHECK: define D.inst_fcall_self($this: *D) : *void {
// CHECK: #b0:
// CHECK: n0: *D = load &$this
// CHECK: n1 = D.bar(n0)
// CHECK: ret null
// CHECK: }
public function inst_fcall_self(): void {
self::bar();
}
// TEST-CHECK-BAL: define D$static.static_fcall_self
// CHECK: define D$static.static_fcall_self($this: *D$static) : *void {
// CHECK: #b0:
// CHECK: n0: *D$static = load &$this
// CHECK: n1 = D$static.bar(n0)
// CHECK: ret null
// CHECK: }
public static function static_fcall_self(): void {
self::bar();
}
// TEST-CHECK-BAL: define D.inst_fcall_static
// CHECK: define D.inst_fcall_static($this: *D) : *void {
// CHECK: #b0:
// CHECK: n0: *D = load &$this
// CHECK: n1 = n0.D.bar()
// CHECK: ret null
// CHECK: }
public function inst_fcall_static(): void {
static::bar();
}
// TEST-CHECK-BAL: define D$static.static_fcall_static
// CHECK: define D$static.static_fcall_static($this: *D$static) : *void {
// CHECK: #b0:
// CHECK: n0: *D$static = load &$this
// CHECK: n1 = n0.D$static.bar()
// CHECK: ret null
// CHECK: }
public static function static_fcall_static(): void {
static::bar();
}
// TEST-CHECK-BAL: define D.inst_fcall_parent
// CHECK: define D.inst_fcall_parent($this: *D) : *void {
// CHECK: #b0:
// CHECK: n0: *D = load &$this
// CHECK: n1 = B.bar(n0)
// CHECK: ret null
// CHECK: }
public function inst_fcall_parent(): void {
parent::bar();
}
// TEST-CHECK-BAL: define D$static.static_fcall_parent
// CHECK: define D$static.static_fcall_parent($this: *D$static) : *void {
// CHECK: #b0:
// CHECK: n0: *D$static = load &$this
// CHECK: n1 = B$static.bar(n0)
// CHECK: ret null
// CHECK: }
public static function static_fcall_parent(): void {
parent::bar();
}
public static function bar(): void { }
}
// TEST-CHECK-1: define $root.MethCaller$C$b
// CHECK: define $root.MethCaller$C$b($this: *void, $o: *HackMixed, $args: .variadic *array) : *HackMixed {
// TEST-CHECK-BAL: define $root.fcall_func
// CHECK: define $root.fcall_func($this: *void) : *void {
// CHECK: #b0:
// CHECK: n0 = $root.f(null, $builtins.hack_int(1), $builtins.hack_int(2), $builtins.hack_int(3))
// CHECK: ret null
// CHECK: }
function fcall_func(): void {
f(1, 2, 3);
}
// TEST-CHECK-BAL: define $root.fcall_static
// CHECK: define $root.fcall_static($this: *void) : *void {
// CHECK: #b0:
// CHECK: n0 = __sil_lazy_class_initialize(<C>)
// CHECK: n1 = C$static.f(n0, $builtins.hack_int(1), $builtins.hack_int(2), $builtins.hack_int(3))
// CHECK: ret null
// CHECK: }
function fcall_static(): void {
C::f(1, 2, 3);
}
// TEST-CHECK-BAL: define $root.fcall_method
// CHECK: define $root.fcall_method($this: *void, $a: *C) : *void {
// CHECK: #b0:
// CHECK: n0: *HackMixed = load &$a
// CHECK: n1 = n0.?.b($builtins.hack_int(1), $builtins.hack_int(2), $builtins.hack_int(3))
// CHECK: ret null
// CHECK: }
function fcall_method(C $a): void {
$a->b(1, 2, 3);
}
// TEST-CHECK-BAL: define $root.fcall_nullsafe
// CHECK: define $root.fcall_nullsafe($this: *void, $c: *C) : *void {
// CHECK: #b0:
// CHECK: n0: *HackMixed = load &$c
// CHECK: n1 = $builtins.hhbc_is_type_null(n0)
// CHECK: jmp b1, b2
// CHECK: #b1:
// CHECK: prune $builtins.hack_is_true(n1)
// CHECK: jmp b3(null)
// CHECK: #b2:
// CHECK: prune ! $builtins.hack_is_true(n1)
// CHECK: n2 = n0.?.g()
// CHECK: jmp b3(n2)
// CHECK: #b3(n3: *HackMixed):
// CHECK: n4 = $root.f(null, n3)
// CHECK: ret null
// CHECK: }
function fcall_nullsafe(?C $c): void {
f($c?->g());
}
// TEST-CHECK-BAL: define $root.fcall_class_meth
// CHECK: define $root.fcall_class_meth($this: *void) : *void {
// CHECK: local $x: *void, $0: *void
// CHECK: #b0:
// CHECK: n0 = __sil_lazy_class_initialize(<C>)
// CHECK: n1 = __sil_allocate(<C$static_sb$curry>)
// CHECK: store n1.C$static_sb$curry.this <- n0: *C$static
// CHECK: store &$x <- n1: *HackMixed
// CHECK: jmp b1
// CHECK: #b1:
// CHECK: n2: *HackMixed = load &$x
// CHECK: store &$0 <- n2: *HackMixed
// CHECK: n3 = n2.?.__invoke($builtins.hack_int(1), $builtins.hack_int(2), $builtins.hack_int(3))
// CHECK: jmp b3
// CHECK: .handlers b2
// CHECK: #b2(n4: *HackMixed):
// CHECK: store &$0 <- null: *HackMixed
// CHECK: n5 = $builtins.hhbc_throw(n4)
// CHECK: unreachable
// CHECK: #b3:
// CHECK: ret null
// CHECK: }
function fcall_class_meth(): void {
$x = C::sb<>;
$x(1, 2, 3);
}
// TEST-CHECK-BAL: define $root.fcall_func_invoke
// CHECK: define $root.fcall_func_invoke($this: *void) : *void {
// CHECK: local $x: *void, $0: *void
// CHECK: #b0:
// CHECK: n0 = __sil_allocate(<f$curry>)
// CHECK: store &$x <- n0: *HackMixed
// CHECK: jmp b1
// CHECK: #b1:
// CHECK: n1: *HackMixed = load &$x
// CHECK: store &$0 <- n1: *HackMixed
// CHECK: n2 = n1.?.__invoke($builtins.hack_int(1), $builtins.hack_int(2), $builtins.hack_int(3))
// CHECK: jmp b3
// CHECK: .handlers b2
// CHECK: #b2(n3: *HackMixed):
// CHECK: store &$0 <- null: *HackMixed
// CHECK: n4 = $builtins.hhbc_throw(n3)
// CHECK: unreachable
// CHECK: #b3:
// CHECK: ret null
// CHECK: }
function fcall_func_invoke(): void {
$x = f<>;
$x(1, 2, 3);
}
// TEST-CHECK-BAL: define $root.fcall_splat
// CHECK: define $root.fcall_splat($this: *void) : *void {
// CHECK: local $x: *void
// CHECK: #b0:
// CHECK: n0 = $builtins.hhbc_new_vec($builtins.hack_int(2), $builtins.hack_int(3), $builtins.hack_int(4))
// CHECK: store &$x <- n0: *HackMixed
// CHECK: n1 = $builtins.__sil_splat(n0)
// CHECK: n2 = $root.f(null, $builtins.hack_int(1), n1)
// CHECK: ret null
// CHECK: }
function fcall_splat(): void {
$x = vec[2, 3, 4];
f(1, ...$x);
}
// TEST-CHECK-BAL: define $root.fcall_meth_caller
// CHECK: define $root.fcall_meth_caller($this: *void, $b: *C) : *void {
// CHECK: local $x: *void, $0: *void
// CHECK: #b0:
// CHECK: n0 = __sil_allocate(<MethCaller$C$b$curry>)
// CHECK: store n0.MethCaller$C$b$curry.arg0 <- null: *void
// CHECK: store &$x <- n0: *HackMixed
// CHECK: jmp b1
// CHECK: #b1:
// CHECK: n1: *HackMixed = load &$x
// CHECK: store &$0 <- n1: *HackMixed
// CHECK: n2: *HackMixed = load &$b
// CHECK: n3 = n1.?.__invoke(n2, $builtins.hack_int(1), $builtins.hack_int(2), $builtins.hack_int(3))
// CHECK: jmp b3
// CHECK: .handlers b2
// CHECK: #b2(n4: *HackMixed):
// CHECK: store &$0 <- null: *HackMixed
// CHECK: n5 = $builtins.hhbc_throw(n4)
// CHECK: unreachable
// CHECK: #b3:
// CHECK: ret null
// CHECK: }
function fcall_meth_caller(C $b): void {
$x = meth_caller(C::class, 'b');
$x($b, 1, 2, 3);
}
// TEST-CHECK-BAL: define $root.fcall_cls_method
// CHECK: define $root.fcall_cls_method($this: *void, $a: *Classname) : *void {
// CHECK: #b0:
// CHECK: n0 = $builtins.hack_new_dict($builtins.hack_string("kind"), $builtins.hack_int(101), $builtins.hack_string("classname"), $builtins.hack_string("HH\\classname"))
// CHECK: n1: *HackMixed = load &$a
// CHECK: n2 = $builtins.hhbc_verify_param_type_ts(n1, n0)
// CHECK: n3 = n1.?.static_fcall_self()
// CHECK: ret null
// CHECK: }
function fcall_cls_method(classname<D> $a): void {
$a::static_fcall_self();
}
// TEST-CHECK-BAL: type C$static_sb$curry
// CHECK: type C$static_sb$curry = .kind="class" .final {
// CHECK: this: .private *C$static
// CHECK: }
// TEST-CHECK-BAL: define .final .curry C$static_sb$curry.__invoke
// CHECK: define .final .curry C$static_sb$curry.__invoke(this: *C$static_sb$curry, args: .variadic *HackVec) : *HackMixed {
// CHECK: #b0:
// CHECK: n0: *C$static_sb$curry = load &this
// CHECK: n1: *HackVec = load &args
// CHECK: n2 = $builtins.__sil_splat(n1)
// CHECK: n3: *C$static = load n0.C$static_sb$curry.this
// CHECK: n4 = n3.C$static.sb(n2)
// CHECK: ret n4
// CHECK: }
// TEST-CHECK-BAL: type f$curry
// CHECK: type f$curry = .kind="class" .final {
// CHECK: }
// TEST-CHECK-BAL: define .final .curry f$curry.__invoke
// CHECK: define .final .curry f$curry.__invoke(this: *f$curry, args: .variadic *HackVec) : *HackMixed {
// CHECK: #b0:
// CHECK: n0: *f$curry = load &this
// CHECK: n1: *HackVec = load &args
// CHECK: n2 = $builtins.__sil_splat(n1)
// CHECK: n3 = $root.f(null, n2)
// CHECK: ret n3
// CHECK: }
// TEST-CHECK-BAL: type MethCaller$C$b$curry
// CHECK: type MethCaller$C$b$curry = .kind="class" .final {
// CHECK: arg0: .private *void
// CHECK: }
// TEST-CHECK-BAL: define .final .curry MethCaller$C$b$curry.__invoke
// CHECK: define .final .curry MethCaller$C$b$curry.__invoke(this: *MethCaller$C$b$curry, args: .variadic *HackVec) : *HackMixed {
// CHECK: #b0:
// CHECK: n0: *MethCaller$C$b$curry = load &this
// CHECK: n1: *void = load n0.MethCaller$C$b$curry.arg0
// CHECK: n2: *HackVec = load &args
// CHECK: n3 = $builtins.__sil_splat(n2)
// CHECK: n4 = $root.MethCaller$C$b(null, n1, n3)
// CHECK: ret n4
// CHECK: }
// TEST-CHECK-1: declare C$static.f
// CHECK: declare C$static.f(...): *HackMixed |
Hack | hhvm/hphp/hack/src/hackc/test/infer/fcall_default.hack | // RUN: %hackc compile-infer %s | FileCheck %s
class C {
// TEST-CHECK-BAL: define C.myfn2($this: *C, $a: *HackInt)
// CHECK: define C.myfn2($this: *C, $a: *HackInt) : *void {
// CHECK: local $b: *void, $c: *void
// CHECK: #b0:
// CHECK: store &$b <- $builtins.hack_int(1): *HackMixed
// CHECK: store &$c <- $builtins.hack_int(2): *HackMixed
// CHECK: jmp b1
// CHECK: #b1:
// CHECK: n0: *HackMixed = load &$a
// CHECK: n1: *HackMixed = load &$b
// CHECK: n2: *HackMixed = load &$c
// CHECK: n3: *HackMixed = load &$this
// CHECK: n4 = n3.?.myfn2(n0, n1, n2)
// CHECK: ret n4
// CHECK: }
// TEST-CHECK-BAL: define C.myfn2($this: *C, $a: *HackInt, $b: *HackInt)
// CHECK: define C.myfn2($this: *C, $a: *HackInt, $b: *HackInt) : *void {
// CHECK: local $c: *void
// CHECK: #b0:
// CHECK: store &$c <- $builtins.hack_int(2): *HackMixed
// CHECK: jmp b1
// CHECK: #b1:
// CHECK: n0: *HackMixed = load &$a
// CHECK: n1: *HackMixed = load &$b
// CHECK: n2: *HackMixed = load &$c
// CHECK: n3: *HackMixed = load &$this
// CHECK: n4 = n3.?.myfn2(n0, n1, n2)
// CHECK: ret n4
// CHECK: }
// TEST-CHECK-BAL: define C.myfn2($this: *C, $a: *HackInt, $b: *HackInt, $c: *HackInt)
// CHECK: define C.myfn2($this: *C, $a: *HackInt, $b: *HackInt, $c: *HackInt) : *void {
// CHECK: #b0:
// CHECK: n0: *HackMixed = load &$a
// CHECK: n1: *HackMixed = load &$b
// CHECK: n2: *HackMixed = load &$c
// CHECK: n3 = $root.printf(null, $builtins.hack_string("%d %d %d\n"), n0, n1, n2)
// CHECK: ret null
// CHECK: }
public function myfn2(int $a, int $b = 1, int $c = 2): void {
printf("%d %d %d\n", $a, $b, $c);
}
}
// TEST-CHECK-BAL: define $root.myfn($this: *void, $a: *HackInt)
// CHECK: define $root.myfn($this: *void, $a: *HackInt) : *void {
// CHECK: local $b: *void, $c: *void
// CHECK: #b0:
// CHECK: store &$b <- $builtins.hack_int(1): *HackMixed
// CHECK: store &$c <- $builtins.hack_int(2): *HackMixed
// CHECK: jmp b1
// CHECK: #b1:
// CHECK: n0: *HackMixed = load &$a
// CHECK: n1: *HackMixed = load &$b
// CHECK: n2: *HackMixed = load &$c
// CHECK: n3 = $root.myfn(null, n0, n1, n2)
// CHECK: ret n3
// CHECK: }
// TEST-CHECK-BAL: define $root.myfn($this: *void, $a: *HackInt, $b: *HackInt)
// CHECK: define $root.myfn($this: *void, $a: *HackInt, $b: *HackInt) : *void {
// CHECK: local $c: *void
// CHECK: #b0:
// CHECK: store &$c <- $builtins.hack_int(2): *HackMixed
// CHECK: jmp b1
// CHECK: #b1:
// CHECK: n0: *HackMixed = load &$a
// CHECK: n1: *HackMixed = load &$b
// CHECK: n2: *HackMixed = load &$c
// CHECK: n3 = $root.myfn(null, n0, n1, n2)
// CHECK: ret n3
// CHECK: }
// TEST-CHECK-BAL: define $root.myfn($this: *void, $a: *HackInt, $b: *HackInt, $c: *HackInt)
// CHECK: define $root.myfn($this: *void, $a: *HackInt, $b: *HackInt, $c: *HackInt) : *void {
// CHECK: #b0:
// CHECK: n0: *HackMixed = load &$a
// CHECK: n1: *HackMixed = load &$b
// CHECK: n2: *HackMixed = load &$c
// CHECK: n3 = $root.printf(null, $builtins.hack_string("%d %d %d\n"), n0, n1, n2)
// CHECK: ret null
// CHECK: }
function myfn(int $a, int $b = 1, int $c = 2): void {
printf("%d %d %d\n", $a, $b, $c);
} |
Hack | hhvm/hphp/hack/src/hackc/test/infer/fcall_tc.hack | // Typecheck Helpers
function f(mixed... $_): void { }
class B {
public static function bar(): void { }
}
class C {
public function b(int $a, int $b, int $c): void { }
public static function sb(int $a, int $b, int $c): void { }
public static function f(mixed... $_): void { }
public function g(): void { }
} |
Hack | hhvm/hphp/hack/src/hackc/test/infer/foreach.hack | // RUN: %hackc compile-infer %s | FileCheck %s
// TEST-CHECK-BAL: define $root.check_foreach
// CHECK: define $root.check_foreach($this: *void, $x: *HackVec) : *void {
// CHECK: local $index: *void, iter0: *void
// CHECK: #b0:
// CHECK: n0 = $builtins.hack_new_dict($builtins.hack_string("kind"), $builtins.hack_int(20), $builtins.hack_string("generic_types"), $builtins.hhbc_new_vec($builtins.hack_new_dict($builtins.hack_string("kind"), $builtins.hack_int(4))))
// CHECK: n1: *HackMixed = load &$x
// CHECK: n2 = $builtins.hhbc_verify_param_type_ts(n1, n0)
// CHECK: n3 = $builtins.hhbc_iter_init(&iter0, null, &$index, n1)
// CHECK: jmp b1, b6
// CHECK: #b1:
// CHECK: prune $builtins.hack_is_true(n3)
// CHECK: jmp b2
// CHECK: #b2:
// CHECK: n4: *HackMixed = load &$index
// CHECK: n5 = $builtins.hhbc_print(n4)
// CHECK: n6: *HackMixed = load &iter0
// CHECK: n7 = $builtins.hhbc_iter_next(n6, null, &$index)
// CHECK: jmp b4, b5
// CHECK: .handlers b3
// CHECK: #b3(n8: *HackMixed):
// CHECK: n9: *HackMixed = load &iter0
// CHECK: n10 = $builtins.hhbc_iter_free(n9)
// CHECK: n11 = $builtins.hhbc_throw(n8)
// CHECK: unreachable
// CHECK: #b4:
// CHECK: prune $builtins.hack_is_true(n7)
// CHECK: jmp b7
// CHECK: #b5:
// CHECK: prune ! $builtins.hack_is_true(n7)
// CHECK: jmp b2
// CHECK: #b6:
// CHECK: prune ! $builtins.hack_is_true(n3)
// CHECK: jmp b7
// CHECK: #b7:
// CHECK: ret null
// CHECK: }
function check_foreach(vec<string> $x): void {
foreach ($x as $index) {
echo $index;
}
} |
Hack | hhvm/hphp/hack/src/hackc/test/infer/hierarchy.hack | // RUN: %hackc compile-infer %s | FileCheck %s
// TEST-CHECK-BAL: type A$static
// CHECK: type A$static = .kind="class" .static {
// CHECK: }
// TEST-CHECK-BAL: "type A "
// CHECK: type A = .kind="class" {
// CHECK: }
class A { }
// TEST-CHECK-BAL: type I0$static
// CHECK: type I0$static = .kind="interface" .static {
// CHECK: }
// TEST-CHECK-BAL: "type I0 "
// CHECK: type I0 = .kind="interface" {
// CHECK: }
interface I0 { }
// TEST-CHECK-BAL: type I1$static
// CHECK: type I1$static extends I0$static = .kind="interface" .static {
// CHECK: }
// TEST-CHECK-BAL: "type I1 "
// CHECK: type I1 extends I0 = .kind="interface" {
// CHECK: }
interface I1 extends I0 { }
// TEST-CHECK-BAL: type T$static
// CHECK: type T$static = .kind="trait" .static {
// CHECK: }
// TEST-CHECK-BAL: "type T "
// CHECK: type T = .kind="trait" {
// CHECK: }
trait T { }
// TEST-CHECK-BAL: type B$static
// CHECK: type B$static extends A$static, I1$static, T$static = .kind="class" .static {
// CHECK: }
// TEST-CHECK-BAL: "type B "
// CHECK: type B extends A, I1, T = .kind="class" {
// CHECK: }
class B extends A implements I1 {
use T;
} |
Hack | hhvm/hphp/hack/src/hackc/test/infer/instr.hack | // RUN: %hackc compile-infer %s | FileCheck %s
// Random instruction tests.
// TEST-CHECK-1: define $root.binops
// CHECK: define $root.binops($this: *void, $a: *HackInt, $b: *HackInt) : *void {
function binops(int $a, int $b): void {
// TEST-CHECK-1*: $builtins.hhbc_add
// CHECK: n2 = $builtins.hhbc_add(n1, n0)
$c = $a + $b;
// TEST-CHECK-1*: $builtins.hhbc_cmp_eq
// CHECK: n3 = $builtins.hhbc_cmp_eq(n1, n0)
$c = $a == $b;
// TEST-CHECK-1*: $builtins.hhbc_cmp_gt
// CHECK: n4 = $builtins.hhbc_cmp_gt(n1, n0)
$c = $a > $b;
// TEST-CHECK-1*: $builtins.hhbc_cmp_gte
// CHECK: n5 = $builtins.hhbc_cmp_gte(n1, n0)
$c = $a >= $b;
// TEST-CHECK-1*: $builtins.hhbc_cmp_lt
// CHECK: n6 = $builtins.hhbc_cmp_lt(n1, n0)
$c = $a < $b;
// TEST-CHECK-1*: $builtins.hhbc_cmp_lte
// CHECK: n7 = $builtins.hhbc_cmp_lte(n1, n0)
$c = $a <= $b;
// TEST-CHECK-1*: $builtins.hhbc_cmp_nsame
// CHECK: n8 = $builtins.hhbc_cmp_nsame(n1, n0)
$c = $a !== $b;
// TEST-CHECK-1*: $builtins.hhbc_cmp_neq
// CHECK: n9 = $builtins.hhbc_cmp_neq(n1, n0)
$c = $a != $b;
// TEST-CHECK-1*: $builtins.hhbc_cmp_same
// CHECK: n10 = $builtins.hhbc_cmp_same(n1, n0)
$c = $a === $b;
// TEST-CHECK-1*: $builtins.hhbc_concat
// CHECK: n11 = $builtins.hhbc_concat(n1, n0)
$c = $a . $b;
// TEST-CHECK-1*: $builtins.hhbc_div
// CHECK: n12 = $builtins.hhbc_div(n1, n0)
$c = $a / $b;
// TEST-CHECK-1*: $builtins.hhbc_modulo
// CHECK: n13 = $builtins.hhbc_modulo(n1, n0)
$c = $a % $b;
// TEST-CHECK-1*: $builtins.hhbc_mul
// CHECK: n14 = $builtins.hhbc_mul(n1, n0)
$c = $a * $b;
// TEST-CHECK-1*: $builtins.hhbc_sub
// CHECK: n15 = $builtins.hhbc_sub(n1, n0)
$c = $a - $b;
}
// TEST-CHECK-1: define $root.unops
// CHECK: define $root.unops($this: *void, $a: *HackInt) : *void {
function unops(int $a): void {
// TEST-CHECK-1*: $builtins.hhbc_not
// CHECK: n1 = $builtins.hhbc_not(n0)
$c = ! $a;
}
// TEST-CHECK-BAL: define $root.check_shape
// CHECK: define $root.check_shape($this: *void) : *void {
// CHECK: #b0:
// CHECK: n0 = $root.a(null)
// CHECK: n1 = $root.b(null)
// CHECK: n2 = $builtins.hack_new_dict($builtins.hack_string("a"), n0, $builtins.hack_string("b"), n1)
// CHECK: n3 = $root.f(null, n2)
// CHECK: ret null
// CHECK: }
function check_shape(): void {
f(shape('a' => a(), 'b' => b()));
}
// TEST-CHECK-BAL: define $root.check_closure
// CHECK: define $root.check_closure($this: *void, $x: *HackInt) : *void {
// CHECK: local $impl: *void
// CHECK: #b0:
// CHECK: n0: *HackMixed = load &$x
// CHECK: n1 = __sil_allocate(<Closure$check_closure>)
// CHECK: n2 = Closure$check_closure.__construct(n1, n0)
// CHECK: store &$impl <- n1: *HackMixed
// CHECK: ret null
// CHECK: }
function check_closure(int $x): void {
$impl = () ==> { return $x; };
}
// TEST-CHECK-BAL: define $root.add_elem
// CHECK: define $root.add_elem($this: *void, $s1: *HackString, $s2: *HackString) : *void {
// CHECK: local $c: *void
// CHECK: #b0:
// CHECK: n0 = $builtins.hhbc_new_dict()
// CHECK: n1: *HackMixed = load &$s1
// CHECK: n2 = $builtins.hhbc_add_elem_c(n0, n1, $builtins.hack_int(0))
// CHECK: n3: *HackMixed = load &$s2
// CHECK: n4 = $builtins.hhbc_add_elem_c(n2, n3, $builtins.hack_int(1))
// CHECK: store &$c <- n4: *HackMixed
// CHECK: ret null
// CHECK: }
function add_elem(string $s1, string $s2) : void {
$c = dict [ $s1 => 0, $s2 => 1 ];
}
// TEST-CHECK-BAL: define $root.col_from_array
// CHECK: define $root.col_from_array($this: *void, $s1: *HackString, $s2: *HackString) : *void {
// CHECK: local $c1: *void, $c2: *void, $c3: *void
// CHECK: #b0:
// CHECK: n0 = $builtins.hhbc_new_dict()
// CHECK: n1: *HackMixed = load &$s1
// CHECK: n2 = $builtins.hhbc_add_elem_c(n0, n1, n1)
// CHECK: n3: *HackMixed = load &$s2
// CHECK: n4 = $builtins.hhbc_add_elem_c(n2, n3, n3)
// CHECK: n5 = $builtins.hhbc_col_from_array_imm_set(n4)
// CHECK: store &$c1 <- n5: *HackMixed
// CHECK: n6 = $builtins.hhbc_new_dict()
// CHECK: n7 = $builtins.hhbc_add_elem_c(n6, n1, $builtins.hack_int(1))
// CHECK: n8 = $builtins.hhbc_add_elem_c(n7, n3, $builtins.hack_int(2))
// CHECK: n9 = $builtins.hhbc_col_from_array_imm_map(n8)
// CHECK: store &$c2 <- n9: *HackMixed
// CHECK: n10 = $builtins.hhbc_new_vec(n1, n3)
// CHECK: n11 = $builtins.hhbc_col_from_array_imm_vector(n10)
// CHECK: store &$c3 <- n11: *HackMixed
// CHECK: ret null
// CHECK: }
function col_from_array(string $s1, string $s2) : void {
$c1 = ImmSet { $s1, $s2 };
$c2 = ImmMap { $s1 => 1, $s2 => 2 };
$c3 = ImmVector { $s1, $s2 };
}
// TEST-CHECK-BAL: define $root.check_switch
// CHECK: define $root.check_switch($this: *void, $x: *HackInt) : *void {
// CHECK: #b0:
// CHECK: n0: *HackMixed = load &$x
// CHECK: n1 = $builtins.hhbc_cmp_eq(n0, $builtins.hack_int(5))
// CHECK: jmp b1, b2
// CHECK: #b1:
// CHECK: prune $builtins.hack_is_true(n1)
// CHECK: n2 = $builtins.hhbc_print($builtins.hack_string("5"))
// CHECK: jmp b3
// CHECK: #b2:
// CHECK: prune ! $builtins.hack_is_true(n1)
// CHECK: n3 = $builtins.hhbc_throw_non_exhaustive_switch()
// CHECK: jmp b3
// CHECK: #b3:
// CHECK: ret null
// CHECK: }
function check_switch(int $x): void {
switch ($x) {
case 5: echo "5"; break;
}
}
// TEST-CHECK-1: declare $builtins.hhbc_add_elem_c
// CHECK: declare $builtins.hhbc_add_elem_c(...): *HackMixed |
Hack | hhvm/hphp/hack/src/hackc/test/infer/instr_tc.hack | // Typecheck Helpers
function f(mixed... $_): void { }
function a(): int { return 0; }
function b(): int { return 0; } |
Hack | hhvm/hphp/hack/src/hackc/test/infer/locals.hack | // RUN: %hackc compile-infer %s | FileCheck %s
// TEST-CHECK-BAL: define $root.no_locals
// CHECK: define $root.no_locals($this: *void, $a: *HackInt) : *void {
// CHECK: #b0:
// CHECK: ret null
// CHECK: }
function no_locals(int $a) : void {
}
// TEST-CHECK-BAL: define $root.only_locals
// CHECK: define $root.only_locals($this: *void) : *void {
// CHECK: local $a: *void, $b: *void
// CHECK: #b0:
// CHECK: store &$a <- $builtins.hack_int(1): *HackMixed
// CHECK: store &$b <- $builtins.hack_int(2): *HackMixed
// CHECK: ret null
// CHECK: }
function only_locals() : void {
$a = 1;
$b = 2;
}
// TEST-CHECK-BAL: define $root.params_and_locals
// CHECK: define $root.params_and_locals($this: *void, $a: *HackInt) : *void {
// CHECK: local $b: *void, $c: *void
// CHECK: #b0:
// CHECK: store &$b <- $builtins.hack_int(1): *HackMixed
// CHECK: store &$c <- $builtins.hack_int(2): *HackMixed
// CHECK: ret null
// CHECK: }
function params_and_locals(int $a) : void {
$b = 1;
$c = 2;
}
// TEST-CHECK-BAL: define $root.locals_for_iter
// CHECK: define $root.locals_for_iter($this: *void, $d: *HackDict) : *void {
// CHECK: local $k: *void, $v: *void, iter0: *void
// CHECK: #b0:
// CHECK: n0 = $builtins.hack_new_dict($builtins.hack_string("kind"), $builtins.hack_int(19), $builtins.hack_string("generic_types"), $builtins.hhbc_new_vec($builtins.hack_new_dict($builtins.hack_string("kind"), $builtins.hack_int(1)), $builtins.hack_new_dict($builtins.hack_string("kind"), $builtins.hack_int(1))))
// CHECK: n1: *HackMixed = load &$d
// CHECK: n2 = $builtins.hhbc_verify_param_type_ts(n1, n0)
// CHECK: n3 = $builtins.hhbc_iter_init(&iter0, &$k, &$v, n1)
// CHECK: jmp b1, b6
// CHECK: #b1:
// CHECK: prune $builtins.hack_is_true(n3)
// CHECK: jmp b2
// CHECK: #b2:
// CHECK: n4: *HackMixed = load &iter0
// CHECK: n5 = $builtins.hhbc_iter_next(n4, &$k, &$v)
// CHECK: jmp b4, b5
// CHECK: .handlers b3
// CHECK: #b3(n6: *HackMixed):
// CHECK: n7: *HackMixed = load &iter0
// CHECK: n8 = $builtins.hhbc_iter_free(n7)
// CHECK: n9 = $builtins.hhbc_throw(n6)
// CHECK: unreachable
// CHECK: #b4:
// CHECK: prune $builtins.hack_is_true(n5)
// CHECK: jmp b7
// CHECK: #b5:
// CHECK: prune ! $builtins.hack_is_true(n5)
// CHECK: jmp b2
// CHECK: #b6:
// CHECK: prune ! $builtins.hack_is_true(n3)
// CHECK: jmp b7
// CHECK: #b7:
// CHECK: ret null
// CHECK: }
function locals_for_iter(dict<int, int> $d) : void {
foreach ($d as $k => $v) {
// do nothing so we make sure that $k and $v declare locals on their own.
}
} |
Hack | hhvm/hphp/hack/src/hackc/test/infer/member_op.hack | // RUN: %hackc compile-infer %s | FileCheck %s
class D {
public int $foo = 42;
/* HH_FIXME[4055] No initial value */
public static D $bar;
// TEST-CHECK-BAL: define D.mop_baseh_querym_pt
// CHECK: define D.mop_baseh_querym_pt($this: *D) : *HackInt {
// CHECK: #b0:
// CHECK: n0: *HackMixed = load &$this
// CHECK: n1 = $builtins.hhbc_check_this(n0)
// CHECK: n2: *HackMixed = load n0.?.foo
// CHECK: n3 = $builtins.hhbc_is_type_int(n2)
// CHECK: n4 = $builtins.hhbc_verify_type_pred(n2, n3)
// CHECK: ret n2
// CHECK: }
public function mop_baseh_querym_pt(): int {
return $this->foo;
}
// TEST-CHECK-BAL: define D.mop_basesc_querym_pt
// CHECK: define D.mop_basesc_querym_pt($this: *D) : *HackInt {
// CHECK: #b0:
// CHECK: n0 = $builtins.hhbc_class_get_c($builtins.hack_string("D"))
// CHECK: n1: *HackMixed = load n0.?.bar
// CHECK: n2: *HackMixed = load n1.?.foo
// CHECK: n3 = $builtins.hhbc_is_type_int(n2)
// CHECK: n4 = $builtins.hhbc_verify_type_pred(n2, n3)
// CHECK: ret n2
// CHECK: }
public function mop_basesc_querym_pt(): int {
return D::$bar->foo;
}
}
// TEST-CHECK-BAL: define $root.mop_basec_querym_pc
// CHECK: define $root.mop_basec_querym_pc($this: *void) : *HackInt {
// CHECK: #b0:
// CHECK: n0 = $root.ret_c(null)
// CHECK: n1: *HackMixed = load n0.?.foo
// CHECK: n2 = $builtins.hhbc_is_type_int(n1)
// CHECK: n3 = $builtins.hhbc_verify_type_pred(n1, n2)
// CHECK: ret n1
// CHECK: }
function mop_basec_querym_pc(): int {
return ret_c()->foo;
}
// TEST-CHECK-BAL: define $root.mop_basegc_querym_ec
// CHECK: define $root.mop_basegc_querym_ec($this: *void) : *HackInt {
// CHECK: #b0:
// CHECK: n0 = $root.ret_int(null)
// CHECK: n1 = $builtins.hack_get_superglobal($builtins.hack_string("_SERVER"))
// CHECK: n2 = $builtins.hack_array_get(n1, n0)
// CHECK: n3 = $builtins.hhbc_is_type_int(n2)
// CHECK: n4 = $builtins.hhbc_verify_type_pred(n2, n3)
// CHECK: ret n2
// CHECK: }
function mop_basegc_querym_ec(): int {
/* HH_FIXME[2050] Hack doesn't know about $_SERVER */
return $_SERVER[ret_int()];
}
// TEST-CHECK-BAL: define $root.mop_basel_querym_ei
// CHECK: define $root.mop_basel_querym_ei($this: *void, $a: *HackVec) : *HackInt {
// CHECK: #b0:
// CHECK: n0 = $builtins.hack_new_dict($builtins.hack_string("kind"), $builtins.hack_int(20), $builtins.hack_string("generic_types"), $builtins.hhbc_new_vec($builtins.hack_new_dict($builtins.hack_string("kind"), $builtins.hack_int(1))))
// CHECK: n1: *HackMixed = load &$a
// CHECK: n2 = $builtins.hhbc_verify_param_type_ts(n1, n0)
// CHECK: n3 = $builtins.hack_int(5)
// CHECK: n4 = $builtins.hack_array_get(n1, n3)
// CHECK: n5 = $builtins.hhbc_is_type_int(n4)
// CHECK: n6 = $builtins.hhbc_verify_type_pred(n4, n5)
// CHECK: ret n4
// CHECK: }
function mop_basel_querym_ei(vec<int> $a): int {
return $a[5];
}
// TEST-CHECK-BAL: define $root.mop_basel_querym_ei_isset
// CHECK: define $root.mop_basel_querym_ei_isset($this: *void, $a: *HackVec) : *HackBool {
// CHECK: #b0:
// CHECK: n0 = $builtins.hack_new_dict($builtins.hack_string("kind"), $builtins.hack_int(20), $builtins.hack_string("generic_types"), $builtins.hhbc_new_vec($builtins.hack_new_dict($builtins.hack_string("kind"), $builtins.hack_int(1))))
// CHECK: n1: *HackMixed = load &$a
// CHECK: n2 = $builtins.hhbc_verify_param_type_ts(n1, n0)
// CHECK: n3 = $builtins.hack_int(5)
// CHECK: n4 = $builtins.hack_array_get(n1, n3)
// CHECK: n5 = $builtins.hhbc_is_type_null(n4)
// CHECK: n6 = $builtins.hhbc_is_type_bool(n5)
// CHECK: n7 = $builtins.hhbc_verify_type_pred(n5, n6)
// CHECK: ret n5
// CHECK: }
function mop_basel_querym_ei_isset(vec<int> $a): bool {
return isset($a[5]);
}
// TEST-CHECK-BAL: define $root.mop_basel_querym_pc
// CHECK: define $root.mop_basel_querym_pc($this: *void, $a: *C) : *HackInt {
// CHECK: #b0:
// CHECK: n0 = $root.ret_str(null)
// CHECK: n1: *HackMixed = load &$a
// CHECK: n2 = $builtins.hack_prop_get(n1, n0, false)
// CHECK: n3 = $builtins.hhbc_is_type_int(n2)
// CHECK: n4 = $builtins.hhbc_verify_type_pred(n2, n3)
// CHECK: ret n2
// CHECK: }
function mop_basel_querym_pc(C $a): int {
return $a->{ret_str()};
}
// TEST-CHECK-BAL: define $root.mop_basel_querym_pl
// CHECK: define $root.mop_basel_querym_pl($this: *void, $a: *C) : *HackInt {
// CHECK: local $b: *void
// CHECK: #b0:
// CHECK: store &$b <- $builtins.hack_string("hello"): *HackMixed
// CHECK: n0: *HackMixed = load &$b
// CHECK: n1: *HackMixed = load &$a
// CHECK: n2 = $builtins.hack_prop_get(n1, n0, false)
// CHECK: n3 = $builtins.hhbc_is_type_int(n2)
// CHECK: n4 = $builtins.hhbc_verify_type_pred(n2, n3)
// CHECK: ret n2
// CHECK: }
function mop_basel_querym_pl(C $a): int {
$b = "hello";
/* HH_FIXME[2011] dynamic access */
return $a->{$b};
}
// TEST-CHECK-BAL: define $root.mop_basel_querym_el
// CHECK: define $root.mop_basel_querym_el($this: *void, $a: *HackVec, $b: *HackInt) : *HackInt {
// CHECK: #b0:
// CHECK: n0 = $builtins.hack_new_dict($builtins.hack_string("kind"), $builtins.hack_int(20), $builtins.hack_string("generic_types"), $builtins.hhbc_new_vec($builtins.hack_new_dict($builtins.hack_string("kind"), $builtins.hack_int(1))))
// CHECK: n1: *HackMixed = load &$a
// CHECK: n2 = $builtins.hhbc_verify_param_type_ts(n1, n0)
// CHECK: n3: *HackMixed = load &$b
// CHECK: n4 = $builtins.hack_array_get(n1, n3)
// CHECK: n5 = $builtins.hhbc_is_type_int(n4)
// CHECK: n6 = $builtins.hhbc_verify_type_pred(n4, n5)
// CHECK: ret n4
// CHECK: }
function mop_basel_querym_el(vec<int> $a, int $b): int {
return $a[$b];
}
// TEST-CHECK-BAL: define $root.mop_basel_querym_et
// CHECK: define $root.mop_basel_querym_et($this: *void, $a: *HackDict) : *HackInt {
// CHECK: #b0:
// CHECK: n0 = $builtins.hack_new_dict($builtins.hack_string("kind"), $builtins.hack_int(19), $builtins.hack_string("generic_types"), $builtins.hhbc_new_vec($builtins.hack_new_dict($builtins.hack_string("kind"), $builtins.hack_int(4)), $builtins.hack_new_dict($builtins.hack_string("kind"), $builtins.hack_int(1))))
// CHECK: n1: *HackMixed = load &$a
// CHECK: n2 = $builtins.hhbc_verify_param_type_ts(n1, n0)
// CHECK: n3 = $builtins.hack_string("hello")
// CHECK: n4 = $builtins.hack_array_get(n1, n3)
// CHECK: n5 = $builtins.hhbc_is_type_int(n4)
// CHECK: n6 = $builtins.hhbc_verify_type_pred(n4, n5)
// CHECK: ret n4
// CHECK: }
function mop_basel_querym_et(dict<string, int> $a): int {
return $a["hello"];
}
// TEST-CHECK-BAL: define $root.mop_basel_querym_pt
// CHECK: define $root.mop_basel_querym_pt($this: *void, $a: *C) : *HackInt {
// CHECK: #b0:
// CHECK: n0: *HackMixed = load &$a
// CHECK: n1: *HackMixed = load n0.?.foo
// CHECK: n2 = $builtins.hhbc_is_type_int(n1)
// CHECK: n3 = $builtins.hhbc_verify_type_pred(n1, n2)
// CHECK: ret n1
// CHECK: }
function mop_basel_querym_pt(C $a): int {
return $a->foo;
}
// TEST-CHECK-BAL: define $root.mop_basel_querym_qt
// CHECK: define $root.mop_basel_querym_qt($this: *void, $a: *C) : *HackInt {
// CHECK: #b0:
// CHECK: n0: *HackMixed = load &$a
// CHECK: n1 = $builtins.hack_prop_get(n0, "foo", true)
// CHECK: n2 = $builtins.hhbc_is_type_null(n1)
// CHECK: jmp b1, b2
// CHECK: #b1:
// CHECK: prune $builtins.hack_is_true(n2)
// CHECK: jmp b3($builtins.hack_bool(true))
// CHECK: #b2:
// CHECK: prune ! $builtins.hack_is_true(n2)
// CHECK: n3 = $builtins.hhbc_is_type_int(n1)
// CHECK: jmp b3(n3)
// CHECK: #b3(n4: *HackMixed):
// CHECK: n5 = $builtins.hhbc_verify_type_pred(n1, n4)
// CHECK: ret n1
// CHECK: }
function mop_basel_querym_qt(?C $a): ?int {
return $a?->foo;
}
// TEST-CHECK-BAL: define $root.mop_basel_setm_w
// CHECK: define $root.mop_basel_setm_w($this: *void, $a: *HackVec) : *void {
// CHECK: #b0:
// CHECK: n0 = $builtins.hack_new_dict($builtins.hack_string("kind"), $builtins.hack_int(20), $builtins.hack_string("generic_types"), $builtins.hhbc_new_vec($builtins.hack_new_dict($builtins.hack_string("kind"), $builtins.hack_int(1))))
// CHECK: n1: *HackMixed = load &$a
// CHECK: n2 = $builtins.hhbc_verify_param_type_ts(n1, n0)
// CHECK: n3 = $builtins.hack_int(5)
// CHECK: n4 = $builtins.hack_array_cow_append(n1, n3)
// CHECK: store &$a <- n4: *HackMixed
// CHECK: ret null
// CHECK: }
function mop_basel_setm_w(vec<int> $a): void {
$a[] = 5;
}
// TEST-CHECK-BAL: define $root.mop_basel_incdec_ei
// CHECK: define $root.mop_basel_incdec_ei($this: *void, $a: *HackVec) : *HackInt {
// CHECK: #b0:
// CHECK: n0 = $builtins.hack_new_dict($builtins.hack_string("kind"), $builtins.hack_int(20), $builtins.hack_string("generic_types"), $builtins.hhbc_new_vec($builtins.hack_new_dict($builtins.hack_string("kind"), $builtins.hack_int(1))))
// CHECK: n1: *HackMixed = load &$a
// CHECK: n2 = $builtins.hhbc_verify_param_type_ts(n1, n0)
// CHECK: n3 = $builtins.hack_int(3)
// CHECK: n4 = $builtins.hack_array_get(n1, n3)
// CHECK: n5 = $builtins.hhbc_add(n4, $builtins.hack_int(1))
// CHECK: n6 = $builtins.hack_array_cow_set(n1, n3, n5)
// CHECK: store &$a <- n6: *HackMixed
// CHECK: n7 = $builtins.hhbc_is_type_int(n4)
// CHECK: n8 = $builtins.hhbc_verify_type_pred(n4, n7)
// CHECK: ret n4
// CHECK: }
function mop_basel_incdec_ei(vec<int> $a): int {
/* HH_FIXME[1002] Assignment as expression */
return $a[3]++;
} |
Hack | hhvm/hphp/hack/src/hackc/test/infer/member_op_tc.hack | class C {
public int $foo = 42;
}
function ret_c(): C {
return new C();
}
function ret_vec(): vec<int> {
return vec[];
}
function ret_int(): int {
return 42;
}
function ret_str(): string {
return "hello";
} |
Hack | hhvm/hphp/hack/src/hackc/test/infer/memo_keep.hack | // RUN: %hackc compile-infer --keep-memo %s | FileCheck %s
class C {
// TEST-CHECK-1: define C$static.memometh_static$memoize_impl
// CHECK: define C$static.memometh_static$memoize_impl($this: *C$static, $a: *HackInt, $b: *HackInt) : *HackInt {
// TEST-CHECK-1: define C$static.memometh_lsb$memoize_impl
// CHECK: define C$static.memometh_lsb$memoize_impl($this: *C$static, $a: *HackInt, $b: *HackInt) : *HackInt {
// TEST-CHECK-BAL: define C.memometh_inst
// CHECK: define C.memometh_inst($this: *C, $a: *HackInt, $b: *HackInt) : *HackInt {
// CHECK: local memocache::_C_2ememometh__inst: *void, $0: *void, $1: *void
// CHECK: #b0:
// CHECK: n0: *HackMixed = load &$this
// CHECK: n1 = $builtins.hhbc_check_this(n0)
// CHECK: n2: *HackMixed = load &$a
// CHECK: n3 = $builtins.hhbc_get_memo_key_l(n2)
// CHECK: store &$0 <- n3: *HackMixed
// CHECK: n4: *HackMixed = load &$b
// CHECK: n5 = $builtins.hhbc_get_memo_key_l(n4)
// CHECK: store &$1 <- n5: *HackMixed
// CHECK: n6 = $builtins.hack_memo_isset(&memocache::_C_2ememometh__inst, n0, n3, n5)
// CHECK: jmp b1, b2
// CHECK: #b1:
// CHECK: prune $builtins.hack_is_true(n6)
// CHECK: n7 = $builtins.hack_memo_get(&memocache::_C_2ememometh__inst, n0, n3, n5)
// CHECK: ret n7
// CHECK: #b2:
// CHECK: prune ! $builtins.hack_is_true(n6)
// CHECK: n8: *C = load &$this
// CHECK: n9: *HackMixed = load &$a
// CHECK: n10: *HackMixed = load &$b
// CHECK: n11 = n8.?.memometh_inst$memoize_impl(n9, n10)
// CHECK: n12: *HackMixed = load &$0
// CHECK: n13: *HackMixed = load &$1
// CHECK: n14 = $builtins.hhbc_memo_set(&memocache::_C_2ememometh__inst, n8, n12, n13, n11)
// CHECK: ret n14
// CHECK: }
<<__Memoize>>
public function memometh_inst(int $a, int $b)[]: int {
return $a + $b;
}
// TEST-CHECK-BAL: define C$static.memometh_static
// CHECK: define C$static.memometh_static($this: *C$static, $a: *HackInt, $b: *HackInt) : *HackInt {
// CHECK: local memocache::_C$static_2ememometh__static: *void, $0: *void, $1: *void
// CHECK: #b0:
// CHECK: n0: *HackMixed = load &$a
// CHECK: n1 = $builtins.hhbc_get_memo_key_l(n0)
// CHECK: store &$0 <- n1: *HackMixed
// CHECK: n2: *HackMixed = load &$b
// CHECK: n3 = $builtins.hhbc_get_memo_key_l(n2)
// CHECK: store &$1 <- n3: *HackMixed
// CHECK: n4: *HackMixed = load &$this
// CHECK: n5 = $builtins.hack_memo_isset(&memocache::_C$static_2ememometh__static, n4, n1, n3)
// CHECK: jmp b1, b2
// CHECK: #b1:
// CHECK: prune $builtins.hack_is_true(n5)
// CHECK: n6 = $builtins.hack_memo_get(&memocache::_C$static_2ememometh__static, n4, n1, n3)
// CHECK: ret n6
// CHECK: #b2:
// CHECK: prune ! $builtins.hack_is_true(n5)
// CHECK: n7: *HackMixed = load &$a
// CHECK: n8: *HackMixed = load &$b
// CHECK: n9: *C$static = load &$this
// CHECK: n10 = C$static.memometh_static$memoize_impl(n9, n7, n8)
// CHECK: n11: *HackMixed = load &$0
// CHECK: n12: *HackMixed = load &$1
// CHECK: n13 = $builtins.hhbc_memo_set(&memocache::_C$static_2ememometh__static, n9, n11, n12, n10)
// CHECK: ret n13
// CHECK: }
<<__Memoize>>
public static function memometh_static(int $a, int $b)[]: int {
return $a + $b;
}
// TEST-CHECK-BAL: define C$static.memometh_lsb
// CHECK: define C$static.memometh_lsb($this: *C$static, $a: *HackInt, $b: *HackInt) : *HackInt {
// CHECK: local memocache::_C$static_2ememometh__lsb: *void, $0: *void, $1: *void
// CHECK: #b0:
// CHECK: n0: *HackMixed = load &$a
// CHECK: n1 = $builtins.hhbc_get_memo_key_l(n0)
// CHECK: store &$0 <- n1: *HackMixed
// CHECK: n2: *HackMixed = load &$b
// CHECK: n3 = $builtins.hhbc_get_memo_key_l(n2)
// CHECK: store &$1 <- n3: *HackMixed
// CHECK: n4: *HackMixed = load &$this
// CHECK: n5 = $builtins.hack_memo_isset(&memocache::_C$static_2ememometh__lsb, n4, n1, n3)
// CHECK: jmp b1, b2
// CHECK: #b1:
// CHECK: prune $builtins.hack_is_true(n5)
// CHECK: n6 = $builtins.hack_memo_get(&memocache::_C$static_2ememometh__lsb, n4, n1, n3)
// CHECK: ret n6
// CHECK: #b2:
// CHECK: prune ! $builtins.hack_is_true(n5)
// CHECK: n7: *HackMixed = load &$a
// CHECK: n8: *HackMixed = load &$b
// CHECK: n9: *C$static = load &$this
// CHECK: n10 = C$static.memometh_lsb$memoize_impl(n9, n7, n8)
// CHECK: n11: *HackMixed = load &$0
// CHECK: n12: *HackMixed = load &$1
// CHECK: n13 = $builtins.hhbc_memo_set(&memocache::_C$static_2ememometh__lsb, n9, n11, n12, n10)
// CHECK: ret n13
// CHECK: }
<<__MemoizeLSB>>
public static function memometh_lsb(int $a, int $b)[]: int {
return $a + $b;
}
}
// TEST-CHECK-1: define $root.memofunc$memoize_impl
// CHECK: define $root.memofunc$memoize_impl($this: *void, $a: *HackInt, $b: *HackInt) : *HackInt {
// TEST-CHECK-BAL: define $root.memofunc
// CHECK: define $root.memofunc($this: *void, $a: *HackInt, $b: *HackInt) : *HackInt {
// CHECK: local memocache::_$root_2ememofunc: *void, $0: *void, $1: *void
// CHECK: #b0:
// CHECK: n0: *HackMixed = load &$a
// CHECK: n1 = $builtins.hhbc_get_memo_key_l(n0)
// CHECK: store &$0 <- n1: *HackMixed
// CHECK: n2: *HackMixed = load &$b
// CHECK: n3 = $builtins.hhbc_get_memo_key_l(n2)
// CHECK: store &$1 <- n3: *HackMixed
// CHECK: n4 = $builtins.hack_memo_isset(&memocache::_$root_2ememofunc, n1, n3)
// CHECK: jmp b1, b2
// CHECK: #b1:
// CHECK: prune $builtins.hack_is_true(n4)
// CHECK: n5 = $builtins.hack_memo_get(&memocache::_$root_2ememofunc, n1, n3)
// CHECK: ret n5
// CHECK: #b2:
// CHECK: prune ! $builtins.hack_is_true(n4)
// CHECK: n6: *HackMixed = load &$a
// CHECK: n7: *HackMixed = load &$b
// CHECK: n8 = $root.memofunc$memoize_impl(null, n6, n7)
// CHECK: n9: *HackMixed = load &$0
// CHECK: n10: *HackMixed = load &$1
// CHECK: n11 = $builtins.hhbc_memo_set(&memocache::_$root_2ememofunc, n9, n10, n8)
// CHECK: ret n11
// CHECK: }
<<__Memoize>>
function memofunc(int $a, int $b)[]: int {
return $a + $b;
}
// TEST-CHECK-1: define .async $root.memo_async_func$memoize_impl
// CHECK: define .async $root.memo_async_func$memoize_impl($this: *void, $a: *HackInt, $b: *HackInt) : *HackInt {
// TEST-CHECK-BAL: define .async $root.memo_async_func
// CHECK: define .async $root.memo_async_func($this: *void, $a: *HackInt, $b: *HackInt) : *HackInt {
// CHECK: local memocache::_$root_2ememo__async__func: *void, $0: *void, $1: *void
// CHECK: #b0:
// CHECK: n0: *HackMixed = load &$a
// CHECK: n1 = $builtins.hhbc_get_memo_key_l(n0)
// CHECK: store &$0 <- n1: *HackMixed
// CHECK: n2: *HackMixed = load &$b
// CHECK: n3 = $builtins.hhbc_get_memo_key_l(n2)
// CHECK: store &$1 <- n3: *HackMixed
// CHECK: n4 = $builtins.hack_memo_isset(&memocache::_$root_2ememo__async__func, n1, n3)
// CHECK: jmp b1, b2
// CHECK: #b1:
// CHECK: prune $builtins.hack_is_true(n4)
// CHECK: n5 = $builtins.hack_memo_get(&memocache::_$root_2ememo__async__func, n1, n3)
// CHECK: ret n5
// CHECK: #b2:
// CHECK: prune ! $builtins.hack_is_true(n4)
// CHECK: n6: *HackMixed = load &$a
// CHECK: n7: *HackMixed = load &$b
// CHECK: n8 = $root.memo_async_func$memoize_impl(null, n6, n7)
// CHECK: n9 = $builtins.hhbc_await(n8)
// CHECK: n10: *HackMixed = load &$0
// CHECK: n11: *HackMixed = load &$1
// CHECK: n12 = $builtins.hhbc_memo_set(&memocache::_$root_2ememo__async__func, n10, n11, n9)
// CHECK: ret n12
// CHECK: }
<<__Memoize>>
async function memo_async_func(int $a, int $b)[]: Awaitable<int> {
return $a + $b;
} |
Hack | hhvm/hphp/hack/src/hackc/test/infer/memo_remove.hack | // RUN: %hackc compile-infer %s | FileCheck %s
class C {
// TEST-CHECK-BAL: define C.memometh_inst
// CHECK: define C.memometh_inst($this: *C, $a: *HackInt, $b: *HackInt) : *HackInt {
// CHECK: #b0:
// CHECK: n0: *HackMixed = load &$b
// CHECK: n1: *HackMixed = load &$a
// CHECK: n2 = $builtins.hhbc_add(n1, n0)
// CHECK: n3 = $builtins.hhbc_is_type_int(n2)
// CHECK: n4 = $builtins.hhbc_verify_type_pred(n2, n3)
// CHECK: ret n2
// CHECK: }
<<__Memoize>>
public function memometh_inst(int $a, int $b)[]: int {
return $a + $b;
}
// TEST-CHECK-BAL: define C$static.memometh_static
// CHECK: define C$static.memometh_static($this: *C$static, $a: *HackInt, $b: *HackInt) : *HackInt {
// CHECK: #b0:
// CHECK: n0: *HackMixed = load &$b
// CHECK: n1: *HackMixed = load &$a
// CHECK: n2 = $builtins.hhbc_add(n1, n0)
// CHECK: n3 = $builtins.hhbc_is_type_int(n2)
// CHECK: n4 = $builtins.hhbc_verify_type_pred(n2, n3)
// CHECK: ret n2
// CHECK: }
<<__Memoize>>
public static function memometh_static(int $a, int $b)[]: int {
return $a + $b;
}
// TEST-CHECK-BAL: define C$static.memometh_lsb
// CHECK: define C$static.memometh_lsb($this: *C$static, $a: *HackInt, $b: *HackInt) : *HackInt {
// CHECK: #b0:
// CHECK: n0: *HackMixed = load &$b
// CHECK: n1: *HackMixed = load &$a
// CHECK: n2 = $builtins.hhbc_add(n1, n0)
// CHECK: n3 = $builtins.hhbc_is_type_int(n2)
// CHECK: n4 = $builtins.hhbc_verify_type_pred(n2, n3)
// CHECK: ret n2
// CHECK: }
<<__MemoizeLSB>>
public static function memometh_lsb(int $a, int $b)[]: int {
return $a + $b;
}
}
// TEST-CHECK-BAL: define $root.memofunc
// CHECK: define $root.memofunc($this: *void, $a: *HackInt, $b: *HackInt) : *HackInt {
// CHECK: #b0:
// CHECK: n0: *HackMixed = load &$b
// CHECK: n1: *HackMixed = load &$a
// CHECK: n2 = $builtins.hhbc_add(n1, n0)
// CHECK: n3 = $builtins.hhbc_is_type_int(n2)
// CHECK: n4 = $builtins.hhbc_verify_type_pred(n2, n3)
// CHECK: ret n2
// CHECK: }
<<__Memoize>>
function memofunc(int $a, int $b)[]: int {
return $a + $b;
}
// TEST-CHECK-BAL: define .async $root.memo_async_func
// CHECK: define .async $root.memo_async_func($this: *void, $a: *HackInt, $b: *HackInt) : *HackInt {
// CHECK: #b0:
// CHECK: n0: *HackMixed = load &$b
// CHECK: n1: *HackMixed = load &$a
// CHECK: n2 = $builtins.hhbc_add(n1, n0)
// CHECK: n3 = $builtins.hhbc_is_type_int(n2)
// CHECK: n4 = $builtins.hhbc_verify_type_pred(n2, n3)
// CHECK: ret n2
// CHECK: }
<<__Memoize>>
async function memo_async_func(int $a, int $b)[]: Awaitable<int> {
return $a + $b;
} |
Hack | hhvm/hphp/hack/src/hackc/test/infer/null_check.hack | // RUN: %hackc compile-infer %s | FileCheck %s
namespace NullCheck;
class A {
public function __construct(public string $prop1) {}
}
// TEST-CHECK-BAL: define $root.NullCheck::f1_nonnull
// CHECK: define $root.NullCheck::f1_nonnull($this: *void, $arg: *NullCheck::A) : *HackString {
// CHECK: #b0:
// CHECK: n0: *HackMixed = load &$arg
// CHECK: n1 = $builtins.hhbc_is_type_null(n0)
// CHECK: n2 = $builtins.hhbc_not(n1)
// CHECK: jmp b1, b2
// CHECK: #b1:
// CHECK: prune ! $builtins.hack_is_true(n2)
// CHECK: n3 = $builtins.hhbc_is_type_str($builtins.hack_string("default"))
// CHECK: n4 = $builtins.hhbc_verify_type_pred($builtins.hack_string("default"), n3)
// CHECK: ret $builtins.hack_string("default")
// CHECK: #b2:
// CHECK: prune $builtins.hack_is_true(n2)
// CHECK: n5: *HackMixed = load &$arg
// CHECK: n6: *HackMixed = load n5.?.prop1
// CHECK: n7 = $builtins.hhbc_is_type_str(n6)
// CHECK: n8 = $builtins.hhbc_verify_type_pred(n6, n7)
// CHECK: ret n6
// CHECK: }
function f1_nonnull(?A $arg): string {
if ($arg is nonnull) {
return $arg->prop1;
} else {
return "default";
}
}
// TEST-CHECK-BAL: define $root.NullCheck::f2_null
// CHECK: define $root.NullCheck::f2_null($this: *void, $arg: *NullCheck::A) : *HackString {
// CHECK: #b0:
// CHECK: n0: *HackMixed = load &$arg
// CHECK: n1 = $builtins.hhbc_is_type_null(n0)
// CHECK: jmp b1, b2
// CHECK: #b1:
// CHECK: prune ! $builtins.hack_is_true(n1)
// CHECK: n2: *HackMixed = load &$arg
// CHECK: n3: *HackMixed = load n2.?.prop1
// CHECK: n4 = $builtins.hhbc_is_type_str(n3)
// CHECK: n5 = $builtins.hhbc_verify_type_pred(n3, n4)
// CHECK: ret n3
// CHECK: #b2:
// CHECK: prune $builtins.hack_is_true(n1)
// CHECK: n6 = $builtins.hhbc_is_type_str($builtins.hack_string("default"))
// CHECK: n7 = $builtins.hhbc_verify_type_pred($builtins.hack_string("default"), n6)
// CHECK: ret $builtins.hack_string("default")
// CHECK: }
function f2_null(?A $arg): string {
if ($arg is null) {
return "default";
} else {
return $arg->prop1;
}
}
// TEST-CHECK-BAL: define $root.NullCheck::f3_as_nonnull
// CHECK: define $root.NullCheck::f3_as_nonnull($this: *void, $arg: *NullCheck::A) : *HackString {
// CHECK: local $0: *void, $1: *void
// CHECK: #b0:
// CHECK: n0 = $builtins.hack_new_dict($builtins.hack_string("kind"), $builtins.hack_int(23))
// CHECK: n1: *HackMixed = load &$arg
// CHECK: store &$0 <- n1: *HackMixed
// CHECK: store &$1 <- n0: *HackMixed
// CHECK: n2 = $builtins.hhbc_is_type_null(n1)
// CHECK: n3 = $builtins.hhbc_not(n2)
// CHECK: jmp b1, b2
// CHECK: #b1:
// CHECK: prune $builtins.hack_is_true(n3)
// CHECK: n4: *HackMixed = load &$0
// CHECK: store &$1 <- null: *HackMixed
// CHECK: n5: *HackMixed = load n4.?.prop1
// CHECK: n6 = $builtins.hhbc_is_type_str(n5)
// CHECK: n7 = $builtins.hhbc_verify_type_pred(n5, n6)
// CHECK: ret n5
// CHECK: #b2:
// CHECK: prune ! $builtins.hack_is_true(n3)
// CHECK: n8: *HackMixed = load &$0
// CHECK: n9: *HackMixed = load &$1
// CHECK: n10 = $builtins.hhbc_throw_as_type_struct_exception(n8, n9)
// CHECK: unreachable
// CHECK: }
function f3_as_nonnull(?A $arg): string {
return ($arg as nonnull)->prop1;
} |
Hack | hhvm/hphp/hack/src/hackc/test/infer/params.hack | // RUN: %hackc compile-infer --keep-going %s | FileCheck %s
class Internal {}
class InternalGeneric<T> {}
// TEST-CHECK-BAL: define $root.internalClassParam
// CHECK: define $root.internalClassParam($this: *void, $a: *HackInt, $b: *Internal) : *Internal {
// CHECK: local $0: *void, $1: *void, $2: *void
// CHECK: #b0:
// CHECK: jmp b1
// CHECK: #b1:
// CHECK: n0 = __sil_lazy_class_initialize(<Internal>)
// CHECK: store &$0 <- n0: *HackMixed
// CHECK: n1 = __sil_allocate(<Internal>)
// CHECK: n2 = Internal._86pinit(n1)
// CHECK: store &$2 <- n1: *HackMixed
// CHECK: jmp b2
// CHECK: .handlers b4
// CHECK: #b2:
// CHECK: jmp b3
// CHECK: #b3:
// CHECK: n3: *HackMixed = load &$2
// CHECK: jmp b5
// CHECK: .handlers b4
// CHECK: #b4(n4: *HackMixed):
// CHECK: store &$0 <- null: *HackMixed
// CHECK: store &$1 <- null: *HackMixed
// CHECK: store &$2 <- null: *HackMixed
// CHECK: n5 = $builtins.hhbc_throw(n4)
// CHECK: unreachable
// CHECK: #b5:
// CHECK: store &$0 <- null: *HackMixed
// CHECK: store &$1 <- null: *HackMixed
// CHECK: store &$2 <- null: *HackMixed
// CHECK: n6 = n3.?.__construct()
// CHECK: n7 = $builtins.hhbc_lock_obj(n3)
// CHECK: n8 = $builtins.hack_bool(__sil_instanceof(n3, <Internal>))
// CHECK: n9 = $builtins.hhbc_verify_type_pred(n3, n8)
// CHECK: ret n3
// CHECK: }
function internalClassParam(int $a, Internal $b) : Internal {
return new Internal();
}
// TEST-CHECK-BAL: define $root.externalClassParam
// CHECK: define $root.externalClassParam($this: *void, $a: *HackBool, $b: *External) : *External {
// CHECK: local $0: *void, $1: *void, $2: *void
// CHECK: #b0:
// CHECK: jmp b1
// CHECK: #b1:
// CHECK: n0 = __sil_lazy_class_initialize(<External>)
// CHECK: store &$0 <- n0: *HackMixed
// CHECK: n1 = __sil_allocate(<External>)
// CHECK: n2 = External._86pinit(n1)
// CHECK: store &$2 <- n1: *HackMixed
// CHECK: jmp b2
// CHECK: .handlers b4
// CHECK: #b2:
// CHECK: jmp b3
// CHECK: #b3:
// CHECK: n3: *HackMixed = load &$2
// CHECK: jmp b5
// CHECK: .handlers b4
// CHECK: #b4(n4: *HackMixed):
// CHECK: store &$0 <- null: *HackMixed
// CHECK: store &$1 <- null: *HackMixed
// CHECK: store &$2 <- null: *HackMixed
// CHECK: n5 = $builtins.hhbc_throw(n4)
// CHECK: unreachable
// CHECK: #b5:
// CHECK: store &$0 <- null: *HackMixed
// CHECK: store &$1 <- null: *HackMixed
// CHECK: store &$2 <- null: *HackMixed
// CHECK: n6 = n3.?.__construct()
// CHECK: n7 = $builtins.hhbc_lock_obj(n3)
// CHECK: n8 = $builtins.hack_bool(__sil_instanceof(n3, <External>))
// CHECK: n9 = $builtins.hhbc_verify_type_pred(n3, n8)
// CHECK: ret n3
// CHECK: }
function externalClassParam(bool $a, External $b): External {
return new External();
}
// TEST-CHECK-BAL: define .async $root.genericParams
// CHECK: define .async $root.genericParams($this: *void, $a: *HackString, $b: *InternalGeneric) : *HackInt {
// CHECK: #b0:
// CHECK: n0 = $builtins.hack_new_dict($builtins.hack_string("kind"), $builtins.hack_int(101), $builtins.hack_string("classname"), $builtins.hack_string("InternalGeneric"), $builtins.hack_string("generic_types"), $builtins.hhbc_new_vec($builtins.hack_new_dict($builtins.hack_string("kind"), $builtins.hack_int(4))))
// CHECK: n1: *HackMixed = load &$b
// CHECK: n2 = $builtins.hhbc_verify_param_type_ts(n1, n0)
// CHECK: n3 = $builtins.hhbc_is_type_int($builtins.hack_int(42))
// CHECK: n4 = $builtins.hhbc_verify_type_pred($builtins.hack_int(42), n3)
// CHECK: ret $builtins.hack_int(42)
// CHECK: }
async function genericParams(string $a, InternalGeneric<string> $b): Awaitable<int> {
return 42;
} |
Hack | hhvm/hphp/hack/src/hackc/test/infer/retm.hack | // RUN: %hackc compile-infer %s | FileCheck %s
// Random instruction tests.
// TEST-CHECK-BAL: define $root.multi_ret
// CHECK: define $root.multi_ret($this: *void, $a: *HackInt) : *HackInt {
// CHECK: #b0:
// CHECK: store &$a <- $builtins.hack_int(7): *HackMixed
// CHECK: n0 = $builtins.hhbc_is_type_int($builtins.hack_int(5))
// CHECK: n1 = $builtins.hhbc_verify_type_pred($builtins.hack_int(5), n0)
// CHECK: n2: *HackMixed = load &$a
// CHECK: n3 = $builtins.hhbc_is_type_int(n2)
// CHECK: n4 = $builtins.hhbc_verify_type_pred(n2, n3)
// CHECK: n5 = $builtins.hhbc_new_vec($builtins.hack_int(5), n2)
// CHECK: ret n5
// CHECK: }
function multi_ret(inout int $a): int {
$a = 7;
return 5;
} |
Hack | hhvm/hphp/hack/src/hackc/test/infer/sswitch.hack | // RUN: %hackc compile-infer %s | FileCheck %s
// TEST-CHECK-BAL: define C$static._86cinit
// CHECK: define C$static._86cinit($this: *C$static, $constName: *HackMixed) : *HackMixed {
// CHECK: #b0:
// CHECK: n0: *HackMixed = load &$constName
// CHECK: n1 = $builtins.hhbc_cmp_same($builtins.hack_string("CONST_REQUIRES_CINIT"), n0)
// CHECK: jmp b1, b2
// CHECK: #b1:
// CHECK: prune $builtins.hack_is_true(n1)
// CHECK: n2 = __sil_lazy_class_initialize(<D>)
// CHECK: n3 = $builtins.hack_field_get(n2, "STRING")
// CHECK: n4 = $builtins.hack_new_dict($builtins.hack_string("var"), $builtins.hack_string("id"), $builtins.hack_string("type"), n3)
// CHECK: ret n4
// CHECK: #b2:
// CHECK: prune ! $builtins.hack_is_true(n1)
// CHECK: n5: *HackMixed = load &$constName
// CHECK: n6 = $builtins.hhbc_concat($builtins.hack_string("Could not find initializer for "), n5, $builtins.hack_string(" in 86cinit"))
// CHECK: n7 = $builtins.hhbc_fatal(n6)
// CHECK: unreachable
// CHECK: }
class C {
// Because this constant has a foreign reference in it (`D::STRING`), it
// forces the class to get an '86cinit' method to initialize it.
const mixed CONST_REQUIRES_CINIT = shape(
'var' => 'id',
'type' => D::STRING,
);
} |
Hack | hhvm/hphp/hack/src/hackc/test/infer/try_catch.hack | // RUN: %hackc compile-infer %s | FileCheck %s
// TEST-CHECK-BAL: define $root.main
// CHECK: define $root.main($this: *void) : *void {
// CHECK: local $e: *void, $x: *void
// CHECK: #b0:
// CHECK: n0 = $root.a(null, $builtins.hack_int(0))
// CHECK: jmp b1
// CHECK: #b1:
// CHECK: n1 = $root.a(null, $builtins.hack_int(1))
// CHECK: store &$x <- n1: *HackMixed
// CHECK: jmp b5
// CHECK: .handlers b2
// CHECK: #b2(n2: *HackMixed):
// CHECK: n3 = $builtins.hack_bool(__sil_instanceof(n2, <Exception>))
// CHECK: jmp b3, b4
// CHECK: #b3:
// CHECK: prune ! $builtins.hack_is_true(n3)
// CHECK: n4 = $builtins.hhbc_throw(n2)
// CHECK: unreachable
// CHECK: #b4:
// CHECK: prune $builtins.hack_is_true(n3)
// CHECK: store &$e <- n2: *HackMixed
// CHECK: n5 = $root.a(null, $builtins.hack_int(2))
// CHECK: jmp b5
// CHECK: #b5:
// CHECK: n6 = $root.a(null, $builtins.hack_int(3))
// CHECK: ret null
// CHECK: }
function main(): void {
a(0);
try {
$x = a(1);
} catch (Exception $e) {
a(2);
}
a(3);
}
function a(int $x): int { return $x + 1; } |
Hack | hhvm/hphp/hack/src/hackc/test/infer/type_const.hack | // RUN: %hackc compile-infer %s | FileCheck %s
// TEST-CHECK-BAL: type C$static
// CHECK: type C$static = .kind="class" .static {
// CHECK: }
abstract class C {
<<__Enforceable>>
abstract const type TMyShape;
// TEST-CHECK-BAL: define C$static.check2
// CHECK: define C$static.check2($this: *C$static, $a: *HackMixed) : *HackBool {
// CHECK: #b0:
// CHECK: n0 = $builtins.hack_new_dict($builtins.hack_string("kind"), $builtins.hack_int(102), $builtins.hack_string("root_name"), $builtins.hack_string("self"), $builtins.hack_string("access_list"), $builtins.hhbc_new_vec($builtins.hack_string("TMyShape")))
// CHECK: n1: *HackMixed = load &$a
// CHECK: n2 = $builtins.hhbc_is_type_struct_c(n1, n0, $builtins.hack_int(1))
// CHECK: n3 = $builtins.hhbc_is_type_bool(n2)
// CHECK: n4 = $builtins.hhbc_verify_type_pred(n2, n3)
// CHECK: ret n2
// CHECK: }
public static function check2(mixed $a): bool {
return $a is self::TMyShape;
}
}
// TEST-CHECK-BAL: type D$static
// CHECK: type D$static extends C$static = .kind="class" .static {
// CHECK: }
class D extends C {
const type TMyShape = shape(
?'a' => ?string,
?'b' => ?int,
);
// TEST-CHECK-BAL: define D$static.check3
// CHECK: define D$static.check3($this: *D$static, $shape: *HackMixed) : *void {
// CHECK: #b0:
// CHECK: ret null
// CHECK: }
public static function check3(self::TMyShape $shape)[]: void {
}
}
// TEST-CHECK-BAL: define $root.check1
// CHECK: define $root.check1($this: *void, $a: *HackMixed) : *HackBool {
// CHECK: #b0:
// CHECK: n0 = $builtins.hack_new_dict($builtins.hack_string("kind"), $builtins.hack_int(102), $builtins.hack_string("root_name"), $builtins.hack_string("D"), $builtins.hack_string("access_list"), $builtins.hhbc_new_vec($builtins.hack_string("TMyShape")))
// CHECK: n1: *HackMixed = load &$a
// CHECK: n2 = $builtins.hhbc_is_type_struct_c(n1, n0, $builtins.hack_int(1))
// CHECK: n3 = $builtins.hhbc_is_type_bool(n2)
// CHECK: n4 = $builtins.hhbc_verify_type_pred(n2, n3)
// CHECK: ret n2
// CHECK: }
function check1(mixed $a): bool {
return $a is D::TMyShape;
}
// TEST-CHECK-BAL: define $root.check2
// CHECK: define $root.check2($this: *void) : *HackMixed {
// CHECK: local $0: *void, $1: *void
// CHECK: #b0:
// CHECK: n0 = $builtins.hack_new_dict()
// CHECK: n1 = $builtins.hack_new_dict($builtins.hack_string("kind"), $builtins.hack_int(102), $builtins.hack_string("root_name"), $builtins.hack_string("D"), $builtins.hack_string("access_list"), $builtins.hhbc_new_vec($builtins.hack_string("TMyShape")))
// CHECK: store &$0 <- n0: *HackMixed
// CHECK: store &$1 <- n1: *HackMixed
// CHECK: n2 = $builtins.hhbc_is_type_struct_c(n0, n1, $builtins.hack_int(1))
// CHECK: jmp b1, b2
// CHECK: #b1:
// CHECK: prune $builtins.hack_is_true(n2)
// CHECK: n3: *HackMixed = load &$0
// CHECK: store &$1 <- null: *HackMixed
// CHECK: n4 = $builtins.hhbc_verify_type_pred(n3, $builtins.hack_bool(true))
// CHECK: ret n3
// CHECK: #b2:
// CHECK: prune ! $builtins.hack_is_true(n2)
// CHECK: n5: *HackMixed = load &$0
// CHECK: n6: *HackMixed = load &$1
// CHECK: n7 = $builtins.hhbc_throw_as_type_struct_exception(n5, n6)
// CHECK: unreachable
// CHECK: }
function check2(): D::TMyShape {
return dict[] as D::TMyShape;
}
// TEST-CHECK-BAL: define $root.main
// CHECK: define $root.main($this: *void) : *void {
// CHECK: #b0:
// CHECK: n0 = $root.check1(null, $builtins.hack_int(5))
// CHECK: n1 = __sil_lazy_class_initialize(<D>)
// CHECK: n2 = D$static.check2(n1, $builtins.hack_int(5))
// CHECK: ret null
// CHECK: }
<<__EntryPoint>>
function main(): void {
check1(5);
D::check2(5);
} |
Python | hhvm/hphp/hack/src/hackc/test/infer/update.py | import argparse
import json
import os
import subprocess
import sys
### Script to rebuild test expect data. Tests are annotated with 'TEST-CHECK*'
### to describe how to update the CHECK data.
###
### Annotations look like:
### // TEST-CHECK*: phrase
###
### The phrase is matched based on the type of check and then an action is
### performed to update the CHECK statements.
###
### TEST-CHECK-1: Look for the phrase at the start of a line and match a single
### CHECK with that line.
###
### TEST-CHECK-1*: Look for the phrase anywhere in a line and match a single
### CHECK with that line.
###
### TEST-CHECK-BAL: Look for the phrase at the start of a line and continue the
### CHECK until the parentheses, brackets, and braces are
### balanced.
###
### TEST-CHECK-IGN: Ignore the next sequence of CHECK lines. They must be
### manually updated.
###
ROOT = "."
HACKC = "hackc"
# From the current "// TEST-CHECK..." remove "// CHECK..." lines.
def strip_existing_check(input, idx):
old = []
while idx < len(input) and (
input[idx].strip().startswith("// CHECK:") or input[idx].startswith("// CHECK-")
):
old.append(input[idx])
del input[idx]
return old
# Find input that matches the expected TEST-CHECK
def fetch_check(filename, line, check, test, old):
indent = test.find("//")
if indent == -1:
indent = 0
indent = " " * indent
test = test.strip()
expect, what = match_and_strip(test, "TEST-CHECK-IGN")
if what:
# A section of "CHECK" which is left alone.
return old, None
expect, what = match_and_strip(test, "TEST-CHECK-1", "TEST-CHECK-1*")
if what:
# A single line. If the asterisk is present then matches anywhere on the line.
any = what == "TEST-CHECK-1*"
where = find_line_with(filename, line, check, expect, any)
output = build_output(indent, check, where, 1)
return output, where
expect, what = match_and_strip(test, "TEST-CHECK-BAL")
if what:
# Balanced braces
where = find_line_with(filename, line, check, expect, 0)
balance = count_balance(check[where])
lines = 1
while balance != 0:
if where + lines >= len(check):
bail(
filename,
line,
f"Unbalanced tokens starting at '{expect}' on line '{where}'",
)
balance += count_balance(check[where + lines])
lines += 1
output = build_output(indent, check, where, lines)
return output, where
bail(filename, line, f"Unknown test type: {test}")
# Look for any of the checks in the test line. Returns `expect, what` or `None,
# None`.
def match_and_strip(test, *checks):
for check in checks:
if test.startswith(f"// {check}:"):
expect = unquote(test[len(check) + 4 :].strip())
return expect, check
return None, None
# Handle indenting and prepending `CHECK`
def build_output(indent, check, where, lines):
output = []
for line in check[where : where + lines]:
if line.startswith("// .line ") or line.startswith("// .file"):
continue
output.append(f"{indent}// CHECK: {line}")
return output
def unquote(input):
if input.startswith('"') and input.endswith('"'):
return input[1:-1]
else:
return input
def count_balance(input):
count = 0
for c in input:
if c == "(" or c == "{" or c == "[":
count += 1
elif c == ")" or c == "}" or c == "]":
count -= 1
return count
def is_identifier(c):
return c.isidentifier() or c == "$" or c == ":"
def is_match(inp, expect, any_match):
# If inp is smaller then they can't match.
if len(inp) < len(expect):
return False
# If they're exactly equal they must match.
if inp == expect:
return True
if any_match:
# For any_match mode then just look for any match.
return expect in inp
# If inp doesn't start with expect then they can't match.
if not inp.startswith(expect):
return False
# If expect ends with an identifier char then we expect that the next char
# in inp must NOT be an identifier char.
if is_identifier(expect[-1]) and is_identifier(inp[len(expect)]):
return False
return True
def find_line_with(filename, line, check, expect, any_match):
idx = 0
while idx < len(check):
inp = check[idx]
if is_match(inp, expect, any_match):
return idx
idx += 1
bail(filename, line, f"Expected string '{expect}' not found")
def update_test(filename, input, idx, check):
old = strip_existing_check(input, idx + 1)
check, start = fetch_check(filename, idx, check, input[idx], old)
input[idx + 1 : idx + 1] = check
return 1 + len(check), start
def remove_prefix(text, prefix):
return text[text.startswith(prefix) and len(prefix) :]
def remove_suffix(text, suffix):
return text[text.endswith(suffix) and 0 : (-len(suffix))]
# Extract hackc flags from the RUN directive in a test file
def extract_flags(filename, input):
cmd = None
for line in input:
if line.startswith("// RUN:"):
cmd = remove_prefix(line, "// RUN: %hackc")
cmd = remove_suffix(cmd, "%s | FileCheck %s").strip()
break
if not cmd:
bail(filename, 0, "RUN directive not found")
return cmd.split()
def update_file(filename):
print(f"Processing {filename}")
with open(filename, "r") as f:
file = f.read().split("\n")
flags = extract_flags(filename, file)
print(f" extracted flags: {flags}")
stdout = subprocess.check_output(
(
HACKC,
*flags,
filename,
)
).decode("utf-8", "ignore")
check = stdout.split("\n")
last_seen = 0
idx = 0
while idx < len(file):
inp = file[idx].strip()
if inp.startswith("// TEST-CHECK:") or inp.startswith("// TEST-CHECK-"):
count, start = update_test(filename, file, idx, check)
elif inp.startswith("// CHECK:") or inp.startswith("// CHECK-"):
warn(filename, idx, "Naked CHECK found")
else:
count, start = 1, last_seen
if start is not None:
if start < last_seen:
bail(
filename,
idx,
f"test was found but is out of order (found at {start} but already processed {last_seen})",
)
last_seen = start
idx += count
with open(filename, "w") as f:
f.write("\n".join(file))
def run(*args):
return subprocess.check_output(*args).decode("utf-8", "ignore").strip()
# Query buck for the location of hackc.
def compute_hackc(use_cargo):
if use_cargo:
root = run("hg root".split())
stdout = run(
(
root + "/fbcode/hphp/hack/scripts/facebook/cargo.sh",
"build",
"-p",
"hackc",
"--message-format=json",
)
)
for msg in stdout.split("\n"):
# print(repr(msg))
output = json.loads(msg)
if output["reason"] == "compiler-artifact" and output[
"package_id"
].startswith("hackc "):
return output["executable"]
raise Exception("hackc not found")
else:
stdout = run(
(
"buck2",
"build",
"--reuse-current-config",
"//hphp/hack/src/hackc:hackc",
"--show-full-output",
)
)
_, hackc = stdout.split(" ", 1)
return hackc.strip()
def main():
parser = argparse.ArgumentParser()
parser.add_argument("files", metavar="FILE", type=str, nargs="*")
parser.add_argument("--cargo", action="store_true")
args = parser.parse_args()
global HACKC, ROOT
HACKC = compute_hackc(args.cargo)
ROOT = os.path.dirname(__file__)
if not args.files:
args.files = []
for root, _, files in os.walk(ROOT):
for file in files:
if file.endswith(".hack") and not file.endswith("_tc.hack"):
args.files.append(os.path.join(root, file))
for file in sorted(args.files):
update_file(file)
def warn(filename, line, why):
print(f"{filename}:{line + 1} (warning): {why}", file=sys.stderr)
def bail(filename, line, why):
print(f"{filename}:{line + 1}: {why}", file=sys.stderr)
sys.exit(1)
main() |
Hack | hhvm/hphp/hack/src/hackc/test/infer/var_cache.hack | // RUN: %hackc compile-infer %s | FileCheck %s
// TEST-CHECK-BAL: define $root.check1
// CHECK: define $root.check1($this: *void, $a: *HackMixed, $b: *HackMixed, $c: *HackMixed) : *void {
// CHECK: #b0:
// CHECK: n0: *HackMixed = load &$a
// CHECK: n1: *HackMixed = load &$b
// CHECK: n2: *HackMixed = load &$c
// CHECK: n3 = $root.call(null, n0, n1, n2)
// CHECK: n4 = $root.call(null, n2, n1, n2)
// CHECK: n5 = $root.call(null, n1, n1, n2)
// CHECK: n6 = $root.call(null, n0, n1, n0)
// CHECK: ret null
// CHECK: }
function check1(mixed $a, mixed $b, mixed $c): void {
call($a,$b,$c);
call($c,$b,$c);
call($b,$b,$c);
call($a,$b,$a);
}
// TEST-CHECK-BAL: define $root.check2
// CHECK: define $root.check2($this: *void, $c: *HackInt) : *void {
// CHECK: local $a: *void
// CHECK: #b0:
// CHECK: store &$a <- $builtins.hack_int(2): *HackMixed
// CHECK: n0: *HackMixed = load &$a
// CHECK: n1 = $root.call(null, n0)
// CHECK: store &$a <- $builtins.hack_int(7): *HackMixed
// CHECK: n2: *HackMixed = load &$a
// CHECK: n3 = $root.call(null, n2)
// CHECK: ret null
// CHECK: }
function check2(int $c): void {
$a = 2;
call($a);
$a = 7;
call($a);
}
// TEST-CHECK-BAL: define $root.check3
// CHECK: define $root.check3($this: *void) : *void {
// CHECK: local $a: *void
// CHECK: #b0:
// CHECK: n0 = $builtins.hhbc_new_vec()
// CHECK: store &$a <- n0: *HackMixed
// CHECK: n1 = $root.call(null, n0)
// CHECK: n2 = $builtins.hack_int(0)
// CHECK: n3 = $builtins.hack_int(7)
// CHECK: n4 = $builtins.hack_array_cow_set(n0, n2, n3)
// CHECK: store &$a <- n4: *HackMixed
// CHECK: n5 = $root.call(null, n4)
// CHECK: ret null
// CHECK: }
function check3(): void {
$a = vec[];
call($a);
$a[0] = 7;
call($a);
} |
Rust | hhvm/hphp/hack/src/hackc/types/lib.rs | #![feature(box_patterns)]
pub mod readonly_check;
pub mod readonly_nonlocal_infer;
mod subtype;
mod tyx; |
Rust | hhvm/hphp/hack/src/hackc/types/readonly_check.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.
//// Keep this file in sync with ../../parser/readonly_check.rs *except* for @HACKC_ADDED parts.
//// TODO(T128733540): we should have only one readonly_check.rs
use std::borrow::Cow;
use aast::Expr_ as E_;
use hash::HashMap;
use hash::HashSet;
use hh_autoimport_rust::is_hh_autoimport_fun;
use lazy_static::lazy_static;
use naming_special_names_rust::special_idents;
use naming_special_names_rust::typehints;
use naming_special_names_rust::user_attributes;
use oxidized::aast;
use oxidized::aast_visitor::visit_mut;
use oxidized::aast_visitor::AstParams;
use oxidized::aast_visitor::NodeMut;
use oxidized::aast_visitor::VisitorMut;
use oxidized::ast::*;
use oxidized::ast_defs;
use oxidized::local_id;
use oxidized::pos::Pos;
use parser_core_types::syntax_error;
use parser_core_types::syntax_error::Error as ErrorMsg;
lazy_static! {
// @HACKC_ADDED because primitives are namespaced in hackc
// behind [`is_codegen()` check](https://www.internalfb.com/code/fbsource/[53b542f7778a]/fbcode/hphp/hack/src/parser/namespaces.rs?lines=186)
// TODO(T128733540): remove this hack.
static ref PRIMITIVE_TYPEHINTS: HashSet<String> = typehints::PRIMITIVE_TYPEHINTS
.iter()
.map(|name| format!(r"\HH\{}", name))
.collect();
}
pub struct ReadOnlyError(pub Pos, pub ErrorMsg);
// Local environment which keeps track of how many readonly values it has
#[derive(PartialEq, Clone)]
struct Lenv {
pub lenv: HashMap<String, Rty>,
pub num_readonly: u32,
}
impl Lenv {
pub fn new() -> Lenv {
Lenv {
lenv: HashMap::default(),
num_readonly: 0,
}
}
pub fn insert(&mut self, var_name: String, rty: Rty) {
let result = self.lenv.insert(var_name, rty);
match (rty, result) {
(Rty::Readonly, Some(Rty::Mutable)) => {
self.num_readonly += 1;
}
(Rty::Readonly, None) => {
self.num_readonly += 1;
}
(Rty::Mutable, Some(Rty::Readonly)) => {
self.num_readonly -= 1;
}
_ => {} // otherwise number of readonly values does not change
}
}
pub fn get(&self, var_name: &str) -> Option<&Rty> {
self.lenv.get(var_name)
}
}
#[derive(PartialEq, Copy, Clone)]
pub enum Rty {
Readonly,
Mutable,
}
struct Context {
locals: Lenv,
readonly_return: Rty,
this_ty: Rty,
inout_params: HashSet<String>,
#[allow(dead_code)]
is_typechecker: bool,
}
impl Context {
fn new(readonly_ret: Rty, this_ty: Rty, is_typechecker: bool) -> Self {
Self {
locals: Lenv::new(),
readonly_return: readonly_ret,
this_ty,
inout_params: HashSet::default(),
is_typechecker,
}
}
pub fn add_local(&mut self, var_name: &str, rty: Rty) {
self.locals.insert(var_name.to_string(), rty);
}
pub fn add_param(&mut self, var_name: &str, rty: Rty, inout_param: bool) {
self.locals.insert(var_name.to_string(), rty);
if inout_param {
self.inout_params.insert(var_name.to_string());
}
}
pub fn get_rty(&self, var_name: &str) -> Rty {
match self.locals.get(var_name) {
Some(&x) => x,
None => Rty::Mutable,
}
}
}
fn ro_expr_list(context: &mut Context, exprs: &[Expr]) -> Rty {
if exprs.iter().any(|e| rty_expr(context, e) == Rty::Readonly) {
Rty::Readonly
} else {
Rty::Mutable
}
}
fn ro_expr_list2<T>(context: &mut Context, exprs: &[(T, Expr)]) -> Rty {
if exprs
.iter()
.any(|e| rty_expr(context, &e.1) == Rty::Readonly)
{
Rty::Readonly
} else {
Rty::Mutable
}
}
fn ro_kind_to_rty(ro: Option<oxidized::ast_defs::ReadonlyKind>) -> Rty {
match ro {
Some(oxidized::ast_defs::ReadonlyKind::Readonly) => Rty::Readonly,
_ => Rty::Mutable,
}
}
fn rty_expr(context: &mut Context, expr: &Expr) -> Rty {
let aast::Expr(_, _, exp) = expr;
use aast::Expr_::*;
match exp {
ReadonlyExpr(_) => Rty::Readonly,
ObjGet(og) => {
let (obj, _member_name, _null_flavor, _reffiness) = &**og;
rty_expr(context, obj)
}
Lvar(id_orig) => {
let var_name = local_id::get_name(&id_orig.1);
let is_this = var_name == special_idents::THIS;
if is_this {
context.this_ty
} else {
context.get_rty(var_name)
}
}
Darray(d) => {
let (_, exprs) = &**d;
ro_expr_list2(context, exprs)
}
Varray(v) => {
let (_, exprs) = &**v;
ro_expr_list(context, exprs)
}
Shape(fields) => ro_expr_list2(context, fields),
ValCollection(v) => {
let (_, _, exprs) = &**v;
ro_expr_list(context, exprs)
}
KeyValCollection(kv) => {
let (_, _, fields) = &**kv;
if fields
.iter()
.any(|f| rty_expr(context, &f.1) == Rty::Readonly)
{
Rty::Readonly
} else {
Rty::Mutable
}
}
Collection(c) => {
let (_, _, fields) = &**c;
if fields.iter().any(|f| match f {
aast::Afield::AFvalue(e) => rty_expr(context, e) == Rty::Readonly,
aast::Afield::AFkvalue(_, e) => rty_expr(context, e) == Rty::Readonly,
}) {
Rty::Readonly
} else {
Rty::Mutable
}
}
Xml(_) | Efun(_) | Lfun(_) => Rty::Mutable,
Tuple(t) => ro_expr_list(context, t),
// Only list destructuring
List(_) => Rty::Mutable,
// Boolean statement always mutable
Is(_) => Rty::Mutable,
//
As(a) => {
// Readonlyness of inner expression
let (exp, hint, _) = &**a;
let hint_ = &*hint.1;
match hint_ {
// Primitives are always mutable
// Unfortunately, we don't make Hprim as a hint type until naming
// so we have to look at Happly
aast::Hint_::Happly(cn, _) if PRIMITIVE_TYPEHINTS.contains(cn.name()) => {
Rty::Mutable
}
_ => rty_expr(context, exp),
}
}
Upcast(a) => {
// Readonlyness of inner expression
let (exp, _) = &**a;
rty_expr(context, exp)
}
Eif(e) => {
// $x ? a : b is readonly if either a or b are readonly
let (_, exp1_opt, exp2) = &**e;
if let Some(exp1) = exp1_opt {
match (rty_expr(context, exp1), rty_expr(context, exp2)) {
(_, Rty::Readonly) | (Rty::Readonly, _) => Rty::Readonly,
(Rty::Mutable, Rty::Mutable) => Rty::Mutable,
}
} else {
rty_expr(context, exp2)
}
}
Pair(p) => {
let (_, exp1, exp2) = &**p;
match (rty_expr(context, exp1), rty_expr(context, exp2)) {
(_, Rty::Readonly) | (Rty::Readonly, _) => Rty::Readonly,
(Rty::Mutable, Rty::Mutable) => Rty::Mutable,
}
}
Hole(h) => {
let (expr, _, _, _) = &**h;
rty_expr(context, expr)
}
Cast(_) => Rty::Mutable, // Casts are only valid on primitive types, so its always mutable
New(_) => Rty::Mutable,
// FWIW, this does not appear on the aast at this stage(it only appears after naming in typechecker),
// but we can handle it for future in case that changes
This => context.this_ty,
ArrayGet(ag) => {
let (expr, _) = &**ag;
rty_expr(context, expr)
}
Await(expr) => {
let expr = &**expr;
rty_expr(context, expr)
}
// Primitive types are mutable
Null | True | False | Omitted | Invalid(_) => Rty::Mutable,
Int(_) | Float(_) | String(_) | String2(_) | PrefixedString(_) => Rty::Mutable,
Id(_) => Rty::Mutable,
Dollardollar(lid) => {
let (id, dollardollar) = &lid.1;
let var_name = format!("{}{}", dollardollar, id);
context.get_rty(&var_name)
}
// First put it in typechecker, then HHVM
Clone(e) => {
// Clone only clones shallowly, so we need to respect readonly even if you clone it
let expr = &**e;
rty_expr(context, expr)
}
Call(c) => {
if let aast::CallExpr {
func: aast::Expr(_, _, Id(i)),
args,
..
} = &**c
{
if is_special_builtin(&i.1) && !args.is_empty() {
// Take first argument
let (_, expr) = &args[0];
rty_expr(context, expr)
} else {
Rty::Mutable
}
} else {
Rty::Mutable
}
}
// Mutable unless wrapped in a readonly expression
ClassGet(_) | ClassConst(_) => Rty::Mutable,
FunctionPointer(_) => Rty::Mutable,
// This is really just a statement, does not have a value
Yield(_) => Rty::Mutable,
Binop(b) => {
let aast::Binop { bop, lhs, rhs } = &**b;
match bop {
ast_defs::Bop::QuestionQuestion => {
match (rty_expr(context, lhs), rty_expr(context, rhs)) {
(Rty::Readonly, _) | (_, Rty::Readonly) => Rty::Readonly,
(Rty::Mutable, Rty::Mutable) => Rty::Mutable,
}
}
// All other operators are all primitive in result
_ => Rty::Mutable,
}
}
// Unary operators are all primitive in result
Unop(_) => Rty::Mutable,
Pipe(p) => {
let (lid, left, _) = &**p;
// The only time the id number matters is for Dollardollar
let (_, dollardollar) = &lid.1;
let left_rty = rty_expr(context, left);
context.add_local(dollardollar, left_rty);
rty_expr(context, &p.2)
}
ExpressionTree(_) | EnumClassLabel(_) | ETSplice(_) => Rty::Mutable,
Import(_) | Lplaceholder(_) => Rty::Mutable,
// More function values which are always mutable
MethodCaller(_) => Rty::Mutable,
Package(_) => Rty::Mutable,
}
}
fn strip_ns(name: &str) -> &str {
match name.chars().next() {
Some('\\') => &name[1..],
_ => name,
}
}
// Special builtins that can take readonly values and return the same readonlyness back
// These are represented as bytecodes, so do not go through regular call enforcement
fn is_special_builtin(f_name: &str) -> bool {
let stripped = strip_ns(f_name);
let namespaced_f_name = if is_hh_autoimport_fun(stripped) {
Cow::Owned(format!("HH\\{}", f_name))
} else {
Cow::Borrowed(stripped)
};
match &namespaced_f_name[..] {
"HH\\dict"
| "HH\\varray"
| "HH\\darray"
| "HH\\vec"
| "hphp_array_idx"
| "HH\\FIXME\\UNSAFE_NONNULL_CAST"
| "HH\\FIXME\\UNSAFE_CAST" => true,
/* all other special builtins listed in emit_expresion.rs return mutable:
specifically, these:
"array_key_exists" => Some((2, IMisc(AKExists))),
"intval" => Some((1, IOp(CastInt))),
"boolval" => Some((1, IOp(CastBool))),
"strval" => Some((1, IOp(CastString))),
"floatval" | "doubleval" => Some((1, IOp(CastDouble))),
"HH\\global_get" => Some((1, IGet(CGetG))),
"HH\\global_isset" => Some((1, IIsset(IssetG))),
*/
_ => false,
}
}
fn explicit_readonly(expr: &mut Expr) {
match &expr.2 {
aast::Expr_::ReadonlyExpr(_) => {}
_ => {
let tmp = std::mem::replace(expr, Expr(expr.0, expr.1.clone(), Expr_::Null));
expr.2 = aast::Expr_::ReadonlyExpr(Box::new(tmp));
}
}
}
// For assignments to nonlocals, i.e.
// $x->prop[0] = new Foo();
fn check_assignment_nonlocal(
context: &mut Context,
checker: &mut Checker,
pos: &Pos,
lhs: &mut Expr,
rhs: &mut Expr,
) {
match &mut lhs.2 {
aast::Expr_::ObjGet(o) => {
let (obj, _get, _, _) = &**o;
// If obj is readonly, throw error
match rty_expr(context, obj) {
Rty::Readonly => {
checker.add_error(pos, syntax_error::assignment_to_readonly);
}
Rty::Mutable => {
match rty_expr(context, rhs) {
Rty::Readonly => {
// make the readonly expression explicit, since if it is
// readonly we need to make sure the property is a readonly prop
explicit_readonly(rhs);
}
// Mutable case does not require special checks
Rty::Mutable => {}
}
}
}
}
// Support self::$x["x"] assignments
// Here, if the rhs is readonly we need to be explicit
aast::Expr_::ClassGet(_) => match rty_expr(context, rhs) {
Rty::Readonly => {
explicit_readonly(rhs);
}
_ => {}
},
// On an array get <expr>[0] = <rhs>, recurse and check compatibility of
// inner <expr> with <rhs>
aast::Expr_::ArrayGet(ag) => {
let (array, _) = &mut **ag;
check_assignment_nonlocal(context, checker, pos, array, rhs);
}
_ => {
// Base case: here we just check whether the lhs expression is readonly
// compared to the rhs
match (rty_expr(context, lhs), rty_expr(context, rhs)) {
(Rty::Mutable, Rty::Readonly) => {
// error, can't assign a readonly value to a mutable collection
checker.add_error(
&rhs.1, // Position of readonly expression
syntax_error::assign_readonly_to_mutable_collection,
)
}
(Rty::Readonly, Rty::Readonly) => {
// make rhs explicit (to make sure we are not writing a readonly
// value to a mutable one)
explicit_readonly(rhs);
// make lhs readonly explicitly, to check that it's a readonly
// copy on write array here the lefthandside is either a local
// variable or a class_get.
explicit_readonly(lhs);
}
(Rty::Readonly, Rty::Mutable) => {
explicit_readonly(lhs);
}
// Assigning to a mutable value always succeeds, so no explicit checks
// are needed
(Rty::Mutable, Rty::Mutable) => {}
}
}
}
}
// Merges two local environments together. Note that
// because of conservativeness, the resulting Lenv's num_readonly is at
// least the max of lenv1.num_readonly, lenv2.num_readonly
fn merge_lenvs(lenv1: &Lenv, lenv2: &Lenv) -> Lenv {
let mut new_lenv = lenv1.clone();
for (key, value) in lenv2.lenv.iter() {
match (value, new_lenv.get(key)) {
(_, Some(Rty::Readonly)) => {}
(rty, _) => {
new_lenv.insert(key.to_string(), *rty);
}
}
}
new_lenv
}
// Toplevel assignment check
fn check_assignment_validity(
context: &mut Context,
checker: &mut Checker,
pos: &Pos,
lhs: &mut Expr,
rhs: &mut Expr,
) {
match &mut lhs.2 {
aast::Expr_::Lvar(id_orig) => {
let var_name = local_id::get_name(&id_orig.1).to_string();
let rhs_rty = rty_expr(context, rhs);
if context.inout_params.contains(&var_name) && rhs_rty == Rty::Readonly {
checker.add_error(pos, syntax_error::inout_readonly_assignment);
}
context.add_local(&var_name, rhs_rty);
}
// list assignment
aast::Expr_::List(l) => {
let exprs = &mut **l;
for e in exprs.iter_mut() {
check_assignment_validity(context, checker, &e.1.clone(), e, rhs);
}
}
// directly assigning to a class static is always valid (locally) as long as
// the rhs is explicit on its readonlyness
aast::Expr_::ClassGet(_) => {
let rhs_rty = rty_expr(context, rhs);
match rhs_rty {
Rty::Readonly => explicit_readonly(rhs),
_ => {}
}
}
_ => {
check_assignment_nonlocal(context, checker, pos, lhs, rhs);
}
}
}
struct Checker {
errors: Vec<ReadOnlyError>,
is_typechecker: bool, // used for migration purposes
}
impl Checker {
fn new(typechecker: bool) -> Self {
Self {
errors: vec![],
is_typechecker: typechecker,
}
}
fn add_error(&mut self, pos: &Pos, msg: ErrorMsg) {
self.errors.push(ReadOnlyError(pos.clone(), msg));
}
fn subtype(&mut self, pos: &Pos, r_sub: &Rty, r_sup: &Rty, reason: &str) {
use Rty::*;
match (r_sub, r_sup) {
(Readonly, Mutable) => self.add_error(
pos,
syntax_error::invalid_readonly("readonly", "mutable", reason),
),
_ => {}
}
}
fn handle_single_block(
&mut self,
context: &mut Context,
lenv: Lenv,
b: &mut aast::Block<(), ()>,
) -> Lenv {
context.locals = lenv;
let _ = b.recurse(context, self.object());
context.locals.clone()
}
// Handles analysis for a given loop
// Will run b.recurse() up to X times, where X is the number
// of readonly values in the local environment
// on each loop, we check if the number of readonly values has changed
// since each loop iteration will monotonically increase the number
// of readonly values, the loop must end within that fixed number of iterations.
fn handle_loop(
&mut self,
context: &mut Context,
lenv: Lenv,
b: &mut aast::Block<(), ()>,
as_expr_var_info: Option<(String, Rty)>,
) -> Lenv {
let mut new_lenv = lenv.clone();
// Reassign the as_expr_var_info on every iteration of the loop
if let Some((ref var_name, rty)) = as_expr_var_info {
new_lenv.insert(var_name.clone(), rty);
}
// run the block once and merge the environment
let new_lenv = merge_lenvs(&lenv, &self.handle_single_block(context, new_lenv, b));
if new_lenv.num_readonly > lenv.num_readonly {
self.handle_loop(context, new_lenv, b, as_expr_var_info)
} else {
new_lenv
}
}
}
impl<'ast> VisitorMut<'ast> for Checker {
type Params = AstParams<Context, ()>;
fn object(&mut self) -> &mut dyn VisitorMut<'ast, Params = Self::Params> {
self
}
fn visit_method_(
&mut self,
_context: &mut Context,
m: &mut aast::Method_<(), ()>,
) -> Result<(), ()> {
if m.user_attributes
.iter()
.any(|ua| user_attributes::ignore_readonly_local_errors(&ua.name.1))
{
return Ok(());
}
let readonly_return = ro_kind_to_rty(m.readonly_ret);
let readonly_this = if m.readonly_this {
Rty::Readonly
} else {
Rty::Mutable
};
let mut context = Context::new(readonly_return, readonly_this, self.is_typechecker);
for p in m.params.iter() {
let is_inout = match p.callconv {
ast_defs::ParamKind::Pinout(_) => true,
_ => false,
};
if let Some(rhs) = &p.expr {
let ro_rhs = rty_expr(&mut context, rhs);
self.subtype(
&rhs.1,
&ro_rhs,
&ro_kind_to_rty(p.readonly),
"this parameter is not marked readonly",
);
}
if p.readonly.is_some() {
if is_inout {
self.add_error(&p.pos, syntax_error::inout_readonly_parameter);
}
context.add_param(&p.name, Rty::Readonly, is_inout)
} else {
context.add_param(&p.name, Rty::Mutable, is_inout)
}
}
m.recurse(&mut context, self.object())
}
fn visit_fun_(&mut self, context: &mut Context, f: &mut aast::Fun_<(), ()>) -> Result<(), ()> {
// Is run on every function definition and closure definition
if f.user_attributes
.iter()
.any(|ua| user_attributes::ignore_readonly_local_errors(&ua.name.1))
{
return Ok(());
}
let readonly_return = ro_kind_to_rty(f.readonly_ret);
let readonly_this = ro_kind_to_rty(f.readonly_this);
let mut new_context = Context::new(readonly_return, readonly_this, self.is_typechecker);
// Add the old context's stuff into the new context, as readonly if needed
for (local, rty) in context.locals.lenv.iter() {
if readonly_this == Rty::Readonly {
new_context.add_local(local, Rty::Readonly);
} else {
new_context.add_local(local, *rty);
}
}
for p in f.params.iter() {
let is_inout = match p.callconv {
ast_defs::ParamKind::Pinout(_) => true,
_ => false,
};
if let Some(rhs) = &p.expr {
let ro_rhs = rty_expr(&mut new_context, rhs);
self.subtype(
&rhs.1,
&ro_rhs,
&ro_kind_to_rty(p.readonly),
"this parameter is not marked readonly",
);
}
if p.readonly.is_some() {
if is_inout {
self.add_error(&p.pos, syntax_error::inout_readonly_parameter)
}
new_context.add_param(&p.name, Rty::Readonly, is_inout)
} else {
new_context.add_param(&p.name, Rty::Mutable, is_inout)
}
}
f.recurse(&mut new_context, self.object())
}
fn visit_fun_def(
&mut self,
_context: &mut Context,
f: &mut aast::FunDef<(), ()>,
) -> Result<(), ()> {
// Clear the context completely on a fun_def
let mut context = Context::new(Rty::Mutable, Rty::Mutable, self.is_typechecker);
f.recurse(&mut context, self.object())
}
fn visit_expr(&mut self, context: &mut Context, p: &mut aast::Expr<(), ()>) -> Result<(), ()> {
// Pipe expressions have their own recursion method due to their weird evaluation rules
if !p.2.is_pipe() {
// recurse on inner members first, then assign to value
p.recurse(context, self.object())?;
}
match &mut p.2 {
aast::Expr_::Binop(x) => {
let aast::Binop { bop, lhs, rhs } = x.as_mut();
if let Bop::Eq(_) = bop {
check_assignment_validity(context, self, &p.1, lhs, rhs);
}
}
aast::Expr_::Call(x) => {
let aast::CallExpr { func, args, .. } = &mut **x;
match rty_expr(context, func) {
Rty::Readonly => explicit_readonly(func),
Rty::Mutable => {}
};
for (callconv, param) in args.iter_mut() {
match (callconv, rty_expr(context, param)) {
(ast_defs::ParamKind::Pinout(_), Rty::Readonly) => {
self.add_error(param.pos(), syntax_error::inout_readonly_argument)
}
(ast_defs::ParamKind::Pnormal, Rty::Readonly) => explicit_readonly(param),
(_, Rty::Mutable) => {}
}
}
}
aast::Expr_::New(n) => {
let (_, _targs, args, _variadic, _) = &mut **n;
for param in args.iter_mut() {
match rty_expr(context, param) {
Rty::Readonly => explicit_readonly(param),
Rty::Mutable => {}
}
}
}
aast::Expr_::Pipe(p) => {
let (lid, left, right) = &mut **p;
// The only time the id number matters is for Dollardollar
let (_, dollardollar) = &lid.1;
// Go left first, get the readonlyness, then go right
self.visit_expr(context, left)?;
let left_rty = rty_expr(context, left);
context.add_local(dollardollar, left_rty);
self.visit_expr(context, right)?;
}
_ => {}
}
Ok(())
}
fn visit_xhp_simple(
&mut self,
context: &mut Context,
p: &mut aast::XhpSimple<(), ()>,
) -> Result<(), ()> {
if let Rty::Readonly = rty_expr(context, &p.expr) {
self.add_error(&p.expr.1, syntax_error::readonly_on_xhp);
}
p.recurse(context, self.object())
}
fn visit_stmt(
&mut self,
context: &mut Context,
s: &mut aast::Stmt<(), ()>,
) -> std::result::Result<(), ()> {
match &mut s.1 {
aast::Stmt_::Return(r) => {
if let Some(expr) = r.as_mut() {
self.subtype(&expr.1, &rty_expr(context, expr), &context.readonly_return, "this function does not return readonly. Please mark it to return readonly if needed.")
}
s.recurse(context, self.object())
}
aast::Stmt_::If(i) => {
let (condition, if_, else_) = &mut **i;
let old_lenv = context.locals.clone();
self.visit_expr(context, condition)?;
let if_lenv = self.handle_single_block(context, old_lenv.clone(), if_);
let else_lenv = self.handle_single_block(context, old_lenv, else_);
let new_lenv = merge_lenvs(&if_lenv, &else_lenv);
context.locals = new_lenv;
Ok(())
}
aast::Stmt_::Try(t) => {
let (try_, catches, finally_) = &mut **t;
let old_lenv = context.locals.clone();
try_.recurse(context, self.object())?;
// Each catch should run with no assumptions about how much of the try ran,
// i.e. with old_lenv. Start with the lenv right after the try block and merge
let result_lenv =
catches
.iter_mut()
.fold(context.locals.clone(), |result_lenv, catch| {
let catch_lenv =
self.handle_single_block(context, old_lenv.clone(), &mut catch.2);
merge_lenvs(&result_lenv, &catch_lenv)
});
// Update the lenv from the old lenv with the result of
context.locals = result_lenv;
finally_.recurse(context, self.object())
}
aast::Stmt_::Switch(s) => {
let (condition, cases, default) = &mut **s;
self.visit_expr(context, condition)?;
let old_lenv = context.locals.clone();
let result_lenv = context.locals.clone();
let result_lenv = cases.iter_mut().fold(result_lenv, |result_lenv, case| {
let _ = self.visit_expr(context, &mut case.0);
let case_lenv =
self.handle_single_block(context, old_lenv.clone(), &mut case.1);
merge_lenvs(&result_lenv, &case_lenv)
});
let result_lenv = default.iter_mut().fold(result_lenv, |result_lenv, case| {
let case_lenv =
self.handle_single_block(context, old_lenv.clone(), &mut case.1);
merge_lenvs(&result_lenv, &case_lenv)
});
context.locals = result_lenv;
Ok(())
}
aast::Stmt_::Throw(t) => {
let inner = &**t;
match rty_expr(context, inner) {
Rty::Readonly => {
self.add_error(&inner.1, syntax_error::throw_readonly_exception);
}
Rty::Mutable => {}
}
t.recurse(context, self.object())
}
aast::Stmt_::Foreach(f) => {
let (e, as_expr, b) = &mut **f;
// Tracks what variable is being assigned each iteration of the loop
let mut as_expr_var_info = None;
match as_expr {
aast::AsExpr::AsV(aast::Expr(_, _, E_::Lvar(id))) => {
let var_name = local_id::get_name(&id.1);
let rty = rty_expr(context, e);
as_expr_var_info = Some((var_name.to_string(), rty));
}
aast::AsExpr::AsKv(
_, // key is arraykey and does not need to be readonly
aast::Expr(_, _, E_::Lvar(value_id)),
) => {
let var_name = local_id::get_name(&value_id.1);
let rty = rty_expr(context, e);
as_expr_var_info = Some((var_name.to_string(), rty));
}
aast::AsExpr::AwaitAsV(_, aast::Expr(_, _, E_::Lvar(id))) => {
let var_name = local_id::get_name(&id.1);
let rty = rty_expr(context, e);
as_expr_var_info = Some((var_name.to_string(), rty));
}
aast::AsExpr::AwaitAsKv(
_,
_, // key is arraykey and does not need to be readonly
aast::Expr(_, _, E_::Lvar(value_id)),
) => {
let var_name = local_id::get_name(&value_id.1);
let rty = rty_expr(context, e);
as_expr_var_info = Some((var_name.to_string(), rty));
}
// Any other Foreach here would mean no Lvar
// where an Lvar is needed. In those cases
// we will parse error, but the parse tree might still exist
// so we just ignore those cases and continue our analysis
// knowing that a parse error will show up
_ => {}
};
self.visit_expr(context, e)?;
as_expr.recurse(context, self.object())?;
let old_lenv = context.locals.clone();
let new_lenv = self.handle_loop(context, old_lenv, b, as_expr_var_info);
context.locals = new_lenv;
Ok(())
}
aast::Stmt_::Do(d) => {
let (b, cond) = &mut **d;
// loop runs at least once
let new_lenv = self.handle_single_block(context, context.locals.clone(), b);
let block_lenv = self.handle_loop(context, new_lenv, b, None);
context.locals = block_lenv;
self.visit_expr(context, cond)
}
aast::Stmt_::While(w) => {
let (cond, b) = &mut **w;
self.visit_expr(context, cond)?;
let old_lenv = context.locals.clone();
let new_lenv = self.handle_loop(context, old_lenv, b, None);
context.locals = new_lenv;
Ok(())
}
aast::Stmt_::For(f) => {
let (initializers, term, increment, b) = &mut **f;
for i in initializers {
self.visit_expr(context, i)?;
}
match term {
Some(t) => {
self.visit_expr(context, t)?;
}
None => {}
}
for inc in increment {
self.visit_expr(context, inc)?;
}
let old_lenv = context.locals.clone();
// Technically, for loops can have an as_expr_var_info as well, but it's
// very rare to write one where this occurs, so we will just be conservative
let new_lenv = self.handle_loop(context, old_lenv, b, None);
context.locals = new_lenv;
Ok(())
}
aast::Stmt_::Awaitall(a) => {
let (assignments, block) = &mut **a;
for i in assignments {
// if there's a temp local
if let Some(lid) = &i.0 {
let var_name = local_id::get_name(&lid.1).to_string();
let rhs_rty = rty_expr(context, &i.1);
context.add_local(&var_name, rhs_rty);
}
}
block.recurse(context, self.object())
}
_ => s.recurse(context, self.object()),
}
}
}
pub fn check_program(
program: &mut aast::Program<(), ()>,
is_typechecker: bool,
) -> Vec<ReadOnlyError> {
let mut checker = Checker::new(is_typechecker);
let mut context = Context::new(Rty::Mutable, Rty::Mutable, is_typechecker);
visit_mut(&mut checker, &mut context, program).unwrap();
checker.errors
} |
Rust | hhvm/hphp/hack/src/hackc/types/readonly_nonlocal_infer.rs | // Copyright (c) Meta Platforms, Inc. and affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
//// Design:
//// - This module is concerned with inserting `readonly`s where needed at *call sites*, for which it uses decls and inference.
//// - For propagating `readonly`s within a function, there should be no change in the logic in ./readonly_check.rs as compared to what is in the parser today.
//// - The code is biased toward speed of development to get signal about what we can infer.
use std::borrow::Cow;
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::env;
use std::sync::Arc;
use decl_provider::DeclProvider;
use decl_provider::Error;
use itertools::Itertools;
use naming_special_names_rust;
use oxidized::aast;
use oxidized::ast;
use oxidized::ast_defs;
use oxidized::ast_defs::Bop;
use oxidized::ast_defs::Pos;
use oxidized_by_ref::shallow_decl_defs::ShallowClass;
use oxidized_by_ref::typing_defs::FunElt;
use crate::subtype;
use crate::tyx;
use crate::tyx::Tyx;
struct Infer<'decl> {
decl_provider: Arc<dyn DeclProvider<'decl> + 'decl>,
stats: Stats,
}
#[derive(Debug, Default)]
struct Stats {
original_readonlys: u64,
redundant_readonlys: u64,
added_readonlys: u64,
}
#[derive(Debug, Copy, Clone)]
enum ClassScopeKind {
Static,
Nonstatic,
}
type Ctx = HashMap<String, Tyx>;
#[derive(Copy, Clone, Debug, Default)]
struct Where<'c> {
arg_of_readonly_expr: bool,
under_try: bool,
this_class_name: Option<&'c str>,
}
macro_rules! box_tup {
($($e:expr),* $(,)?) => {
Box::new(($($e,)*))
}
}
impl<'decl> Infer<'decl> {
fn infer_expr(
&mut self,
expr: &ast::Expr,
ctx: Ctx,
where_: Where<'_>,
) -> (ast::Expr, Tyx, Ctx) {
let aast::Expr(ex, pos, exp) = expr;
use aast::Expr_::*;
let next_where = Where {
arg_of_readonly_expr: matches!(exp, ReadonlyExpr(_)),
..where_
};
let (exp, ty, ctx) = match exp {
Darray(box (ty_args_opt, kvs)) => {
let mut kvs_out = Vec::with_capacity(kvs.len());
let mut ctx = ctx;
for (k, v) in kvs.iter() {
let (k, _k_ty, k_ctx) = self.infer_expr(k, ctx, next_where);
ctx = k_ctx;
let (v, _v_ty, v_ctx) = self.infer_expr(v, ctx, next_where);
ctx = v_ctx;
kvs_out.push((k, v))
}
(
Darray(box_tup!(ty_args_opt.clone(), kvs_out)),
Tyx::Todo,
ctx,
)
}
Varray(box (ty_args_opt, es)) => {
let mut es_out = Vec::with_capacity(es.len());
let mut ctx = ctx;
for e in es.iter() {
let (e, _e_ty, e_ctx) = self.infer_expr(e, ctx, next_where);
ctx = e_ctx;
es_out.push(e)
}
(
Varray(box_tup!(ty_args_opt.clone(), es_out)),
Tyx::Todo,
ctx,
)
}
Shape(fields) => {
let field_values = fields.iter().map(|field| &field.1).cloned().collect_vec();
let (field_exprs, _field_tys, ctx) =
self.infer_exprs(&field_values, ctx, next_where);
let fields: Vec<_> = fields
.iter()
.map(|field| &field.0)
.cloned()
.zip(field_exprs)
.collect();
(Shape(fields), Tyx::Todo, ctx)
}
ValCollection(box (vc_kind, ty_var_opt, es)) => {
let (es, _tys, ctx) = self.infer_exprs(es, ctx, next_where);
(
ValCollection(box_tup!(vc_kind.clone(), ty_var_opt.clone(), es)),
Tyx::Todo,
ctx,
)
}
KeyValCollection(box (kvc_kind, ty_var_opt, fields)) => {
let mut fields_out = Vec::with_capacity(fields.len());
let mut ctx = ctx;
for ast::Field(k, v) in fields.iter() {
let (k, _k_ty, k_ctx) = self.infer_expr(k, ctx, next_where);
ctx = k_ctx;
let (v, _v_ty, v_ctx) = self.infer_expr(v, ctx, next_where);
ctx = v_ctx;
fields_out.push(ast::Field(k, v))
}
(
KeyValCollection(box_tup!(kvc_kind.clone(), ty_var_opt.clone(), fields_out)),
Tyx::Todo,
ctx,
)
}
This => (exp.clone(), Tyx::Todo, ctx),
Null | True | False => (exp.clone(), Tyx::Primitive, ctx),
Omitted | Invalid(_) => (exp.clone(), Tyx::GiveUp, ctx),
Id(box id) => {
let ty = self
.get_fun_decl(id, pos)
.map_or(Tyx::GiveUp, |ft| Tyx::Fun(Box::new(ft)));
(exp.clone(), ty, ctx)
}
Lvar(box ast::Lid(_, (_, var))) => {
let ty = ctx.get(var).cloned().unwrap_or(Tyx::GiveUp);
(exp.clone(), ty, ctx)
}
Dollardollar(_b) => (exp.clone(), Tyx::Todo, ctx),
Clone(box e) => {
let (e, ty, ctx) = self.infer_expr(e, ctx, next_where);
(Clone(Box::new(e)), ty, ctx)
}
ArrayGet(box (arr, index_opt)) => {
let (arr, _arr_ty, ctx) = self.infer_expr(arr, ctx, next_where);
let (index_opt, _index_ty_opt, ctx) =
self.infer_expr_opt(index_opt.as_ref(), ctx, next_where);
(ArrayGet(box_tup!(arr, index_opt)), Tyx::Todo, ctx)
}
ObjGet(box (e1, e2, og_null_flavor, prop_or_method)) => {
let (e1, e1_ty, ctx) = self.infer_expr(e1, ctx, next_where);
let (e2, _e2_ty, ctx) = self.infer_expr(e2, ctx, next_where);
let ty = match (&e1_ty, prop_or_method, &e2) {
(
Tyx::Object { class_name },
ast_defs::PropOrMethod::IsMethod,
ast::Expr(_, _, aast::Expr_::Id(box ast_defs::Id(_, member_name))),
) => match &self.get_method_type(
class_name,
member_name,
ClassScopeKind::Nonstatic,
pos,
) {
Some(ft) => Tyx::Fun(Box::new(ft.clone())),
None => Tyx::Todo,
},
_ => Tyx::Todo,
};
let obj_get = ObjGet(box_tup!(
e1,
e2,
og_null_flavor.clone(),
prop_or_method.clone()
));
(obj_get, ty, ctx)
}
ClassGet(box (class_id, get_expr, prop_or_meth)) => {
let (get_expr, ctx, prop_name_opt) = match get_expr {
ClassGetExpr::CGstring((_, prop_name)) => {
(get_expr.clone(), ctx, Some(prop_name))
}
ClassGetExpr::CGexpr(e) => {
let (e, _, ctx) = self.infer_expr(e, ctx, next_where);
(ClassGetExpr::CGexpr(e), ctx, None)
}
};
let ty = match (prop_name_opt, class_id_to_name(class_id, where_)) {
(Some(prop_name), Some(class_name)) => self
.get_prop_type(class_name, prop_name, ClassScopeKind::Static, pos)
.unwrap_or(Tyx::GiveUp),
_ => Tyx::GiveUp,
};
use aast::ClassGetExpr;
let class_get =
ClassGet(box_tup!(class_id.clone(), get_expr, prop_or_meth.clone()));
let class_get = match &ty {
Tyx::Readonly(_) => readonly_wrap_expr_(pos.clone(), class_get),
_ => class_get,
};
(class_get, ty, ctx)
}
ClassConst(box (class_id, (pos, member_name))) => {
let ty = match class_id_to_name(class_id, where_) {
Some(class_name) => self
.get_method_type(class_name, member_name, ClassScopeKind::Static, pos)
.map_or(Tyx::GiveUp, |ft| Tyx::Fun(Box::new(ft))),
None => Tyx::GiveUp,
};
let class_const = ClassConst(box_tup!(
class_id.clone(),
(pos.clone(), member_name.clone())
));
(class_const, ty, ctx)
}
Call(box aast::CallExpr {
func: e1,
targs,
args,
unpacked_arg: expr2_opt,
}) => {
let (e1, e1_ty, ctx) = self.infer_expr(e1, ctx, next_where);
let (param_kinds, param_exprs): (Vec<ast::ParamKind>, Vec<ast::Expr>) =
args.iter().cloned().unzip();
let (param_exprs, _param_tys, ctx) =
self.infer_exprs(¶m_exprs, ctx, next_where);
let (expr2_opt, _expr2_opt_ty, ctx) =
self.infer_expr_opt(expr2_opt.as_ref(), ctx, next_where);
let args = param_kinds.into_iter().zip(param_exprs).collect();
let mut call = Call(Box::new(aast::CallExpr {
func: e1,
targs: targs.clone(),
args,
unpacked_arg: expr2_opt,
}));
match &e1_ty {
Tyx::Fun(box ft) if returns_readonly(ft) => {
if where_.arg_of_readonly_expr {
self.stats.redundant_readonlys += 1;
} else {
call = readonly_wrap_expr_(pos.clone(), call);
self.stats.added_readonlys += 1;
}
}
_ => (),
}
(call, Tyx::Todo, ctx)
}
FunctionPointer(box (ptr, _ty_args)) => {
let ty = match ptr {
aast::FunctionPtrId::FPId(id) => match self.get_fun_decl(id, pos) {
Some(ft) => Tyx::Fun(Box::new(ft)),
None => Tyx::GiveUp,
},
aast::FunctionPtrId::FPClassConst(class_id, (pos, member_name)) => {
class_id_to_name(class_id, where_)
.and_then(|class_name| {
self.get_method_type(
class_name,
member_name,
ClassScopeKind::Static,
pos,
)
})
.map_or(Tyx::Todo, |ft| Tyx::Fun(Box::new(ft)))
}
};
(exp.clone(), ty, ctx)
}
Int(_s) => (exp.clone(), Tyx::Todo, ctx),
Float(_s) => (exp.clone(), Tyx::Todo, ctx),
String(_bstring) => (exp.clone(), Tyx::Todo, ctx),
String2(es) => {
let (es, _tys, ctx) = self.infer_exprs(es, ctx, next_where);
(String2(es), Tyx::Todo, ctx)
}
PrefixedString(box (str, e)) => {
let (e, _ty, ctx) = self.infer_expr(e, ctx, next_where);
(PrefixedString(box_tup!(str.clone(), e)), Tyx::Todo, ctx)
}
Yield(box field) => {
let (field, _field_ty, ctx) = self.infer_a_field(field, ctx, next_where);
(Yield(Box::new(field)), Tyx::Todo, ctx)
}
Await(e) => {
let (e, _ty, ctx) = self.infer_expr(e, ctx, next_where);
(Await(Box::new(e)), Tyx::Todo, ctx)
}
ReadonlyExpr(box e) => {
self.stats.original_readonlys += 1;
let (e, _ty, ctx) = self.infer_expr(e, ctx, next_where);
(ReadonlyExpr(Box::new(e)), Tyx::Todo, ctx)
}
Tuple(exprs) => {
let (exprs, _tys, ctx) = self.infer_exprs(exprs, ctx, next_where);
(Tuple(exprs), Tyx::Todo, ctx)
}
List(exprs) => {
let (exprs, _tys, ctx) = self.infer_exprs(exprs, ctx, next_where);
(List(exprs), Tyx::Todo, ctx)
}
Cast(box (hint, e)) => {
let (e, _ty, ctx) = self.infer_expr(e, ctx, next_where);
(Cast(box_tup!(hint.clone(), e)), Tyx::Todo, ctx)
}
Unop(box (unop, e)) => {
let (e, _ty, ctx) = self.infer_expr(e, ctx, next_where);
(Unop(box_tup!(unop.clone(), e)), Tyx::Todo, ctx)
}
// Does not yet handle `list`
Binop(box aast::Binop {
bop: eq @ Bop::Eq(bop_opt),
lhs: lhs @ ast::Expr(_, _, Lvar(box ast::Lid(_, (_, var_name)))),
rhs,
}) => {
let (rhs, r_ty, ctx) = self.infer_expr(rhs, ctx, next_where);
let (lhs, _l_ty, mut ctx) = self.infer_expr(lhs, ctx, next_where);
match bop_opt {
None => {
{
let ty_to_insert = match ctx.get(var_name) {
Some(existing_ty) if where_.under_try => {
subtype::join(Cow::Borrowed(existing_ty), Cow::Owned(r_ty))
.into_owned()
}
_ => r_ty,
};
ctx.insert(var_name.clone(), ty_to_insert);
}
(
Binop(Box::new(aast::Binop {
bop: eq.clone(),
lhs,
rhs,
})),
Tyx::GiveUp, // hhvm doesn't actually allow assignments to be used as expressions
ctx,
)
}
// no special handling for `+=` etc. yet
Some(_) => (
Binop(Box::new(aast::Binop {
bop: eq.clone(),
lhs,
rhs,
})),
Tyx::GiveUp,
ctx,
),
}
}
Binop(box ast::Binop { bop, lhs, rhs }) => {
let (lhs, _l_ty, ctx) = self.infer_expr(lhs, ctx, next_where);
let (rhs, _r_ty, ctx) = self.infer_expr(rhs, ctx, next_where);
(
Binop(Box::new(ast::Binop {
bop: bop.clone(),
lhs,
rhs,
})),
Tyx::Todo,
ctx,
)
}
Pipe(box (lid, lhs, rhs)) => {
let (lhs, _l_ty, ctx) = self.infer_expr(lhs, ctx, next_where);
let (rhs, _r_ty, ctx) = self.infer_expr(rhs, ctx, next_where);
(Pipe(box_tup!(lid.clone(), lhs, rhs)), Tyx::Todo, ctx)
}
Eif(box (e1, e2_opt, e3)) => {
let (e1, _e1_ty, ctx) = self.infer_expr(e1, ctx, next_where);
let (e2_opt, _index_ty_opt, ctx) =
self.infer_expr_opt(e2_opt.as_ref(), ctx, next_where);
let (e3, _e3_ty, ctx) = self.infer_expr(e3, ctx, next_where);
(Eif(box_tup!(e1, e2_opt, e3)), Tyx::Todo, ctx)
}
Is(box (e, hint)) => {
let (e, _e_ty, ctx) = self.infer_expr(e, ctx, next_where);
(Is(box_tup!(e, hint.clone())), Tyx::Todo, ctx)
}
As(box (e, hint, is_nullable)) => {
let (e, _e_ty, mut ctx) = self.infer_expr(e, ctx, next_where);
match &e {
ast::Expr(_, _, ast::Expr_::Lvar(box ast::Lid(_, (_, var)))) => {
// There's demo readonly code that does something like this:
// `$var as dynamic; $_ = $var->method_that_returns_readonly()`
// To ensure that we don't change the bytecode emitted in such cases, remove
// the variable from the context. TODO(T131219582): use type information from the hint
ctx.remove(var);
}
_ => (),
}
(As(box_tup!(e, hint.clone(), *is_nullable)), Tyx::Todo, ctx)
}
Upcast(box (e, hint)) => {
let (e, _e_ty, ctx) = self.infer_expr(e, ctx, next_where);
(Upcast(box_tup!(e, hint.clone())), Tyx::Todo, ctx)
}
New(box (class_id, ty_args, es, e_opt, ex)) => {
let (es, _es_tys, ctx) = self.infer_exprs(es, ctx, next_where);
let (e_opt, _e_ty_opt, ctx) = self.infer_expr_opt(e_opt.as_ref(), ctx, next_where);
let new = New(box_tup!(
class_id.clone(),
ty_args.clone(),
es,
e_opt,
ex.clone()
));
let ty = class_id_to_name(class_id, where_).map_or(Tyx::Todo, |class_name| {
Tyx::Object {
class_name: class_name.to_string(),
}
});
(new, ty, ctx)
}
Efun(efun) => {
let (fun, _fun_ty, ctx) = self.infer_fun(&efun.fun, ctx, next_where);
(
Efun(Box::new(ast::Efun {
fun,
use_: efun.use_.clone(),
closure_class_name: efun.closure_class_name.clone(),
})),
Tyx::Todo,
ctx,
)
}
Lfun(box (fun, lid)) => {
let (fun, _fun_ty, ctx) = self.infer_fun(fun, ctx, next_where);
(Lfun(box_tup!(fun, lid.clone())), Tyx::Todo, ctx)
}
Xml(box (class_name, attrs, es)) => {
let (es, _tys, mut ctx) = self.infer_exprs(es, ctx, next_where);
use ast::XhpAttribute;
let mut attrs_out = Vec::with_capacity(attrs.len());
for attr in attrs.iter() {
match attr {
XhpAttribute::XhpSimple(ast::XhpSimple { name, type_, expr }) => {
let (expr, _ty, expr_ctx) = self.infer_expr(expr, ctx, next_where);
ctx = expr_ctx;
attrs_out.push(XhpAttribute::XhpSimple(ast::XhpSimple {
name: name.clone(),
type_: type_.clone(),
expr,
}))
}
XhpAttribute::XhpSpread(e) => {
let (e, _ty, e_ctx) = self.infer_expr(e, ctx, next_where);
ctx = e_ctx;
attrs_out.push(XhpAttribute::XhpSpread(e))
}
}
}
let xml = Xml(box_tup!(class_name.clone(), attrs_out, es));
(xml, Tyx::Todo, ctx)
}
Import(_b) => (exp.clone(), Tyx::Todo, ctx),
Collection(box (id, opt_ty_args, a_fields)) => {
let mut a_fields_out = Vec::with_capacity(a_fields.len());
let mut ctx = ctx;
for a_field in a_fields.iter() {
let (a_field, _field_ty, field_ctx) =
self.infer_a_field(a_field, ctx, next_where);
ctx = field_ctx;
a_fields_out.push(a_field);
}
(
Collection(box_tup!(id.clone(), opt_ty_args.clone(), a_fields_out)),
Tyx::Todo,
ctx,
)
}
ExpressionTree(box et) => {
let (virtualized_expr, _virtualized_ty, ctx) =
self.infer_expr(&et.virtualized_expr, ctx, next_where);
let (runtime_expr, _runtime_ty, ctx) =
self.infer_expr(&et.runtime_expr, ctx, next_where);
let (splices, ctx) = self.infer_stmts_block(&et.splices, ctx, next_where);
let (function_pointers, ctx) =
self.infer_stmts_block(&et.function_pointers, ctx, next_where);
let splices = splices.0; // we want Vec<Stmt> rather than Block
let function_pointers = function_pointers.0; // we want Vec<Stmt> rather than Block
let et = ExpressionTree(Box::new(ast::ExpressionTree {
hint: et.hint.clone(),
splices,
function_pointers,
virtualized_expr,
runtime_expr,
dollardollar_pos: et.dollardollar_pos.clone(),
}));
(et, Tyx::Todo, ctx)
}
// The runtime iuc treats $_ like a normal variable, but
// hh` doesn't allow such code:
// $_ = 3; echo $_; // prints `3`, doesn't type-check
// Soundly approximate by treating such code as ill-formed.
Lplaceholder(_b) => (exp.clone(), Tyx::GiveUp, ctx),
MethodCaller(_b) => (exp.clone(), Tyx::Todo, ctx),
Pair(box (ty_args, e1, e2)) => {
let (e1, _ty1, ctx) = self.infer_expr(e1, ctx, next_where);
let (e2, _ty2, ctx) = self.infer_expr(e2, ctx, next_where);
let pair = Pair(box_tup!(ty_args.clone(), e1, e2));
(pair, Tyx::Todo, ctx)
}
ETSplice(box e) => {
let (e, _ty, ctx) = self.infer_expr(e, ctx, next_where);
(ETSplice(Box::new(e)), Tyx::Todo, ctx)
}
EnumClassLabel(_b) => (exp.clone(), Tyx::Todo, ctx),
Hole(_b) => (exp.clone(), Tyx::Todo, ctx),
Package(_) => todo!(),
};
let expr = aast::Expr(ex.clone(), pos.clone(), exp);
(expr, ty, ctx)
}
fn infer_exprs(
&mut self,
exprs: &[ast::Expr],
mut ctx: Ctx,
where_: Where<'_>,
) -> (Vec<ast::Expr>, Vec<Tyx>, Ctx) {
let mut es = Vec::with_capacity(exprs.len());
let mut tys = Vec::with_capacity(exprs.len());
for e in exprs.iter() {
let (e, ty, e_ctx) = self.infer_expr(e, ctx, where_);
ctx = e_ctx;
es.push(e);
tys.push(ty);
}
(es, tys, ctx)
}
fn infer_expr_opt(
&mut self,
expr_opt: Option<&ast::Expr>,
ctx: Ctx,
where_: Where<'_>,
) -> (Option<ast::Expr>, Option<Tyx>, Ctx) {
match expr_opt {
None => (None, None, ctx),
Some(e) => {
let (e, ty, ctx) = self.infer_expr(e, ctx, where_);
(Some(e), Some(ty), ctx)
}
}
}
fn infer_stmt(&mut self, stmt: &ast::Stmt, ctx: Ctx, where_: Where<'_>) -> (ast::Stmt, Ctx) {
let aast::Stmt(pos, st) = stmt;
use aast::Stmt_::*;
let next_where = Where {
arg_of_readonly_expr: false,
..where_
};
let (new_stmt, ctx) = match st {
Fallthrough => (Fallthrough, ctx),
Expr(box expr) => {
let (new_expr, _expr_ty, ctx) = self.infer_expr(expr, ctx, next_where);
(Expr(Box::new(new_expr)), ctx)
}
Break => (Break, ctx),
Continue => (Continue, ctx),
Throw(box e) => {
let (e, _e_ty, ctx) = self.infer_expr(e, ctx, next_where);
(Throw(Box::new(e)), ctx)
}
Return(box opt_expr) => match opt_expr {
None => (Return(Box::new(None)), ctx),
Some(e) => {
let (e, _e_ty, ctx) = self.infer_expr(e, ctx, next_where);
(Return(Box::new(Some(e))), ctx)
}
},
YieldBreak => (YieldBreak, ctx),
Awaitall(box (assigns, block)) => {
let lid_opts: Vec<Option<ast::Lid>> = assigns
.iter()
.map(|(lid_opt, _)| lid_opt)
.cloned()
.collect();
let assigns_exprs: Vec<_> =
assigns.iter().map(|(_, assign)| assign).cloned().collect();
let (assigns_exprs, _assigns_tys, ctx) =
self.infer_exprs(&assigns_exprs, ctx, next_where);
let (block, ctx) = self.infer_stmts_block(block, ctx, next_where);
let assigns: Vec<_> = lid_opts
.into_iter()
.zip(assigns_exprs.into_iter())
.collect();
let await_all = Awaitall(Box::new((assigns, block)));
(await_all, ctx)
}
If(box (expr, stmts1, stmts2)) => {
let (e, _e_ty, ctx) = self.infer_expr(expr, ctx, next_where);
let (stmts1, child_ctx_1) = self.infer_stmts_block(stmts1, ctx.clone(), next_where);
let (stmts2, child_ctx_2) = self.infer_stmts_block(stmts2, ctx.clone(), next_where);
let ctx = merge_ctxs(ctx, vec![child_ctx_1, child_ctx_2]);
let if_ = If(box_tup!(e, stmts1, stmts2));
(if_, ctx)
}
Do(box (stmts, e)) => {
let (stmts, child_ctx) = self.infer_stmts_block(stmts, ctx.clone(), next_where);
let ctx = merge_ctxs(ctx, vec![child_ctx]);
let (e, _e_ty, ctx) = self.infer_expr(e, ctx, next_where);
(Do(box_tup!(stmts, e)), ctx)
}
While(box (cond, block)) => {
let (cond, _cond_ty, ctx) = self.infer_expr(cond, ctx, next_where);
let (block, child_ctx) = self.infer_stmts_block(block, ctx.clone(), next_where);
let ctx = merge_ctxs(ctx, vec![child_ctx]);
(While(box_tup!(cond, block)), ctx)
}
Using(box ast::UsingStmt {
is_block_scoped,
has_await,
exprs,
block,
}) => {
let (pos, es) = exprs;
let (es, _es_tys, ctx) = self.infer_exprs(es, ctx, next_where);
let (block, ctx) = self.infer_stmts_block(block, ctx, next_where);
let using = Using(Box::new(ast::UsingStmt {
is_block_scoped: *is_block_scoped,
has_await: *has_await,
exprs: (pos.clone(), es),
block,
}));
(using, ctx)
}
For(box (e1s, e2_opt, e3s, stmts)) => {
let (e1s, _e1s_tys, ctx) = self.infer_exprs(e1s, ctx, next_where);
let (e2_opt, _e2_ty_opt, ctx) =
self.infer_expr_opt(e2_opt.as_ref(), ctx, next_where);
let (e3s, _e3s_tys, e3s_ctx) = self.infer_exprs(e3s, ctx.clone(), next_where);
let (stmts, stmt_ctx) = self.infer_stmts_block(stmts, ctx.clone(), next_where);
let ctx = merge_ctxs(ctx, vec![e3s_ctx, stmt_ctx]);
let for_ = For(box_tup!(e1s, e2_opt, e3s, stmts));
(for_, ctx)
}
Switch(box (e, cases, default_opt)) => {
let (e, _e_ty, ctx) = self.infer_expr(e, ctx, next_where);
let mut cases_out = Vec::with_capacity(cases.len());
let mut child_ctxs = Vec::with_capacity(cases.len());
for ast::Case(e, block) in cases {
let (e, _e_ty, e_ctx) = self.infer_expr(e, ctx.clone(), next_where);
let (block, child_ctx) = self.infer_stmts_block(block, e_ctx, next_where);
cases_out.push(ast::Case(e, block));
child_ctxs.push(child_ctx);
}
let default_opt = default_opt.as_ref().map(|ast::DefaultCase(pos, block)| {
let (block, ctx) = self.infer_stmts_block(block, ctx.clone(), next_where);
child_ctxs.push(ctx);
ast::DefaultCase(pos.clone(), block)
});
let ctx = merge_ctxs(ctx, child_ctxs);
let switch = Switch(box_tup!(e, cases_out, default_opt));
(switch, ctx)
}
Foreach(box (e, as_, stmts)) => {
let (e, _e_ty, ctx) = self.infer_expr(e, ctx, next_where);
let (as_, _as_ty, ctx) = self.infer_as_expr(as_, ctx, next_where);
let (stmts, child_ctx) = self.infer_stmts_block(stmts, ctx.clone(), next_where);
let ctx = merge_ctxs(ctx, vec![child_ctx]);
(Foreach(box_tup!(e, as_, stmts)), ctx)
}
Try(box (stmts, catches, finally)) => {
let (stmts, ctx) = self.infer_stmts_block(
stmts,
ctx,
Where {
under_try: true,
..next_where
},
);
let mut catches_out = Vec::with_capacity(catches.len());
let mut child_ctxs = Vec::with_capacity(catches.len());
for ast::Catch(name, lid, block) in catches.iter() {
let (block, catch_ctx) = self.infer_stmts_block(block, ctx.clone(), next_where);
let catch = ast::Catch(name.clone(), lid.clone(), block);
catches_out.push(catch);
child_ctxs.push(catch_ctx);
}
let (finally, finally_ctx) =
self.infer_stmts_finally_block(finally, ctx.clone(), next_where);
child_ctxs.push(finally_ctx);
let ctx = merge_ctxs(ctx, child_ctxs);
(Try(box_tup!(stmts, catches_out, finally)), ctx)
}
Noop => (Noop, ctx),
DeclareLocal(box (id, h, expr)) => {
if let Some(expr) = expr {
let (new_expr, _expr_ty, ctx) = self.infer_expr(expr, ctx, next_where);
(
DeclareLocal(box_tup!(id.clone(), h.clone(), Some(new_expr))),
ctx,
)
} else {
(st.clone(), ctx)
}
}
Block(stmts) => {
let (stmts, ctx) = self.infer_stmts_block(stmts, ctx, next_where);
(Block(stmts), ctx)
}
Markup(_) => (st.clone(), ctx),
AssertEnv(b) => (AssertEnv(b.clone()), ctx),
Match(..) => todo!("TODO(jakebailey): match statements"),
};
(ast::Stmt(pos.clone(), new_stmt), ctx)
}
fn infer_stmts_block(
&mut self,
stmts: &[ast::Stmt],
mut ctx: Ctx,
where_: Where<'_>,
) -> (ast::Block, Ctx) {
let mut out = Vec::with_capacity(stmts.len());
for stmt in stmts.iter() {
let (s, s_ctx) = self.infer_stmt(stmt, ctx, where_);
out.push(s);
ctx = s_ctx;
}
(ast::Block(out), ctx)
}
fn infer_stmts_finally_block(
&mut self,
stmts: &[ast::Stmt],
mut ctx: Ctx,
where_: Where<'_>,
) -> (ast::FinallyBlock, Ctx) {
let mut out = Vec::with_capacity(stmts.len());
for stmt in stmts.iter() {
let (s, s_ctx) = self.infer_stmt(stmt, ctx, where_);
out.push(s);
ctx = s_ctx;
}
(ast::FinallyBlock(out), ctx)
}
fn infer_a_field(
&mut self,
a_field: &ast::Afield,
ctx: Ctx,
where_: Where<'_>,
) -> (ast::Afield, Tyx, Ctx) {
match a_field {
aast::Afield::AFvalue(v) => {
let (v, _v_ty, ctx) = self.infer_expr(v, ctx, where_);
let a_field = aast::Afield::AFvalue(v);
(a_field, Tyx::Todo, ctx)
}
aast::Afield::AFkvalue(k, v) => {
let (k, _k_ty, ctx) = self.infer_expr(k, ctx, where_);
let (v, _v_ty, ctx) = self.infer_expr(v, ctx, where_);
let a_field = aast::Afield::AFkvalue(k, v);
(a_field, Tyx::Todo, ctx)
}
}
}
fn infer_as_expr(
&mut self,
as_: &ast::AsExpr,
ctx: Ctx,
where_: Where<'_>,
) -> (ast::AsExpr, Tyx, Ctx) {
use ast::AsExpr;
match as_ {
AsExpr::AsV(e) => {
let (e, _ty, ctx) = self.infer_expr(e, ctx, where_);
(AsExpr::AsV(e), Tyx::Todo, ctx)
}
AsExpr::AsKv(k, v) => {
let (k, _k_ty, ctx) = self.infer_expr(k, ctx, where_);
let (v, _v_ty, ctx) = self.infer_expr(v, ctx, where_);
(AsExpr::AsKv(k, v), Tyx::Todo, ctx)
}
AsExpr::AwaitAsV(pos, v) => {
let (v, _v_ty, ctx) = self.infer_expr(v, ctx, where_);
(AsExpr::AwaitAsV(pos.clone(), v), Tyx::Todo, ctx)
}
AsExpr::AwaitAsKv(pos, k, v) => {
let (k, _k_ty, ctx) = self.infer_expr(k, ctx, where_);
let (v, _v_ty, ctx) = self.infer_expr(v, ctx, where_);
(AsExpr::AwaitAsKv(pos.clone(), k, v), Tyx::Todo, ctx)
}
}
}
fn infer_fun(&mut self, fun: &ast::Fun_, ctx: Ctx, where_: Where<'_>) -> (ast::Fun_, Tyx, Ctx) {
// it's safe to ignore any `use` clause, since we treat undefined variables as of unknown type
let (fb_ast, _) = self.infer_stmts_block(&fun.body.fb_ast, ctx.clone(), where_);
let fun = ast::Fun_ {
body: ast::FuncBody { fb_ast },
..fun.clone()
};
(fun, Tyx::Todo, ctx)
}
fn infer_fun_def(&mut self, fun_def: &ast::FunDef) -> ast::FunDef {
let (fun, _fun_ty, _ctx) =
self.infer_fun(&fun_def.fun, Default::default(), Default::default());
ast::FunDef {
fun,
..fun_def.clone()
}
}
fn infer_class(&mut self, class: &ast::Class_) -> ast::Class_ {
let where_ = Where {
this_class_name: Some(&class.name.1), // potential optimization: reference the class rather than just the name
..Default::default()
};
let consts = class
.consts
.iter()
.map(|const_| {
use aast::ClassConstKind::*;
let kind = match &const_.kind {
CCAbstract(e_opt) => {
let (e_opt, _e_opt_ty, _ctx) = self.infer_expr_opt(
e_opt.as_ref(),
Default::default(),
Default::default(),
);
CCAbstract(e_opt)
}
CCConcrete(e) => {
let (e, _e_ty, _ctx) = self.infer_expr(e, Default::default(), where_);
CCConcrete(e)
}
};
ast::ClassConst {
kind,
..const_.clone()
}
})
.collect();
let methods = class
.methods
.iter()
.map(|meth| {
let (fb_ast, _ctx) =
self.infer_stmts_block(&meth.body.fb_ast, Default::default(), where_);
let body = ast::FuncBody { fb_ast };
ast::Method_ {
body,
..meth.clone()
}
})
.collect();
let vars = class
.vars
.iter()
.map(|var| {
let (expr, _expr_ty, _ctx) =
self.infer_expr_opt(var.expr.as_ref(), Default::default(), Default::default());
ast::ClassVar {
expr,
..var.clone()
}
})
.collect();
ast::Class_ {
consts,
methods,
vars,
..class.clone()
}
}
fn infer_typedef(&self, td: &ast::Typedef) -> ast::Typedef {
td.clone()
}
fn type_gconst(&mut self, gc: &ast::Gconst) -> ast::Gconst {
// future-proofing: currently has no effect, since const expressions are limited
let (value, _v_ty, _ctx) =
self.infer_expr(&gc.value, Default::default(), Default::default());
ast::Gconst {
value,
..gc.clone()
}
}
fn infer_type_def(&mut self, d: &ast::Def) -> ast::Def {
use aast::Def::*;
match d {
Fun(box fd) => Fun(Box::new(self.infer_fun_def(fd))),
Class(box c_) => Class(Box::new(self.infer_class(c_))),
Stmt(box stmt) => {
let (stmt, _ctx) = self.infer_stmt(stmt, Default::default(), Default::default());
Stmt(Box::new(stmt))
}
Typedef(box td) => Typedef(Box::new(self.infer_typedef(td))),
Constant(box gconst) => Constant(Box::new(self.type_gconst(gconst))),
Namespace(b) => Namespace(b.clone()),
NamespaceUse(b) => NamespaceUse(b.clone()),
SetNamespaceEnv(b) => SetNamespaceEnv(b.clone()),
FileAttributes(b) => FileAttributes(b.clone()),
Module(b) => Module(b.clone()),
SetModule(b) => SetModule(b.clone()),
}
}
fn get_prop_type(
&self,
class_name: &str,
prop_name: &str,
prop_scope: ClassScopeKind,
pos: &Pos,
) -> Option<Tyx> {
let shallow_class = self.get_shallow_class(class_name, pos)?;
let props = match prop_scope {
ClassScopeKind::Static => shallow_class.sprops,
ClassScopeKind::Nonstatic => shallow_class.props,
};
let prop = props.iter().find(|prop| prop.name.1 == prop_name)?;
let ty = tyx::convert(&prop.type_.1);
let ty = if prop.flags.is_readonly() {
Tyx::Readonly(Box::new(ty))
} else {
ty
};
Some(ty)
}
fn get_method_type(
&self,
class_name: &str,
method_name: &str,
method_scope: ClassScopeKind,
pos: &Pos,
) -> Option<tyx::FunType> {
let shallow_class = self.get_shallow_class(class_name, pos)?;
let methods = match method_scope {
ClassScopeKind::Static => shallow_class.static_methods,
ClassScopeKind::Nonstatic => shallow_class.methods,
};
let method = methods.iter().find(|method| method.name.1 == method_name)?;
tyx::ty_to_fun_type_opt(&method.type_.1)
}
// TODO: look up in parent classes using folded decls
fn get_shallow_class(&self, class_name: &str, pos: &Pos) -> Option<&'_ ShallowClass<'_>> {
match self.decl_provider.type_decl(class_name, 1) {
Ok(decl_provider::TypeDecl::Class(shallow_class)) => Some(shallow_class),
Ok(_) => None, // reachable if TypeDecl::Typedef, which is currently not allowed to be an alias for a class
Err(Error::NotFound) => None,
Err(err @ Error::Bincode(_)) => {
panic!(
"Internal error when attempting to read the type of class '{class_name}' at {pos:?}. {err}"
)
}
}
}
fn get_fun_decl(&self, id: &ast::Id, pos: &Pos) -> Option<tyx::FunType> {
let name = id.name();
match self.decl_provider.func_decl(name) {
Ok(FunElt {
type_: oxidized_by_ref::typing_defs::Ty(_, ty_),
..
}) => tyx::ty_to_fun_type_opt(ty_),
Err(Error::NotFound) => None,
Err(err @ Error::Bincode(_)) => {
panic!(
"Internal error when attempting to read the type of callable '{name}' at {pos:?}. {err}"
)
}
}
}
}
fn merge_ctxs(mut parent: Ctx, children: Vec<Ctx>) -> Ctx {
for child in children {
for (var, ty) in child.into_iter() {
match parent.entry(var) {
Entry::Occupied(mut entry) => {
let existing_ty = entry.get_mut();
*existing_ty =
subtype::join(Cow::Borrowed(existing_ty), Cow::Owned(ty)).into_owned();
}
Entry::Vacant(entry) => {
entry.insert(ty);
}
}
}
}
parent
}
fn readonly_wrap_expr_(pos: Pos, expr_: ast::Expr_) -> ast::Expr_ {
aast::Expr_::ReadonlyExpr(Box::new(ast::Expr((), pos, expr_)))
}
fn returns_readonly(ft: &tyx::FunType) -> bool {
matches!(ft.ret, Tyx::Readonly(_))
}
fn class_id_to_name<'c>(class_id: &'c aast::ClassId<(), ()>, where_: Where<'c>) -> Option<&'c str> {
use aast::ClassId_::*;
let self_class_name = where_.this_class_name;
let class_name: Option<&str> = match &class_id.2 {
CI(ast_defs::Id(_, class_name)) => Some(class_name),
CIexpr(ast::Expr(_, _, aast::Expr_::Id(box ast_defs::Id(_, class_name)))) => {
Some(class_name) // might be something magic like "self"
}
CIself => self_class_name,
_ => None, // TODO: handle more cases, such as CIParent
};
match class_name? {
naming_special_names_rust::classes::SELF => self_class_name,
// TODO: handle more cases
_ => class_name,
}
}
/// # Panics
/// Panics if a decl provider returns any error other than [`decl_provider::Error::NotFound`];
pub fn infer<'d>(
prog: &ast::Program,
decl_provider: Arc<dyn DeclProvider<'d> + 'd>,
) -> ast::Program {
let mut infer: Infer<'d> = Infer {
decl_provider,
stats: Default::default(),
};
let res = ast::Program(
prog.iter()
.map(|def| infer.infer_type_def(def))
.collect::<Vec<_>>(),
);
if env::var("HACKC_INTERNAL_LOG_READONLY_TDB_DIAGNOSTICS")
.map(|s| s.parse::<u8>().unwrap_or_default())
.unwrap_or_default()
== 1
{
let Stats {
original_readonlys,
redundant_readonlys,
added_readonlys,
} = infer.stats;
eprintln!(
"original_readonlys: {original_readonlys} redundant_readonlys: {redundant_readonlys} added_readonlys: {added_readonlys}",
);
}
res
} |
Rust | hhvm/hphp/hack/src/hackc/types/subtype.rs | use std::borrow::Borrow;
use std::borrow::Cow;
use crate::tyx::Tyx;
pub(crate) fn join<'a>(ty1: Cow<'a, Tyx>, ty2: Cow<'a, Tyx>) -> Cow<'a, Tyx> {
use Tyx::*;
match (ty1.borrow(), ty2.borrow()) {
(t1, t2) if equiv(t1, t2) => ty1,
(Bottom, _) => ty2,
(_, Bottom) => ty1,
_ => Cow::Owned(Mixed),
}
}
// not very sophisiticated
pub(crate) fn equiv(t1: &Tyx, t2: &Tyx) -> bool {
t1 == t2
} |
Rust | hhvm/hphp/hack/src/hackc/types/tyx.rs | use oxidized_by_ref::typing_defs;
use oxidized_by_ref::typing_defs_core::Exact;
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) enum Tyx {
Fun(Box<FunType>),
// Class{class_name: String},
Object {
class_name: String,
},
GiveUp, // We're not sure what the type is
Todo, // should be gone later
#[allow(dead_code)]
Bottom, // like empty union in hh
Primitive,
Mixed, // top
Readonly(Box<Tyx>),
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct FunType {
pub ret: Tyx,
}
/// Lossy conversion, falls back to Ty::Mixed
/// no `From` implementation because this is a reference->owned conversion rather than owned->owned
pub(crate) fn convert(ty_: &typing_defs::Ty_<'_>) -> Tyx {
use typing_defs::Ty_;
// TODO: can get more expressivity if we support Tapply, Tnewtype, soundly-approximated refinements
match ty_ {
Ty_::Tthis => Tyx::Mixed,
Ty_::Tapply(_) => Tyx::Mixed,
Ty_::Trefinement(_) => Tyx::Mixed,
Ty_::Tmixed => Tyx::Mixed,
Ty_::Tlike(_) => Tyx::Mixed,
Ty_::Tdynamic => Tyx::GiveUp,
Ty_::Toption(_) => Tyx::Mixed,
Ty_::Tprim(_) => Tyx::Primitive,
Ty_::Tfun(_) => {
let converted_ft = ty_to_fun_type_opt(ty_).unwrap();
Tyx::Fun(Box::new(converted_ft))
}
Ty_::Ttuple(_) => Tyx::Mixed,
Ty_::Tshape(_) => Tyx::Mixed,
Ty_::Tvar(_) => Tyx::Mixed,
Ty_::Tgeneric(_) => Tyx::Mixed,
Ty_::Tunion(ty_s) => {
if ty_s.is_empty() {
Tyx::Bottom
} else {
Tyx::Mixed
}
}
Ty_::Tintersection(_) => Tyx::Mixed,
Ty_::TunappliedAlias(_) => Tyx::Mixed,
Ty_::Tnewtype(_) => Tyx::Mixed,
Ty_::Tclass(((_, class_name), Exact::Exact, _ty_args)) => Tyx::Object {
class_name: class_name.to_string(),
},
Ty_::Tclass((_, Exact::Nonexact(_refinements), _ty_args)) => Tyx::Mixed,
Ty_::Tneg(_) => Tyx::Mixed,
_ => Tyx::Mixed,
}
}
pub(crate) fn ty_to_fun_type_opt(ty_: &typing_defs::Ty_<'_>) -> Option<FunType> {
match ty_ {
typing_defs::Ty_::Tfun(ft) => {
let ret = convert(&ft.ret.type_.1);
let ret = if ft
.flags
.contains(typing_defs::FunTypeFlags::RETURNS_READONLY)
{
Tyx::Readonly(Box::new(ret))
} else {
ret
};
Some(FunType { ret })
}
_ => None,
}
} |
TOML | hhvm/hphp/hack/src/hackc/types/cargo/types/Cargo.toml | # @generated by autocargo
[package]
name = "types"
version = "0.0.0"
edition = "2021"
[lib]
path = "../../lib.rs"
[dependencies]
decl_provider = { version = "0.0.0", path = "../../../decl_provider" }
hash = { version = "0.0.0", path = "../../../../utils/hash" }
hh_autoimport_rust = { version = "0.0.0", path = "../../../../parser/cargo/hh_autoimport" }
itertools = "0.10.3"
lazy_static = "1.4"
naming_special_names_rust = { version = "0.0.0", path = "../../../../naming" }
oxidized = { version = "0.0.0", path = "../../../../oxidized" }
oxidized_by_ref = { version = "0.0.0", path = "../../../../oxidized_by_ref" }
parser_core_types = { version = "0.0.0", path = "../../../../parser/cargo/core_types" } |
Rust | hhvm/hphp/hack/src/hackc/utils/stack_depth.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::VecDeque;
use ffi::Just;
use hhbc::DefaultValue;
use hhbc::Instruct;
use hhbc::Label;
use hhbc::Opcode;
use hhbc::Param;
use hhbc::Pseudo;
use hhbc::Targets;
use hhbc_gen::InstrFlags;
use hhbc_gen::OpcodeData;
use hhbc_gen::Outputs;
use log::debug;
use newtype::newtype_int;
use newtype::IdVec;
use thiserror::Error;
pub type Result<T, E = Error> = std::result::Result<T, E>;
/// Given an hhbc::Body compute the maximum stack needed when executing that
/// body. In general dead code will not be tracked however all catch blocks are
/// assumed to start out live.
pub fn compute_stack_depth(params: &[Param<'_>], body_instrs: &[Instruct<'_>]) -> Result<usize> {
let mut csd = ComputeStackDepth {
body_instrs,
labels: Default::default(),
work: Default::default(),
handled: Default::default(),
max_depth: 0,
cur_depth: 0,
};
csd.run(params, body_instrs)?;
Ok(csd.max_depth as usize)
}
#[derive(Error, Debug)]
pub enum Error {
#[error("back edge stack depth mismatch")]
MismatchDepth,
#[error("stack underflow")]
StackUnderflow,
#[error("stack should be 0 after RetC or RetM")]
UnexpectedExitWithStack,
#[error("stack should be 1 after resume")]
UnexpectedStackAfterResume,
#[error("unexpected end of function")]
UnexpectedFunctionEnd,
#[error("unknown label")]
UnknownLabel,
}
// An Addr is a newtype wrapper for the index into a Body's Instruct Vec.
newtype_int!(Addr, u32, AddrMap, AddrSet);
impl Addr {
fn next(&mut self) {
self.0 += 1;
}
}
struct PendingWork {
addr: Addr,
depth: u32,
}
impl PendingWork {
fn new(addr: Addr, depth: u32) -> Self {
PendingWork { addr, depth }
}
}
struct ComputeStackDepth<'a> {
body_instrs: &'a [Instruct<'a>],
labels: IdVec<Label, Addr>,
work: VecDeque<PendingWork>,
/// Mapping from handled label addresses to their depth at that
/// location. This is a sparse map with entries only at label Addrs.
handled: AddrMap<u32>,
max_depth: u32,
cur_depth: u32,
}
impl ComputeStackDepth<'_> {
fn run(&mut self, params: &[Param<'_>], body_instrs: &[Instruct<'_>]) -> Result<()> {
debug!("ComputeStackDepth::run");
self.precompute(body_instrs);
// The "normal" entrypoint.
self.work.push_back(PendingWork::new(Addr(0), 0));
// A depth-0 entrypoint for each default value.
for param in params {
if let Just(DefaultValue { label, .. }) = param.default_value.as_ref() {
let addr = self.labels[*label];
self.work.push_back(PendingWork::new(addr, 0));
}
}
while let Some(PendingWork { addr, depth }) = self.work.pop_front() {
self.process_block(addr, depth)?;
}
Ok(())
}
/// Process a block of execution.
fn process_block(&mut self, mut addr: Addr, depth: u32) -> Result<()> {
debug!(" -- block at {addr:?}, depth {depth}");
self.cur_depth = depth;
loop {
if let Some(instr) = self.body_instrs.get(addr.0 as usize) {
if !matches!(instr, Instruct::Pseudo(Pseudo::SrcLoc(..))) {
debug!(
" {addr:?}, {depth}: instr {instr:?}",
depth = self.cur_depth
);
}
let finished = self.process_instruct(addr, instr)?;
addr.next();
if finished {
break;
}
} else {
// We fell off the end of the function - this isn't allowed!
return Err(Error::UnexpectedFunctionEnd);
}
}
Ok(())
}
/// Push `n` values onto the stack.
fn push_n(&mut self, n: u32) {
self.cur_depth += n;
self.max_depth = std::cmp::max(self.max_depth, self.cur_depth);
}
/// Pop `n` values off the stack.
fn pop_n(&mut self, n: u32) -> Result<()> {
if n > self.cur_depth {
return Err(Error::StackUnderflow);
}
self.cur_depth -= n;
Ok(())
}
/// Register a control-flow jump to a new address. This doesn't
/// (automatically) termintate the current block of execution.
fn jmp(&mut self, target: Addr) -> Result<()> {
if let Some(expected_depth) = self.handled.get(&target) {
// We already handled this target - it had better have the same
// depth as we saw last time.
if self.cur_depth != *expected_depth {
return Err(Error::MismatchDepth);
}
} else {
self.work
.push_back(PendingWork::new(target, self.cur_depth));
}
Ok(())
}
/// Register a control-flow jump to a new label. This doesn't
/// (automatically) terminate the current block of execution.
fn jmp_label(&mut self, target: Label) -> Result<()> {
let target = self.labels.get(target).ok_or(Error::UnknownLabel)?;
self.jmp(*target)
}
/// Process an Instruct. Returns `true` if this Instruct ends the current block.
fn process_instruct(&mut self, addr: Addr, instr: &Instruct<'_>) -> Result<bool> {
let end_block = match instr {
Instruct::Pseudo(
Pseudo::Break
| Pseudo::Comment(_)
| Pseudo::Continue
| Pseudo::SrcLoc(..)
| Pseudo::TryCatchBegin
| Pseudo::TryCatchEnd
| Pseudo::TryCatchMiddle
| Pseudo::TypedValue(_),
) => false,
Instruct::Pseudo(Pseudo::Label(_)) => {
if let Some(old_depth) = self.handled.insert(addr, self.cur_depth) {
if old_depth != self.cur_depth {
return Err(Error::MismatchDepth);
}
// We've already handled this label - stop processing this
// block.
true
} else {
false
}
}
Instruct::Opcode(Opcode::MemoGet(target, _)) => {
// MemoGet jumps to its target BEFORE pushing a value.
self.jmp_label(*target)?;
self.push_n(1);
false
}
Instruct::Opcode(Opcode::MemoGetEager([target0, target1], _, _)) => {
// MemoGetEager jumps to its first target BEFORE pushing a value.
self.jmp_label(*target0)?;
self.push_n(1);
// ... but jumps to its second AFTER pushing a value.
self.jmp_label(*target1)?;
false
}
Instruct::Opcode(opcode) => {
// "standard" opcode handling
let opcode_data = lookup_data_for_opcode(opcode);
// Pop inputs.
let n = opcode.num_inputs();
self.pop_n(n as u32)?;
// Push outputs.
let n = num_outputs(opcode, opcode_data);
self.push_n(n);
if opcode_data.flags.contains(InstrFlags::CF) {
// If the Instruct has a control flow make sure to jump to
// the targets.
let targets = opcode.targets();
for target in targets {
self.jmp_label(*target)?;
}
}
match opcode {
Opcode::RetC | Opcode::RetCSuspended | Opcode::RetM(_) | Opcode::NativeImpl => {
// Stack depth should be 0 after RetC or RetM.
if self.cur_depth != 0 {
return Err(Error::UnexpectedExitWithStack);
}
}
Opcode::CreateCont | Opcode::Await | Opcode::Yield | Opcode::YieldK => {
// Stack depth should be 1 after resume from suspend.
if self.cur_depth != 1 {
return Err(Error::UnexpectedStackAfterResume);
}
}
_ => {}
}
// If the Instruct is a terminator make sure to end this block
// here.
opcode_data.flags.contains(InstrFlags::TF)
}
};
Ok(end_block)
}
/// Precompute label addresses and catch addresses.
fn precompute(&mut self, body_instrs: &[Instruct<'_>]) {
for (idx, instr) in body_instrs.iter().enumerate() {
let addr = Addr(idx as u32);
match instr {
Instruct::Pseudo(Pseudo::Label(label)) => {
if self.labels.len() <= label.as_usize() {
self.labels.resize(label.as_usize() + 1, Addr(0));
}
self.labels[*label] = addr;
}
Instruct::Pseudo(Pseudo::TryCatchMiddle) => {
// Add the catch block as a pending action.
// Catch frames always start with just the thrown object on the stack.
self.work.push_back(PendingWork::new(addr, 1));
}
_ => {}
}
}
}
}
fn num_outputs(opcode: &Opcode<'_>, opcode_data: &OpcodeData) -> u32 {
match &opcode_data.outputs {
Outputs::NOV => 0,
Outputs::Fixed(n) => n.len() as u32,
Outputs::FCall => match opcode {
Opcode::FCallClsMethod(fca, _, _)
| Opcode::FCallClsMethodM(fca, _, _, _)
| Opcode::FCallClsMethodD(fca, _, _)
| Opcode::FCallClsMethodS(fca, _, _)
| Opcode::FCallClsMethodSD(fca, _, _, _)
| Opcode::FCallCtor(fca, _)
| Opcode::FCallFunc(fca)
| Opcode::FCallFuncD(fca, _)
| Opcode::FCallObjMethod(fca, _, _)
| Opcode::FCallObjMethodD(fca, _, _, _) => fca.num_rets,
_ => unreachable!(),
},
}
}
fn lookup_data_for_opcode(opcode: &Opcode<'_>) -> &'static OpcodeData {
hhbc_gen::opcode_data().get(opcode.variant_index()).unwrap()
} |
Rust | hhvm/hphp/hack/src/hackc/utils/string_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 std::borrow::Cow;
use std::cell::Cell;
use bstr::BStr;
use bstr::ByteSlice;
use escaper::*;
use lazy_static::lazy_static;
use naming_special_names_rust::classes as ns_classes;
use naming_special_names_rust::members;
use regex::Regex;
lazy_static! {
static ref HH_NS_RE: Regex = Regex::new(r"^\\?HH\\").unwrap();
static ref NS_RE: Regex = Regex::new(r".*\\").unwrap();
static ref TYPE_RE: Regex = Regex::new(r"<.*>").unwrap();
}
#[derive(Clone)]
pub struct GetName {
string: Vec<u8>,
unescape: fn(String) -> String,
}
impl GetName {
pub fn new(string: Vec<u8>, unescape: fn(String) -> String) -> GetName {
GetName { string, unescape }
}
pub fn get(&self) -> &Vec<u8> {
&self.string
}
#[allow(clippy::inherent_to_string)]
pub fn to_string(&self) -> String {
String::from_utf8_lossy(&self.string).to_string()
}
pub fn to_unescaped_string(&self) -> String {
let unescape = self.unescape;
unescape(self.to_string())
}
}
impl std::fmt::Debug for GetName {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "GetName {{ string: {}, unescape:? }}", self.to_string())
}
}
thread_local!(static MANGLE_XHP_MODE: Cell<bool> = Cell::new(true));
pub fn without_xhp_mangling<T>(f: impl FnOnce() -> T) -> T {
MANGLE_XHP_MODE.with(|cur| {
let old = cur.replace(false);
let ret = f();
cur.set(old); // use old instead of true to support nested calls in the same thread
ret
})
}
pub fn is_xhp(name: &str) -> bool {
name.chars().next().map_or(false, |c| c == ':')
}
pub fn clean(s: &str) -> &str {
if is_xhp(s) { strip_colon(s) } else { s }
}
fn strip_colon(s: &str) -> &str {
s.trim_start_matches(':')
}
fn ignore_id(name: &str) -> bool {
name.starts_with("Closure$")
}
pub fn mangle_xhp_id(mut name: String) -> String {
if !ignore_id(&name) && MANGLE_XHP_MODE.with(|x| x.get()) {
if is_xhp(&name) {
name.replace_range(..1, "xhp_")
}
name.replace(':', "__").replace('-', "_")
} else {
name
}
}
fn unmangle_xhp_id(name: &str) -> String {
if name.starts_with("xhp_") {
format!(
":{}",
lstrip(name, "xhp_").replace("__", ":").replace('_', "-")
)
} else {
name.replace("__", ":").replace('_', "-")
}
}
pub fn mangle(mut name: String) -> String {
if !ignore_id(&name) {
if let Some(pos) = name.rfind('\\') {
name.replace_range(pos + 1.., &mangle_xhp_id(name[pos + 1..].to_string()))
} else {
name = mangle_xhp_id(name);
}
}
name
}
pub fn unmangle(name: String) -> String {
if ignore_id(&name) {
return name;
}
let ids = name.split('\\').collect::<Vec<_>>();
match ids.split_last() {
None => String::new(),
Some((last, rest)) => {
if rest.is_empty() {
unmangle_xhp_id(last)
} else {
format!("{}\\{}", rest.join("\\"), unmangle_xhp_id(last))
}
}
}
}
pub fn quote_string(s: &str) -> String {
format!("\"{}\"", escape(s))
}
pub fn prefix_namespace(n: &str, s: &str) -> String {
format!("{}\\{}", n, s)
}
pub fn strip_global_ns(s: &str) -> &str {
if let Some(rest) = s.strip_prefix('\\') {
rest
} else {
s
}
}
pub fn strip_global_ns_bslice(s: &[u8]) -> &[u8] {
s.strip_prefix(b"\\").unwrap_or(s)
}
// Strip zero or more chars followed by a backslash
pub fn strip_ns(s: &str) -> &str {
s.rfind('\\').map_or(s, |i| &s[i + 1..])
}
// Strip zero or more chars followed by a backslash
pub fn strip_ns_bstr(s: &BStr) -> &BStr {
s.rfind("\\").map_or(s, |i| &s[i + 1..])
}
// Remove \HH\ or HH\ preceding a string
pub fn strip_hh_ns(s: &str) -> Cow<'_, str> {
HH_NS_RE.replace(s, "")
}
pub fn has_ns(s: &str) -> bool {
NS_RE.is_match(s)
}
pub fn strip_type_list(s: &str) -> Cow<'_, str> {
TYPE_RE.replace_all(s, "")
}
pub fn cmp(s1: &str, s2: &str, case_sensitive: bool, ignore_ns: bool) -> bool {
fn canon(s: &str, ignore_ns: bool) -> &str {
if ignore_ns { strip_ns(s) } else { s }
}
let s1 = canon(s1, ignore_ns);
let s2 = canon(s2, ignore_ns);
if case_sensitive {
s1 == s2
} else {
s1.eq_ignore_ascii_case(s2)
}
}
pub fn is_self(s: impl AsRef<str>) -> bool {
s.as_ref().eq_ignore_ascii_case(ns_classes::SELF)
}
pub fn is_parent(s: impl AsRef<str>) -> bool {
s.as_ref().eq_ignore_ascii_case(ns_classes::PARENT)
}
pub fn is_static(s: impl AsRef<str>) -> bool {
s.as_ref().eq_ignore_ascii_case(ns_classes::STATIC)
}
pub fn is_class(s: impl AsRef<str>) -> bool {
s.as_ref().eq_ignore_ascii_case(members::M_CLASS)
}
pub fn mangle_meth_caller(mangled_cls_name: &str, f_name: &str) -> String {
format!("\\MethCaller${}${}", mangled_cls_name, f_name)
}
pub fn lstrip<'a>(s: &'a str, p: &str) -> &'a str {
s.strip_prefix(p).unwrap_or(s)
}
pub fn lstrip_bslice<'a>(s: &'a [u8], p: &[u8]) -> &'a [u8] {
s.strip_prefix(p).unwrap_or(s)
}
pub mod types {
pub fn fix_casing(s: &str) -> &str {
match s.to_lowercase().as_str() {
"vector" => "Vector",
"immvector" => "ImmVector",
"set" => "Set",
"immset" => "ImmSet",
"map" => "Map",
"immmap" => "ImmMap",
"pair" => "Pair",
_ => s,
}
}
}
/* Integers are represented as strings */
pub mod integer {
pub fn to_decimal(s: &str) -> Result<String, ocaml_helper::ParseIntError> {
/* Don't accidentally convert 0 to 0o */
let r = if s.len() > 1
&& s.as_bytes()[0] == b'0'
&& s.as_bytes()[1] >= b'0'
&& s.as_bytes()[1] <= b'9'
{
ocaml_helper::int_of_string_wrap(format!("0o{}", &s[1..]).as_bytes())
} else {
ocaml_helper::int_of_string_wrap(s.as_bytes())
};
r.map(|n| n.to_string())
}
}
pub mod float {
fn sprintf(f: f64) -> Option<String> {
const BUF_SIZE: usize = 256;
let format = "%.17g\0";
let mut buffer = [0u8; BUF_SIZE];
let n = unsafe {
libc::snprintf(
buffer.as_mut_ptr() as *mut libc::c_char,
BUF_SIZE,
format.as_ptr() as *const libc::c_char,
f,
) as usize
};
if n >= BUF_SIZE {
None
} else {
String::from_utf8(buffer[..n].to_vec()).ok()
}
}
pub fn to_string(f: impl Into<f64>) -> String {
let f = f.into();
// or_else should not happen, but just in case it does fall back
// to Rust native formatting
let res = sprintf(f).unwrap_or_else(|| f.to_string());
match res.as_ref() {
"-nan" => naming_special_names_rust::math::NAN.to_string(),
"nan" => naming_special_names_rust::math::NAN.to_string(),
"-inf" => naming_special_names_rust::math::NEG_INF.to_string(),
"inf" => naming_special_names_rust::math::INF.to_string(),
_ => res,
}
}
}
pub mod locals {
pub fn strip_dollar(s: &str) -> &str {
if !s.is_empty() && s.as_bytes()[0] == b'$' {
&s[1..]
} else {
s
}
}
}
pub mod classes {
pub fn mangle_class(prefix: &str, scope: &str, idx: u32) -> String {
if idx == 1 {
format!("{}${}", prefix, scope)
} else {
format!("{}${}#{}", prefix, scope, idx)
}
}
}
pub mod closures {
pub fn mangle_closure(scope: &str, idx: u32) -> String {
super::classes::mangle_class("Closure", scope, idx)
}
/* Closure classes have names of the form
* Closure$ scope ix ; num
* where
* scope ::=
* <function-name>
* | <class-name> :: <method-name>
* |
* ix ::=
* # <digits>
*/
pub fn unmangle_closure(mangled_name: &str) -> Option<&str> {
if is_closure_name(mangled_name) {
let prefix_length = "Closure$".chars().count();
match mangled_name.find('#') {
Some(pos) => Some(&mangled_name[prefix_length..pos]),
None => Some(&mangled_name[prefix_length..]),
}
} else {
None
}
}
pub fn is_closure_name(s: &str) -> bool {
s.starts_with("Closure$")
}
}
pub mod reified {
pub static PROP_NAME: &str = "86reified_prop";
pub static INIT_METH_NAME: &str = "86reifiedinit";
pub static INIT_METH_PARAM_NAME: &str = "$__typestructures";
pub static GENERICS_LOCAL_NAME: &str = "$0ReifiedGenerics";
pub static CAPTURED_PREFIX: &str = "$__captured$reifiedgeneric$";
pub fn reified_generic_captured_name(is_fun: bool, i: usize) -> String {
let type_ = if is_fun { "function" } else { "class" };
// to_string() due to T52404885
format!("$__captured$reifiedgeneric${}${}", type_, i)
}
pub fn mangle_reified_param(no_dollar: bool, s: &str) -> String {
format!("{}__reified${}", if no_dollar { "" } else { "$" }, s)
}
pub fn captured_name(is_fun: bool, i: usize) -> String {
format!(
"{}{}${}",
CAPTURED_PREFIX,
if is_fun { "function" } else { "class" },
i
)
}
pub fn is_captured_generic(id: &str) -> Option<(bool, u32)> {
if id.starts_with(CAPTURED_PREFIX) {
if let [name, i] = id
.trim_start_matches(CAPTURED_PREFIX)
.splitn(2, '$')
.collect::<Vec<_>>()
.as_slice()
{
let is_captured = match *name {
"function" => true,
"class" => false,
_ => return None,
};
let captured_id = i.parse();
if let Ok(captured) = captured_id {
return Some((is_captured, captured));
};
}
};
None
}
}
pub mod coeffects {
#[allow(clippy::redundant_static_lifetimes)]
pub static LOCAL_NAME: &'static str = "$0Coeffects";
#[allow(clippy::redundant_static_lifetimes)]
pub static CALLER: &'static str = "86caller";
}
#[cfg(test)]
mod string_utils_tests {
use pretty_assertions::assert_eq;
#[test]
fn quote_string_test() {
let some_string = "test";
assert_eq!(super::quote_string(some_string), "\"test\"");
}
#[test]
fn prefix_namespace_test() {
let namespace = "ns";
let some_string = "test";
assert_eq!(super::prefix_namespace(namespace, some_string), "ns\\test");
}
#[test]
fn strip_global_ns_test() {
let some_string = "\\test";
let another_string = "\\\\";
assert_eq!(super::strip_global_ns(some_string), "test");
assert_eq!(super::strip_global_ns(another_string), "\\");
let some_string = b"\\test";
let another_string = b"\\\\";
assert_eq!(super::strip_global_ns_bslice(some_string), b"test");
assert_eq!(super::strip_global_ns_bslice(another_string), b"\\");
}
#[test]
fn strip_ns_test() {
let with_ns = "ns1\\test";
let without_ns = "test";
assert_eq!(super::strip_ns(with_ns), "test");
assert_eq!(super::strip_ns(without_ns), without_ns);
}
#[test]
fn strip_hh_ns() {
let with_ns = "HH\\test";
let without_ns = "test";
assert_eq!(super::strip_ns(with_ns), "test");
assert_eq!(super::strip_ns(without_ns), without_ns);
}
#[test]
fn strip_hh_ns_2() {
let with_ns = "\\HH\\test";
let without_ns = "test";
assert_eq!(super::strip_ns(with_ns), "test");
assert_eq!(super::strip_ns(without_ns), without_ns);
}
#[test]
fn has_ns_test() {
let with_ns = "\\test";
let without_ns = "test";
assert!(super::has_ns(with_ns));
assert!(!super::has_ns(without_ns));
}
#[test]
fn strip_type_list_test() {
let s = "MutableMap<Tk, Tv>";
assert_eq!(super::strip_type_list(s).into_owned(), "MutableMap");
}
#[test]
fn cmp_test() {
let s1 = "ns1\\s1";
let s1_uppercase = "NS1\\S1";
let ns2_s1 = "ns2\\s1";
let ns2_s1_uppercase = "NS2\\S1";
let ns2_s2 = "ns2\\s2";
assert!(super::cmp(s1, s1_uppercase, false, false));
assert!(!super::cmp(s1, s1_uppercase, true, false));
assert!(super::cmp(s1, s1_uppercase, false, true));
assert!(!super::cmp(s1, s1_uppercase, true, true));
assert!(!super::cmp(s1, ns2_s1, false, false));
assert!(!super::cmp(s1, ns2_s1, true, false));
assert!(super::cmp(s1, ns2_s1, false, true));
assert!(super::cmp(s1, ns2_s1, true, true));
assert!(!super::cmp(s1, ns2_s1_uppercase, false, false));
assert!(!super::cmp(s1, ns2_s1_uppercase, true, false));
assert!(super::cmp(s1, ns2_s1_uppercase, false, true));
assert!(!super::cmp(s1, ns2_s1_uppercase, true, true));
assert!(!super::cmp(s1, ns2_s2, false, false));
assert!(!super::cmp(s1, ns2_s2, true, false));
assert!(!super::cmp(s1, ns2_s2, false, true));
assert!(!super::cmp(s1, ns2_s2, true, true));
}
#[test]
fn is_self_test() {
let s1 = "self";
let s2 = "not_self";
assert!(super::is_self(s1));
assert!(!super::is_self(s2));
}
#[test]
fn is_parent_test() {
let s1 = "parent";
let s2 = "not_parent";
assert!(super::is_parent(s1));
assert!(!super::is_parent(s2));
}
#[test]
fn is_static_test() {
let s1 = "static";
let s2 = "not_static";
assert!(super::is_static(s1));
assert!(!super::is_static(s2));
}
#[test]
fn is_class_test() {
let s1 = "class";
let s2 = "not_a_class";
assert!(super::is_class(s1));
assert!(!super::is_class(s2));
}
#[test]
fn mangle_meth_caller_test() {
let cls = "SomeClass";
let f = "some_function";
assert_eq!(
super::mangle_meth_caller(cls, f),
"\\MethCaller$SomeClass$some_function"
);
}
#[test]
fn mangle_test_1() {
assert_eq!(
super::mangle(":foo:bar-and-baz".into()),
"xhp_foo__bar_and_baz"
);
}
#[test]
fn mangle_test_2() {
assert_eq!(super::mangle("\\:base".into()), "\\xhp_base");
}
#[test]
fn mangle_test_3() {
assert_eq!(
super::mangle("\\NS1\\NS2\\:base".into()),
"\\NS1\\NS2\\xhp_base"
);
}
mod types {
mod fix_casing {
macro_rules! test_case {
($name: ident, $input: expr, $expected: expr) => {
#[test]
fn $name() {
assert_eq!(crate::types::fix_casing($input), $expected);
}
};
}
test_case!(lowercase_vector, "vector", "Vector");
test_case!(mixedcase_vector, "vEcTor", "Vector");
test_case!(uppercase_vector, "VECTOR", "Vector");
test_case!(lowercase_immvector, "immvector", "ImmVector");
test_case!(mixedcase_immvector, "immvEcTor", "ImmVector");
test_case!(uppercase_immvector, "IMMVECTOR", "ImmVector");
test_case!(lowercase_set, "set", "Set");
test_case!(mixedcase_set, "SeT", "Set");
test_case!(uppercase_set, "SET", "Set");
test_case!(lowercase_immset, "immset", "ImmSet");
test_case!(mixedcase_immset, "ImMSeT", "ImmSet");
test_case!(uppercase_immset, "IMMSET", "ImmSet");
test_case!(lowercase_map, "map", "Map");
test_case!(mixedcase_map, "MaP", "Map");
test_case!(uppercase_map, "MAP", "Map");
test_case!(lowercase_immmap, "immmap", "ImmMap");
test_case!(mixedcase_immmap, "immMaP", "ImmMap");
test_case!(uppercase_immmap, "IMMMAP", "ImmMap");
test_case!(lowercase_pair, "pair", "Pair");
test_case!(mixedcase_pair, "pAiR", "Pair");
test_case!(uppercase_pair, "PAIR", "Pair");
test_case!(
non_hack_collection_returns_original_string,
"SomeStRinG",
"SomeStRinG"
);
test_case!(
hack_collection_with_leading_whitespace_returns_original_string,
" pair",
" pair"
);
test_case!(
hack_collection_with_trailing_whitespace_returns_original_string,
"pair ",
"pair "
);
}
}
mod float {
use crate::float;
#[test]
fn test_no_float_part() {
assert_eq!(float::to_string(1.0), "1")
}
#[test]
fn test_precision() {
assert_eq!(float::to_string(1.1), "1.1000000000000001")
}
#[test]
fn test_no_trailing_zeroes() {
assert_eq!(float::to_string(1.2), "1.2")
}
#[test]
fn test_scientific() {
assert_eq!(float::to_string(1e+100), "1e+100")
}
#[test]
fn test_scientific_precision() {
assert_eq!(float::to_string(-2.1474836480001e9), "-2147483648.0001001")
}
#[test]
fn test_negative_nan() {
assert_eq!(float::to_string(-std::f32::NAN), "NAN")
}
}
mod integer {
mod to_decimal {
use crate::integer;
#[test]
fn decimal_zero() {
assert_eq!(integer::to_decimal("0"), Ok("0".to_string()));
}
#[test]
fn octal_zero() {
assert_eq!(integer::to_decimal("00"), Ok("0".to_string()));
}
#[test]
fn binary_zero_lowercase() {
assert_eq!(integer::to_decimal("0b0"), Ok("0".to_string()));
}
#[test]
fn binary_zero_uppercase() {
assert_eq!(integer::to_decimal("0B0"), Ok("0".to_string()));
}
#[test]
fn hex_zero_lowercase() {
assert_eq!(integer::to_decimal("0x0"), Ok("0".to_string()));
}
#[test]
fn hex_zero_uppercase() {
assert_eq!(integer::to_decimal("0X0"), Ok("0".to_string()));
}
#[test]
fn decimal_random_value() {
assert_eq!(integer::to_decimal("1245"), Ok("1245".to_string()));
}
#[test]
fn octal_random_value() {
assert_eq!(integer::to_decimal("02335"), Ok("1245".to_string()));
}
#[test]
fn binary_random_value_lowercase() {
assert_eq!(integer::to_decimal("0b10011011101"), Ok("1245".to_string()));
}
#[test]
fn binary_random_value_uppercase() {
assert_eq!(integer::to_decimal("0B10011011101"), Ok("1245".to_string()));
}
#[test]
fn hex_random_value_lowercase() {
assert_eq!(integer::to_decimal("0x4DD"), Ok("1245".to_string()));
}
#[test]
fn hex_random_value_uppercase() {
assert_eq!(integer::to_decimal("0X4DD"), Ok("1245".to_string()));
}
#[test]
fn decimal_max_value() {
assert_eq!(
integer::to_decimal("9223372036854775807"),
Ok("9223372036854775807".to_string())
);
}
#[test]
fn octal_max_value() {
assert_eq!(
integer::to_decimal("0777777777777777777777"),
Ok("9223372036854775807".to_string())
);
}
#[test]
fn binary_max_value_lowercase() {
assert_eq!(
integer::to_decimal(
"0b111111111111111111111111111111111111111111111111111111111111111"
),
Ok("9223372036854775807".to_string())
);
}
#[test]
fn binary_max_value_uppercase() {
assert_eq!(
integer::to_decimal(
"0B111111111111111111111111111111111111111111111111111111111111111"
),
Ok("9223372036854775807".to_string())
);
}
#[test]
fn hex_max_value_lowercase() {
assert_eq!(
integer::to_decimal("0x7FFFFFFFFFFFFFFF"),
Ok("9223372036854775807".to_string())
);
}
#[test]
fn hex_max_value_uppercase() {
assert_eq!(
integer::to_decimal("0X7FFFFFFFFFFFFFFF"),
Ok("9223372036854775807".to_string())
);
}
#[test]
fn unparsable_string() {
assert!(integer::to_decimal("bad_string").is_err());
}
}
}
mod locals {
use crate::locals;
#[test]
fn strip_single_leading_dollar() {
assert_eq!(locals::strip_dollar("$foo"), "foo");
}
#[test]
fn return_string_if_no_leading_dollar() {
assert_eq!(locals::strip_dollar("foo"), "foo");
}
#[test]
fn empty_string() {
assert_eq!(locals::strip_dollar(""), "");
}
#[test]
fn string_of_single_dollar() {
assert_eq!(locals::strip_dollar("$"), "");
}
}
mod classes {
mod mangle_class {
use crate::classes::mangle_class;
#[test]
fn idx_of_one() {
assert_eq!(mangle_class("foo", "bar", 1), "foo$bar")
}
#[test]
fn idx_of_two() {
assert_eq!(mangle_class("foo", "bar", 2), "foo$bar#2")
}
}
}
mod closures {
mod mangle_closure {
use crate::closures::mangle_closure;
#[test]
fn idx_of_one() {
assert_eq!(mangle_closure("foo", 1), "Closure$foo")
}
#[test]
fn idx_of_two() {
assert_eq!(mangle_closure("foo", 2), "Closure$foo#2")
}
}
mod unmangle_closure {
use crate::closures::unmangle_closure;
#[test]
fn idx_of_one() {
assert_eq!(unmangle_closure("Closure$foo"), Some("foo"))
}
#[test]
fn idx_of_two() {
assert_eq!(unmangle_closure("Closure$foo#2"), Some("foo"))
}
#[test]
fn non_closure() {
assert_eq!(unmangle_closure("SomePrefix$foo"), None);
assert_eq!(unmangle_closure("SomePrefix$foo#2"), None)
}
}
mod is_closure_name {
use crate::closures::is_closure_name;
#[test]
fn closure_1() {
assert!(is_closure_name("Closure$foo"))
}
#[test]
fn closure_2() {
assert!(is_closure_name("Closure$foo#2"))
}
#[test]
fn non_closure() {
assert!(!is_closure_name("SomePrefix$foo"));
assert!(!is_closure_name("SomePrefix$foo#2"))
}
}
}
mod reified {
use crate::reified;
#[test]
fn test_mangle_reified_param() {
assert_eq!(reified::mangle_reified_param(false, "x"), "$__reified$x");
assert_eq!(reified::mangle_reified_param(true, "x"), "__reified$x")
}
#[test]
fn test_is_captured_generic() {
assert_eq!(
reified::is_captured_generic("$__captured$reifiedgeneric$function$1"),
Some((true, 1))
);
assert_eq!(
reified::is_captured_generic("$__captured$reifiedgeneric$class$1"),
Some((false, 1))
);
assert_eq!(reified::is_captured_generic("function$1"), None);
assert_eq!(
reified::is_captured_generic("$__captured$reifiedgeneric$function1"),
None
);
}
#[test]
fn test_captured_name() {
assert_eq!(
reified::captured_name(true, 1),
"$__captured$reifiedgeneric$function$1"
);
assert_eq!(
reified::captured_name(false, 1),
"$__captured$reifiedgeneric$class$1"
);
}
}
#[test]
fn test_lstrip() {
use super::lstrip;
assert_eq!(lstrip("a", "a"), "");
assert_eq!(lstrip("a", "ab"), "a");
assert_eq!(lstrip("", "ab"), "");
assert_eq!(lstrip("", ""), "");
assert_eq!(lstrip("a", ""), "a");
assert_eq!(lstrip("aa", "a"), "a");
assert_eq!(lstrip("aa", "a"), "a");
}
} |
Rust | hhvm/hphp/hack/src/hackc/utils/unique_id_builder.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 type SMap<T> = std::collections::BTreeMap<String, T>;
pub type SSet = std::collections::BTreeSet<String>;
pub fn get_unique_id_for_main() -> String {
String::from("|")
}
pub fn get_unique_id_for_method(cls_name: &str, md_name: &str) -> String {
format!("{}|{}", cls_name, md_name)
}
pub fn get_unique_id_for_function(fun_name: &str) -> String {
format!("|{}", fun_name)
} |
TOML | hhvm/hphp/hack/src/hackc/utils/cargo/hhbc_string_utils/Cargo.toml | # @generated by autocargo
[package]
name = "hhbc_string_utils"
version = "0.0.0"
edition = "2021"
[lib]
path = "../../string_utils.rs"
[dependencies]
bstr = { version = "1.4.0", features = ["serde", "std", "unicode"] }
escaper = { version = "0.0.0", path = "../../../../utils/escaper" }
lazy_static = "1.4"
libc = "0.2.139"
naming_special_names_rust = { version = "0.0.0", path = "../../../../naming" }
ocaml_helper = { version = "0.0.0", path = "../../../../utils/ocaml_helper" }
regex = "1.9.2"
[dev-dependencies]
pretty_assertions = { version = "1.2", features = ["alloc"], default-features = false } |
TOML | hhvm/hphp/hack/src/hackc/utils/cargo/stack_depth/Cargo.toml | # @generated by autocargo
[package]
name = "stack_depth"
version = "0.0.0"
edition = "2021"
[lib]
path = "../../stack_depth.rs"
[dependencies]
ffi = { version = "0.0.0", path = "../../../../utils/ffi" }
hhbc = { version = "0.0.0", path = "../../../hhbc/cargo/hhbc" }
hhbc-gen = { version = "0.0.0", path = "../../../../../../tools/hhbc-gen" }
log = { version = "0.4.17", features = ["kv_unstable", "kv_unstable_std"] }
newtype = { version = "0.0.0", path = "../../../../utils/newtype" }
thiserror = "1.0.43" |
TOML | hhvm/hphp/hack/src/hackc/utils/cargo/unique_id_builder/Cargo.toml | # @generated by autocargo
[package]
name = "unique_id_builder"
version = "0.0.0"
edition = "2021"
[lib]
path = "../../unique_id_builder.rs" |
OCaml | hhvm/hphp/hack/src/hackfmt/boundaries.ml | (*
* Copyright (c) 2017, 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 SourceText = Full_fidelity_source_text
open Hh_prelude
open Printf
let get_line_boundaries text =
let lines = String_utils.split_on_newlines text in
let bytes_seen = ref 0 in
Array.of_list
@@ List.map lines ~f:(fun line ->
let line_start = !bytes_seen in
let line_end = line_start + String.length line + 1 in
bytes_seen := line_end;
(line_start, line_end))
let expand_to_line_boundaries ?ranges source_text range =
let (start_offset, end_offset) = range in
(* Ensure that 0 <= start_offset <= end_offset <= source_text length *)
let start_offset = max start_offset 0 in
let end_offset = max start_offset end_offset in
let end_offset = min end_offset (SourceText.length source_text) in
let start_offset = min start_offset end_offset in
(* Ensure that start_offset and end_offset fall on line boundaries *)
let ranges =
match ranges with
| Some ranges -> ranges
| None -> get_line_boundaries (SourceText.text source_text)
in
Caml.Array.fold_left
(fun (st, ed) (line_start, line_end) ->
let st =
if st > line_start && st < line_end then
line_start
else
st
in
let ed =
if ed > line_start && ed < line_end then
line_end
else
ed
in
(st, ed))
(start_offset, end_offset)
ranges
let line_interval_to_offset_range line_boundaries (start_line, end_line) =
if start_line > end_line then
invalid_arg @@ sprintf "Illegal line interval: %d,%d" start_line end_line;
if
start_line < 1
|| start_line > Array.length line_boundaries
|| end_line < 1
|| end_line > Array.length line_boundaries
then
invalid_arg
@@ sprintf
"Can't format line interval %d,%d in file with %d lines"
start_line
end_line
(Array.length line_boundaries);
let (start_offset, _) = line_boundaries.(start_line - 1) in
let (_, end_offset) = line_boundaries.(end_line - 1) in
(start_offset, end_offset)
let get_atom_boundaries chunk_groups =
chunk_groups
|> List.concat_map ~f:(fun chunk_group -> chunk_group.Chunk_group.chunks)
|> List.concat_map ~f:(fun chunk -> chunk.Chunk.atoms)
|> List.map ~f:(fun atom -> atom.Chunk.range)
let expand_to_atom_boundaries boundaries (r_st, r_ed) =
let rev_bounds = List.rev boundaries in
let st =
match List.find rev_bounds ~f:(fun (b_st, _) -> b_st <= r_st) with
| Some bound -> fst bound
| None -> r_st
in
let ed =
match List.find boundaries ~f:(fun (_, b_ed) -> b_ed >= r_ed) with
| Some bound -> snd bound
| None -> r_ed
in
(st, ed) |
OCaml | hhvm/hphp/hack/src/hackfmt/chunk.ml | (*
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
(* An atom is a substring of the original source which will be exactly
* represented in the formatted output and is considered indivisible by hackfmt.
*
* An atom is one of the following:
* - A single token
* - A single-line comment or delimited comment containing no newlines
* - A segment of a multiline delimited comment. Multiline delimited comments
* are broken on newlines and stripped of their indentation whitespace so that
* their segments can be reindented properly.
* - A single instance of ExtraTokenError trivia
* - An empty string representing a blank line. When this atom occurs, it must
* be the only atom in the chunk.
*
* We keep track of the atoms that make up a chunk to make it possible
* to format ranges which begin or end inside chunks (essential for as-you-type
* formatting, where the cursor may be in the middle of a chunk).
*
* This data structure associates atoms with their location in the original
* source. *)
type atom = {
text: string;
range: Interval.t;
leading_space: bool;
}
type t = {
spans: Span.t list;
is_appendable: bool;
space_if_not_split: bool;
(* If this chunk would have a trailing comma inserted after it if the next
* split is broken on, this will be Some, and the int will be the ID of the
* rule governing that split. If a trailing comma was present in the original
* source, the Interval is the offset range of that token. *)
comma: (int * Interval.t option) option;
rule: int;
nesting: Nesting.t;
start_char: int;
end_char: int;
indentable: bool;
atoms: atom list;
length: int;
}
let default_chunk =
{
spans = [];
is_appendable = true;
space_if_not_split = false;
comma = None;
rule = Rule.null_rule_id;
nesting = Nesting.dummy;
start_char = -1;
end_char = -1;
indentable = true;
atoms = [];
length = -1;
}
let make rule nesting start_char =
let c =
match rule with
| None -> default_chunk
| Some rule -> { default_chunk with rule }
in
{ c with start_char; nesting }
let add_atom c ?(leading_space = false) text width source_offset =
let range = (source_offset, source_offset + width) in
{ c with atoms = { text; range; leading_space } :: c.atoms }
let finalize chunk rule ra space comma end_char =
if List.is_empty chunk.atoms then failwith "Cannot finalize empty chunk";
let end_char = max chunk.start_char end_char in
let rule =
if
Rule.is_always (Rule_allocator.get_rule_kind ra rule)
|| chunk.rule = Rule.null_rule_id
then
rule
else
chunk.rule
in
let atom_length atom =
(if atom.leading_space then
1
else
0)
+ String.length atom.text
in
let length =
chunk.atoms |> List.map ~f:atom_length |> List.fold ~init:0 ~f:( + )
in
{
chunk with
is_appendable = false;
rule;
space_if_not_split = space;
comma;
end_char;
atoms = List.rev chunk.atoms;
length;
}
let get_nesting_id chunk = chunk.nesting.Nesting.id
let get_range chunk =
if chunk.is_appendable then failwith "Can't get range of non-finalized chunk";
let first_atom = List.hd_exn chunk.atoms in
let last_atom = List.last_exn chunk.atoms in
(fst first_atom.range, snd last_atom.range)
let get_comma_range chunk =
match chunk.comma with
| None -> failwith "Can't get comma range of chunk with no comma rule"
| Some (_, range) -> range
let is_empty chunk =
match chunk.atoms with
| [] -> true
| [atom] when String.equal atom.text "" -> true
| _ -> false
let text chunk =
let buf = Buffer.create chunk.length in
List.iter chunk.atoms ~f:(fun atom ->
if atom.leading_space then Buffer.add_char buf ' ';
Buffer.add_string buf atom.text);
Buffer.contents buf |
OCaml | hhvm/hphp/hack/src/hackfmt/chunk_builder.ml | (*
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
module Env = Format_env
type open_span = { open_span_start: int }
type rule_state =
| NoRule
| RuleKind of Rule.kind
| LazyRuleID of int
let open_span start = { open_span_start = start }
type string_type =
| DocStringClose
| Number
| ConcatOp
| LineComment
| Other
[@@deriving eq]
let is_doc_string_close = function
| DocStringClose -> true
| Number
| ConcatOp
| LineComment
| Other ->
false
let builder =
object (this)
val open_spans = Caml.Stack.create ()
val mutable env = Env.default
val mutable rules = []
val mutable lazy_rules = ISet.empty
val mutable chunks = []
val mutable next_split_rule = NoRule
val mutable next_lazy_rules = ISet.empty
val mutable num_pending_spans = 0
val mutable space_if_not_split = false
val mutable pending_comma = None
val mutable pending_space = false
val mutable chunk_groups = []
val mutable rule_alloc = Rule_allocator.make ()
val mutable nesting_alloc = Nesting_allocator.make ()
val mutable span_alloc = Span_allocator.make ()
val mutable block_indent = 0
val mutable seen_chars = 0
val mutable last_chunk_end = 0
val mutable last_string_type = Other
val mutable after_next_string = None
(* TODO: Make builder into an instantiable class instead of
* having this reset method
*)
method private reset new_env =
env <- new_env;
Caml.Stack.clear open_spans;
rules <- [];
lazy_rules <- ISet.empty;
chunks <- [];
next_split_rule <- RuleKind Rule.Always;
next_lazy_rules <- ISet.empty;
num_pending_spans <- 0;
space_if_not_split <- false;
pending_comma <- None;
pending_space <- false;
chunk_groups <- [];
rule_alloc <- Rule_allocator.make ();
nesting_alloc <- Nesting_allocator.make ();
span_alloc <- Span_allocator.make ();
block_indent <- 0;
seen_chars <- 0;
last_chunk_end <- 0;
last_string_type <- Other;
()
method private add_string ?(is_trivia = false) ?(multiline = false) s width
=
if is_doc_string_close last_string_type && (is_trivia || String.(s <> ";"))
then
this#hard_split ();
chunks <-
(match chunks with
| hd :: tl when hd.Chunk.is_appendable ->
let leading_space = pending_space in
pending_space <- false;
let indentable = hd.Chunk.indentable && not multiline in
let hd = Chunk.{ hd with indentable } in
let hd = Chunk.add_atom hd ~leading_space s width seen_chars in
hd :: tl
| _ ->
space_if_not_split <- pending_space;
pending_space <- false;
let nesting = nesting_alloc.Nesting_allocator.current_nesting in
let handle_started_next_split_rule () =
let chunk = Chunk.make (List.hd rules) nesting last_chunk_end in
let chunk = Chunk.add_atom chunk s width seen_chars in
let chunk = { chunk with Chunk.indentable = not multiline } in
let cs = chunk :: chunks in
this#end_rule ();
next_split_rule <- NoRule;
cs
in
(match next_split_rule with
| NoRule ->
let chunk = Chunk.make (List.hd rules) nesting last_chunk_end in
let chunk = Chunk.add_atom chunk s width seen_chars in
let chunk = { chunk with Chunk.indentable = not multiline } in
chunk :: chunks
| LazyRuleID rule_id ->
this#start_lazy_rule rule_id;
handle_started_next_split_rule ()
| RuleKind rule_kind ->
this#start_rule_kind ~rule_kind ();
handle_started_next_split_rule ()));
this#advance width;
if not is_trivia then (
lazy_rules <- ISet.union next_lazy_rules lazy_rules;
next_lazy_rules <- ISet.empty;
for _ = 1 to num_pending_spans do
Caml.Stack.push (open_span (List.length chunks - 1)) open_spans
done;
num_pending_spans <- 0;
if is_doc_string_close last_string_type && String.equal s ";" then (
(* Normally, we'd have already counted the newline in the semicolon's
* trailing trivia before splitting. Since here we're splitting before
* getting the chance to handle that trailing trivia, we temporarily
* advance to make sure the new chunk has the correct start_char. *)
this#advance 1;
this#hard_split ();
this#advance (-1)
)
);
last_string_type <- Other;
Option.call ~f:after_next_string ();
after_next_string <- None
method private set_pending_comma present_in_original_source =
if not (is_doc_string_close last_string_type) then (
let range =
if not present_in_original_source then
None
else
Some (seen_chars, seen_chars + 1)
in
chunks <-
(match chunks with
| hd :: tl when not hd.Chunk.is_appendable ->
{ hd with Chunk.comma = Some (List.hd_exn rules, range) } :: tl
| _ ->
pending_comma <- Some (List.hd_exn rules, range);
chunks);
if Env.version_gte env 3 then last_string_type <- Other
)
method private add_space () =
pending_space <- true;
if Option.is_some pending_comma then this#simple_split_if_unsplit ()
method private split () =
chunks <-
(match chunks with
| hd :: tl when hd.Chunk.is_appendable ->
let rule_id = hd.Chunk.rule in
let rule =
if rule_id <> Rule.null_rule_id then
rule_id
else
match rules with
| [] -> this#create_rule (Rule.Simple Cost.Base)
| hd :: _ -> hd
in
let chunk =
Chunk.finalize
hd
rule
rule_alloc
space_if_not_split
pending_comma
seen_chars
in
last_chunk_end <- seen_chars;
space_if_not_split <- pending_space;
pending_comma <- None;
chunk :: tl
| _ -> chunks)
method private create_rule rule_kind =
let (ra, rule) = Rule_allocator.make_rule rule_alloc rule_kind in
rule_alloc <- ra;
rule.Rule.id
method private create_lazy_rule ?(rule_kind = Rule.Simple Cost.Base) () =
let id = this#create_rule rule_kind in
next_lazy_rules <- ISet.add id next_lazy_rules;
id
(* TODO: after unit tests, make this idempotency a property of method split *)
method private simple_split_if_unsplit () =
match chunks with
| hd :: _ when hd.Chunk.is_appendable -> this#simple_split ()
| _ -> ()
(* TODO: is this the right whitespace strategy? *)
method private add_always_empty_chunk () =
let nesting = nesting_alloc.Nesting_allocator.current_nesting in
let create_empty_chunk () =
let rule = this#create_rule Rule.Always in
let chunk = Chunk.make (Some rule) nesting last_chunk_end in
let chunk = Chunk.add_atom chunk "" 0 last_chunk_end in
last_chunk_end <- seen_chars;
Chunk.finalize chunk rule rule_alloc false None seen_chars
in
chunks <-
(match chunks with
| [] -> create_empty_chunk () :: chunks
| hd :: _ when not hd.Chunk.is_appendable ->
create_empty_chunk () :: chunks
(* TODO: this is probably wrong, figure out what this means *)
| _ -> chunks)
method private simple_split ?(cost = Cost.Base) () =
this#split ();
this#set_next_split_rule (RuleKind (Rule.Simple cost));
()
method private is_at_chunk_group_boundry () =
List.is_empty rules
&& ISet.is_empty lazy_rules
&& ISet.is_empty next_lazy_rules
&& not (Nesting_allocator.is_nested nesting_alloc)
method private hard_split () =
begin
match chunks with
| [] -> ()
| _ ->
this#split ();
this#set_next_split_rule (RuleKind Rule.Always)
end;
if this#is_at_chunk_group_boundry () && not (List.is_empty chunks) then
this#push_chunk_group ()
method private set_next_split_rule rule_type =
next_split_rule <-
(match next_split_rule with
| RuleKind Rule.Always -> next_split_rule
| _ -> rule_type)
method private nest ?(skip_parent = false) () =
nesting_alloc <- Nesting_allocator.nest nesting_alloc skip_parent
method private unnest () =
nesting_alloc <- Nesting_allocator.unnest nesting_alloc
method private start_rule_id rule_id =
rule_alloc <-
Rule_allocator.mark_dependencies rule_alloc lazy_rules rules rule_id;
rules <- rule_id :: rules
method private start_rule_kind ?(rule_kind = Rule.Simple Cost.Base) () =
(* Override next_split_rule unless it's an Always rule *)
next_split_rule <-
(match next_split_rule with
| RuleKind kind when not (Rule.is_always kind) -> NoRule
| _ -> next_split_rule);
let rule = this#create_rule rule_kind in
this#start_rule_id rule
method private start_lazy_rule lazy_rule_id =
if ISet.mem lazy_rule_id next_lazy_rules then (
next_lazy_rules <- ISet.remove lazy_rule_id next_lazy_rules;
this#start_rule_id lazy_rule_id
) else if ISet.mem lazy_rule_id lazy_rules then (
lazy_rules <- ISet.remove lazy_rule_id lazy_rules;
this#start_rule_id lazy_rule_id
) else
raise
(Failure "Called start_lazy_rule with a rule id is not a lazy rule")
method private end_rule () =
rules <-
(match rules with
| _ :: tl -> tl
| [] -> [])
(*TODO: error *)
method private has_rule_kind kind =
List.exists rules ~f:(fun id ->
Rule.equal_kind (Rule_allocator.get_rule_kind rule_alloc id) kind)
method private start_span () = num_pending_spans <- num_pending_spans + 1
method private end_span () =
num_pending_spans <-
(match num_pending_spans with
| 0 ->
let os = Caml.Stack.pop open_spans in
let (sa, span) = Span_allocator.make_span span_alloc in
span_alloc <- sa;
let r_chunks = List.rev chunks in
chunks <-
List.rev_mapi r_chunks ~f:(fun n x ->
if n <= os.open_span_start then
x
else
(* TODO: handle required hard splits *)
{ x with Chunk.spans = span :: x.Chunk.spans });
0
| _ -> num_pending_spans - 1)
(*
TODO: find a better way to represt the rules empty case
for end chunks and block nesting
*)
method private start_block_nest () =
if this#is_at_chunk_group_boundry () then
block_indent <- block_indent + 1
else
this#nest ()
method private end_block_nest () =
if this#is_at_chunk_group_boundry () then
block_indent <- block_indent - 1
else
this#unnest ()
method private push_chunk_group () =
chunk_groups <-
Chunk_group.
{
chunks = List.rev chunks;
rule_map = rule_alloc.Rule_allocator.rule_map;
rule_dependency_map = rule_alloc.Rule_allocator.dependency_map;
block_indentation = block_indent;
}
:: chunk_groups;
chunks <- [];
rule_alloc <- Rule_allocator.make ();
nesting_alloc <- Nesting_allocator.make ();
span_alloc <- Span_allocator.make ()
method private _end () =
this#hard_split ();
if not (List.is_empty chunks) then
failwith
("The impossible happened: Chunk_builder attempted to end "
^ "when not at a chunk group boundary");
List.rev chunk_groups
method private advance n = seen_chars <- seen_chars + n
method build_chunk_groups env node =
this#reset env;
this#consume_doc node;
this#_end ()
method private consume_doc node =
Doc.(
match node with
| Nothing -> ()
| Concat nodes -> List.iter nodes ~f:this#consume_doc
| Text (text, width) -> this#add_string text width
| Comment (text, width) -> this#add_string ~is_trivia:true text width
| SingleLineComment (text, width) ->
this#add_string ~is_trivia:true text width;
last_string_type <- LineComment
| Ignore (_, width) -> this#advance width
| MultilineString (strings, width) ->
let prev_seen = seen_chars in
begin
match strings with
| hd :: tl ->
this#add_string hd (String.length hd);
List.iter tl ~f:(fun s ->
this#advance 1;
this#hard_split ();
this#add_string ~multiline:true s (String.length s))
| [] -> ()
end;
seen_chars <- prev_seen + width
| DocLiteral node ->
if not (Env.version_gte env 3) then
this#set_next_split_rule (RuleKind (Rule.Simple Cost.Base));
this#consume_doc node;
last_string_type <- DocStringClose
| NumericLiteral node ->
if equal_string_type last_string_type ConcatOp then this#add_space ();
this#consume_doc node;
last_string_type <- Number
| ConcatOperator node ->
if equal_string_type last_string_type Number then this#add_space ();
this#consume_doc node;
last_string_type <- ConcatOp
| Split -> this#split ()
| SplitWith cost -> this#simple_split ~cost ()
| Newline -> this#hard_split ()
| BlankLine ->
this#hard_split ();
this#add_always_empty_chunk ()
| Space -> this#add_space ()
| Span nodes ->
this#start_span ();
List.iter nodes ~f:this#consume_doc;
this#end_span ()
| Nest nodes ->
this#nest ();
List.iter nodes ~f:this#consume_doc;
this#unnest ()
| ConditionalNest nodes ->
this#nest ~skip_parent:true ();
List.iter nodes ~f:this#consume_doc;
this#unnest ()
| BlockNest nodes ->
this#start_block_nest ();
List.iter nodes ~f:this#consume_doc;
this#end_block_nest ()
| WithRule (rule_kind, body) ->
this#start_rule_kind ~rule_kind ();
this#consume_doc body;
this#end_rule ()
| WithLazyRule (rule_kind, before, body) ->
let rule = this#create_lazy_rule ~rule_kind () in
this#consume_doc before;
this#start_lazy_rule rule;
this#consume_doc body;
this#end_rule ()
| WithOverridingParentalRule body ->
let start_parental_rule =
this#start_rule_kind ~rule_kind:Rule.Parental
in
(* If we have a pending split which is not a hard split, replace it with a
Parental rule, which will break if the body breaks. *)
let override_independent_split =
match next_split_rule with
| RuleKind Rule.Always -> false
| RuleKind _ -> true
| _ -> false
in
(* Starting a new rule will override the independent split, controlling
that split with the new Parental rule instead. *)
if override_independent_split then start_parental_rule ();
(* Regardless of whether we intend to override the preceding split, start
a new Parental rule to govern the contents of the body. *)
after_next_string <- Some start_parental_rule;
this#consume_doc body;
this#end_rule ();
if override_independent_split then this#end_rule ()
| TrailingComma present_in_original_source ->
if not (equal_string_type last_string_type LineComment) then
this#set_pending_comma present_in_original_source
else (
this#add_string "," 1;
this#advance (-1)
);
if not (Env.version_gte env 3) then last_string_type <- Other)
end
let build env node = builder#build_chunk_groups env node |
OCaml | hhvm/hphp/hack/src/hackfmt/chunk_group.ml | (*
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
type t = {
chunks: Chunk.t list;
rule_map: Rule.t IMap.t;
rule_dependency_map: int list IMap.t;
block_indentation: int;
}
let get_rule_count t = IMap.cardinal t.rule_map
let get_rules t =
(* TODO verify or log if there are unused rules *)
List.map (IMap.bindings t.rule_map) ~f:fst
let get_rule_kind t id =
let r = IMap.find id t.rule_map in
r.Rule.kind
let get_char_range t =
t.chunks
|> List.fold ~init:(Int.max_value, 0) ~f:(fun (start_char, end_char) chunk ->
let (chunk_start, chunk_end) = Chunk.get_range chunk in
(min start_char chunk_start, max end_char chunk_end))
let propagate_breakage t initial_bindings =
initial_bindings
|> IMap.filter (fun _ is_broken -> is_broken)
|> IMap.keys
|> List.fold ~init:initial_bindings ~f:(fun acc rule_id ->
let dependencies =
Option.value
~default:[]
(IMap.find_opt rule_id t.rule_dependency_map)
in
dependencies
|> List.filter ~f:(fun id ->
Rule.cares_about_children (get_rule_kind t id))
|> List.fold ~init:acc ~f:(fun acc id -> IMap.add id true acc))
let get_always_rules t =
t.rule_map |> IMap.filter (fun _ v -> Rule.is_always v.Rule.kind) |> IMap.keys
let get_always_rule_bindings t =
get_always_rules t
|> List.fold ~init:IMap.empty ~f:(fun acc id -> IMap.add id true acc)
let get_initial_rule_bindings t =
propagate_breakage t (get_always_rule_bindings t)
(* When a child rule is broken on, all its parent rules must break too. *)
let is_dependency_satisfied parent_kind parent_val child_val =
(* If the parent rule doesn't care about whether its child rules break, then
* the dependency doesn't matter. *)
if not (Rule.cares_about_children parent_kind) then
true
else
(* Otherwise, the dependency is only unsatisfied when the parent rule is
* bound not to break and the child rule is bound to break. *)
match (parent_val, child_val) with
| (Some false, true) -> false
| _ -> true
let are_rule_bindings_valid t rbm =
let valid_map =
IMap.mapi
(fun rule_id v ->
let parent_list =
Option.value ~default:[] (IMap.find_opt rule_id t.rule_dependency_map)
in
List.for_all parent_list ~f:(fun parent_id ->
let parent_rule = IMap.find parent_id t.rule_map in
let parent_value = IMap.find_opt parent_id rbm in
is_dependency_satisfied parent_rule.Rule.kind parent_value v))
rbm
in
List.for_all ~f:(fun x -> x) @@ List.map ~f:snd @@ IMap.bindings valid_map
let dependency_map_to_string t =
let get_map_values map = List.map ~f:snd @@ IMap.bindings @@ map in
let str_list =
get_map_values
@@ IMap.mapi
(fun k v_list ->
let values = List.map v_list ~f:string_of_int in
string_of_int k ^ ": [" ^ String.concat ~sep:", " values ^ "]")
t.rule_dependency_map
in
"{" ^ String.concat ~sep:", " str_list ^ "}" |
OCaml | hhvm/hphp/hack/src/hackfmt/cost.ml | (*
* Copyright (c) 2016, 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.
*
*)
type t =
| NoCost
| Base
| Moderate
| High
[@@deriving eq]
let get_cost t =
match t with
| NoCost -> 0
| Base -> 1
| Moderate -> 2
| High -> 3 |
OCaml | hhvm/hphp/hack/src/hackfmt/doc.ml | (*
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
type t =
(* Null case *)
| Nothing
(* List of concatenated nodes *)
| Concat of t list
(* Text which will appear in the formatted file *)
| Text of string * int
(* A comment which will appear in the formatted file *)
| Comment of string * int
(* A comment which must be followed by a Newline. No text may be inserted
* between this comment and the Newline following it. *)
| SingleLineComment of string * int
(* Text from the original source which will not appear in the formatted file.
* Keeping track of these allows range formatting. *)
| Ignore of string * int
(* Breaking point for the line solver *)
| Split
(* Allow splitting here, but with the given cost instead of the cost of the
* nearest containing rule *)
| SplitWith of Cost.t
(* Always split here. Consecutive Newlines are ignored by the Chunk_builder
* (use BlankLine to insert a blank line). *)
| Newline
(* Always split here and leave a blank line *)
| BlankLine
(* Add a space *)
| Space
(* Items in a Span prefer to stay on the same line *)
| Span of t list
(* Nested items are indented if they break across lines *)
| Nest of t list
(* All lines in a BlockNest are indented *)
| BlockNest of t list
(* Splits in a WithRule region will default to using that region's rule *)
| WithRule of Rule.kind * t
(* Splits in a WithLazyRule region will default to using this lazy rule.
* Lazy rules are necessary when needing to emit formatted text between the
* location where the rule's dependencies are computed and the region to which
* the lazy rule applies. The first Doc is for content before the lazy rule
* becomes active, while the second is for content the lazy rule applies
* to. *)
| WithLazyRule of Rule.kind * t * t (*** Special cases ***)
(* Tokens representing part of a string literal spanning multiple lines are
* split on newlines and passed as a MultilineString. These strings are not
* indented (since indenting would insert whitespace into the literal). *)
| MultilineString of string list * int
(* Heredoc and Nowdoc literals end with a closing identifier, which must be
* the only characters on their line (other than a semicolon). Chunk_builder
* needs to know if the last string was a docstring close in order to ensure a
* newline after it (except if the next token is a semicolon). *)
| DocLiteral of t
(* Chunk_builder needs to know if the last literal was numeric in order to
* avoid adding a concat operator directly next to it (since it would then be
* parsed as a decimal point). *)
| NumericLiteral of t
(* Chunk_builder needs to know if the last token was a concat operator in
* order to avoid adding a numeric literal directly next to it (since it would
* then be parsed as a decimal point). *)
| ConcatOperator of t
(* Set Nesting.skip_parent_if_nested on this nesting *)
| ConditionalNest of t list
(* Splits in a WithOverridingParentalRule region are controlled by a Parental
rule. If an independent split (i.e., SplitWith) precedes the region,
override that split to be governed by the Parental rule instead.
This is useful for XHP, where we would never like to join multiline XHP
expressions onto a previous line:
$x = <p>
foo
</p>;
Instead, it is conventional to start a multiline XHP expression on a new
line:
$x =
<p>
foo
</p>;
Using WithOverridingParentalRule overrides the independent split following
the assignment operator, causing it to be governed by the Parental rule
governing the rest of the splits in this region instead of the Simple rule
originally created for the independent split.
Note that this "overriding" behavior is actually the *default* behavior of
WithRule--if a split is pending when a WithRule region begins, that split
will be considered to be part of the WithRule region, even if it was
already associated with another rule. What is special about the
WithOverridingParentalRule construct is that it *doesn't* trample the rule
association of a preceding Split which is not independent.
Yes, this is confusing. Diffs which make this more sensible and consistent
would be more than welcome! *)
| WithOverridingParentalRule of t
(* Add a comma only if the next split is broken on. The bool indicates whether
* a trailing comma was present in the original source. *)
| TrailingComma of bool
let is_nothing = function
| Nothing -> true
| _ -> false
let space () = Space
let split () = Split
let space_split () = Concat [Space; Split]
let newline () = Newline
let text s = Text (s, String.length s)
let rec has_printable_content node =
match node with
| Text _
| Comment _
| SingleLineComment _
| MultilineString _
| DocLiteral _
| NumericLiteral _
| ConcatOperator _ ->
true
| Concat nodes
| Span nodes
| Nest nodes
| ConditionalNest nodes
| BlockNest nodes ->
List.exists nodes ~f:has_printable_content
| WithRule (_, body)
| WithOverridingParentalRule body ->
has_printable_content body
| WithLazyRule (_, before, body) ->
has_printable_content before || has_printable_content body
| Nothing
| Ignore _
| Split
| SplitWith _
| Newline
| BlankLine
| Space
| TrailingComma _ ->
false
let rec has_split node =
match node with
| Split
| SplitWith _
| Newline
| BlankLine
| MultilineString _
| DocLiteral _ ->
true
| Concat nodes
| Span nodes
| Nest nodes
| ConditionalNest nodes
| BlockNest nodes ->
List.exists nodes ~f:has_split
| WithRule (_, body)
| WithOverridingParentalRule body ->
has_split body
| WithLazyRule (_, before, body) -> has_split before || has_split body
| Text _
| Comment _
| SingleLineComment _
| NumericLiteral _
| ConcatOperator _
| Nothing
| Ignore _
| Space
| TrailingComma _ ->
false
(* Add "dump @@" before any Doc.t expression to dump it to stderr. *)
let dump ?(ignored = false) node =
Printf.(
let rec aux = function
| Nothing -> ()
| Concat nodes -> List.iter nodes ~f:aux
| Text (text, _) -> print (sprintf "Text \"%s\"" text)
| Comment (text, _) -> print (sprintf "Comment \"%s\"" text)
| SingleLineComment (text, _) ->
print (sprintf "SingleLineComment \"%s\"" text)
| Ignore (text, _) ->
if ignored then
print
(sprintf
"Ignored \"%s\""
(String.concat
~sep:"\\n"
(Str.split_delim (Str.regexp "\n") text)))
| MultilineString (strings, _) ->
print "MultilineString [";
indent := !indent + 2;
List.iter strings ~f:(fun s -> print (sprintf "\"%s\"" s));
indent := !indent - 2;
print "]"
| DocLiteral node -> dump_list "DocLiteral" [node]
| NumericLiteral node -> dump_list "NumericLiteral" [node]
| ConcatOperator node -> dump_list "ConcatOperator" [node]
| Split -> print "Split"
| SplitWith cost ->
print
("SplitWith "
^
match cost with
| Cost.NoCost -> "Cost.NoCost"
| Cost.Base -> "Cost.Base"
| Cost.Moderate -> "Cost.Moderate"
| Cost.High -> "Cost.High")
| Newline -> print "Newline"
| BlankLine -> print "BlankLine"
| Space -> print "Space"
| Span nodes -> dump_list "Span" nodes
| Nest nodes -> dump_list "Nest" nodes
| ConditionalNest nodes -> dump_list "ConditionalNest" nodes
| BlockNest nodes -> dump_list "BlockNest" nodes
| WithRule (_, body) -> dump_list "WithRule" [body]
| WithLazyRule (_, before, body) ->
print "WithLazyRule ([";
dump_list_items [before];
print "], [";
dump_list_items [body];
print "])"
| WithOverridingParentalRule body ->
print "WithOverridingParentalRule ([";
dump_list_items [body];
print "])"
| TrailingComma present_in_original_source ->
print (sprintf "TrailingComma %b" present_in_original_source)
and indent = ref 0
and print s = eprintf "%s%s\n" (String.make !indent ' ') s
and dump_list name nodes =
print
(if String.equal name "" then
"["
else
name ^ " [");
dump_list_items nodes;
print "]"
and dump_list_items nodes =
indent := !indent + 2;
List.iter nodes ~f:aux;
indent := !indent - 2
in
if is_nothing node then
print "Nothing"
else
aux node;
eprintf "%!";
node) |
hhvm/hphp/hack/src/hackfmt/dune | (library
(name hackfmt_doc)
(wrapped false)
(modules cost doc rule)
(preprocess
(pps ppx_deriving.std))
(libraries core_kernel utils_core))
(library
(name hackfmt_env)
(wrapped false)
(preprocess
(pps ppx_deriving.std))
(modules format_env))
(library
(name hackfmt)
(wrapped false)
(preprocess
(pps ppx_deriving.std))
(modules
boundaries
chunk
chunk_builder
chunk_group
hack_format
interval
libhackfmt
line_splitter
nesting
nesting_allocator
noformat
rule_allocator
solve_state
span
span_allocator
state_queue
subchunk)
(libraries
common
diff
full_fidelity
hackfmt_doc
hackfmt_env
hackfmt_error
logging
utils_www_root)) |
|
OCaml | hhvm/hphp/hack/src/hackfmt/format_env.ml | (*
* Copyright (c) 2017, 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.
*
*)
type t = {
add_trailing_commas: bool;
indent_width: int;
indent_with_tabs: bool;
line_width: int;
format_generated_code: bool;
version: int option;
}
let default =
{
add_trailing_commas = true;
indent_width = 2;
indent_with_tabs = false;
line_width = 80;
format_generated_code = false;
version = None;
}
let version_gte env min_version =
match env.version with
| None -> true (* If no version is specified, use latest *)
| Some v -> v >= min_version |
OCaml | hhvm/hphp/hack/src/hackfmt/hack_format.ml | (*
* Copyright (c) 2018, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
module Env = Format_env
module SourceText = Full_fidelity_source_text
module Syntax = Full_fidelity_editable_syntax
module SyntaxKind = Full_fidelity_syntax_kind
module Token = Full_fidelity_editable_token
module TokenKind = Full_fidelity_token_kind
module Trivia = Full_fidelity_editable_trivia
module TriviaKind = Full_fidelity_trivia_kind
module Rewriter = Full_fidelity_rewriter.WithSyntax (Syntax)
open Doc
let is_trivia_kind_fallthrough = function
| TriviaKind.FallThrough -> true
| _ -> false
let is_trivia_kind_end_of_line = function
| TriviaKind.EndOfLine -> true
| _ -> false
let is_trivia_kind_white_space = function
| TriviaKind.WhiteSpace -> true
| _ -> false
let is_syntax_kind_parenthesized_exprression = function
| SyntaxKind.ParenthesizedExpression -> true
| _ -> false
let is_token_kind_xhp_body = function
| TokenKind.XHPBody -> true
| _ -> false
let is_token_kind_in_out = function
| TokenKind.Inout -> true
| _ -> false
let make_list = Syntax.make_list SourceText.empty 0
let make_missing () = Syntax.make_missing SourceText.empty 0
(* Main transform function, which takes a full-fidelity CST node and produces a
* Doc.t node (the IR which is fed to Chunk_builder.build).
*
* Exported via the `transform` alias below. *)
let rec t (env : Env.t) (node : Syntax.t) : Doc.t =
(* Leave this node as it was in the original source if it is preceded by a
hackfmt-ignore comment. *)
match transform_node_if_ignored node with
| Some doc -> doc
| None ->
(match Syntax.syntax node with
| Syntax.Missing -> Nothing
| Syntax.Token x ->
let token_kind = Token.kind x in
Concat
[
begin
match token_kind with
| TokenKind.EndOfFile ->
let leading_trivia = Token.leading x in
let trivia_without_trailing_invisibles =
let reversed = List.rev leading_trivia in
List.rev (List.drop_while reversed ~f:is_invisible)
in
transform_leading_trivia trivia_without_trailing_invisibles
| _ -> transform_leading_trivia (Token.leading x)
end;
begin
match token_kind with
| TokenKind.EndOfFile -> Nothing
| TokenKind.SingleQuotedStringLiteral
| TokenKind.DoubleQuotedStringLiteral
| TokenKind.DoubleQuotedStringLiteralHead
| TokenKind.StringLiteralBody
| TokenKind.DoubleQuotedStringLiteralTail
| TokenKind.HeredocStringLiteral
| TokenKind.HeredocStringLiteralHead
| TokenKind.HeredocStringLiteralTail
| TokenKind.NowdocStringLiteral ->
make_string (Token.text x) (Token.width x)
| TokenKind.XHPStringLiteral when Env.version_gte env 2 ->
make_string (Token.text x) (Token.width x)
| _ -> Text (Token.text x, Token.width x)
end;
transform_trailing_trivia (Token.trailing x);
]
| Syntax.SyntaxList _ ->
failwith
(Printf.sprintf
"Error: SyntaxList should never be handled directly;
offending text is '%s'."
(Syntax.text node))
| Syntax.EndOfFile x -> t env x.end_of_file_token
| Syntax.Script x -> Concat [handle_possible_list env x.script_declarations]
| Syntax.LiteralExpression { literal_expression } ->
(* Double quoted string literals can create a list *)
let wrap_with_literal_type token transformed =
match Token.kind token with
| TokenKind.HeredocStringLiteral
| TokenKind.HeredocStringLiteralHead
| TokenKind.HeredocStringLiteralTail
| TokenKind.NowdocStringLiteral ->
DocLiteral transformed
| TokenKind.DecimalLiteral
| TokenKind.OctalLiteral
| TokenKind.HexadecimalLiteral
| TokenKind.BinaryLiteral
| TokenKind.FloatingLiteral ->
NumericLiteral transformed
| _ -> transformed
in
begin
match Syntax.syntax literal_expression with
| Syntax.Token tok ->
wrap_with_literal_type tok (t env literal_expression)
| Syntax.SyntaxList l ->
let last = Syntax.trailing_token literal_expression in
begin
match last with
| Some tok ->
wrap_with_literal_type tok (Concat (List.map l ~f:(t env)))
| _ -> failwith "Expected Token"
end
| _ -> failwith "Expected Token or SyntaxList"
end
| Syntax.PrefixedStringExpression
{ prefixed_string_name = name; prefixed_string_str = str } ->
Concat [t env name; t env str]
| Syntax.MarkupSection
{ markup_hashbang = hashbang; markup_suffix = suffix; _ } ->
if Syntax.is_missing hashbang then
t env suffix
else
Concat [t env hashbang; Newline; t env suffix]
| Syntax.MarkupSuffix _ -> transform_simple_statement env node
| Syntax.SimpleTypeSpecifier _
| Syntax.VariableExpression _
| Syntax.PipeVariableExpression _
| Syntax.PropertyDeclarator _
| Syntax.ConstantDeclarator _
| Syntax.ScopeResolutionExpression _
| Syntax.EmbeddedMemberSelectionExpression _
| Syntax.EmbeddedSubscriptExpression _
| Syntax.PostfixUnaryExpression _
| Syntax.XHPRequired _
| Syntax.XHPLateinit _
| Syntax.XHPSimpleClassAttribute _
| Syntax.XHPClose _
| Syntax.TypeConstant _
| Syntax.GenericTypeSpecifier _
| Syntax.NullableTypeSpecifier _
| Syntax.LikeTypeSpecifier _
| Syntax.SoftTypeSpecifier _
| Syntax.VariablePattern _
| Syntax.ListItem _ ->
transform_simple env node
| Syntax.ReifiedTypeArgument
{ reified_type_argument_reified; reified_type_argument_type } ->
Concat
[
t env reified_type_argument_reified;
Space;
t env reified_type_argument_type;
]
| Syntax.QualifiedName { qualified_name_parts } ->
handle_possible_list env qualified_name_parts
| Syntax.ModuleName { module_name_parts } ->
handle_possible_list env module_name_parts
| Syntax.ExpressionStatement _ -> transform_simple_statement env node
| Syntax.EnumDeclaration
{
enum_attribute_spec = attr;
enum_modifiers = modifiers;
enum_keyword = kw;
enum_name = name;
enum_colon = colon_kw;
enum_base = base;
enum_type;
enum_left_brace = left_b;
enum_use_clauses;
enum_enumerators = enumerators;
enum_right_brace = right_b;
} ->
Concat
[
t env attr;
when_present attr newline;
handle_possible_list env ~after_each:(fun _ -> Space) modifiers;
t env kw;
Space;
t env name;
t env colon_kw;
Space;
SplitWith Cost.Base;
Nest [Space; t env base; Space; t env enum_type; Space];
braced_block_nest
env
left_b
right_b
[
handle_possible_list env enum_use_clauses;
handle_possible_list env enumerators;
];
Newline;
]
| Syntax.Enumerator
{
enumerator_name = name;
enumerator_equal = eq_kw;
enumerator_value = value;
enumerator_semicolon = semi;
} ->
let value = t env value in
Concat
[
t env name;
Space;
t env eq_kw;
Space;
(if has_split value then
SplitWith Cost.Base
else
Nothing);
Nest [value];
t env semi;
Newline;
]
| Syntax.EnumUse
{
enum_use_keyword = kw;
enum_use_names = elements;
enum_use_semicolon = semi;
} ->
Concat
[
t env kw;
(match Syntax.syntax elements with
| Syntax.SyntaxList [x] -> Concat [Space; t env x]
| Syntax.SyntaxList _ ->
WithRule
( Rule.Parental,
Nest
[handle_possible_list env ~before_each:space_split elements]
)
| _ -> Concat [Space; t env elements]);
t env semi;
Newline;
]
| Syntax.AliasDeclaration
{
alias_attribute_spec = attr;
alias_modifiers = modifiers;
alias_module_kw_opt = mkw_opt;
alias_keyword = kw;
alias_name = name;
alias_generic_parameter = generic;
alias_constraint = type_constraint;
alias_equal = eq_kw;
alias_type = ty;
alias_semicolon = semi;
} ->
(* TODO: revisit this for long names *)
Concat
[
t env attr;
when_present attr newline;
handle_possible_list env ~after_each:(fun _ -> Space) modifiers;
t env mkw_opt;
when_present mkw_opt space;
t env kw;
Space;
t env name;
t env generic;
Space;
handle_possible_list env type_constraint;
when_present eq_kw (function () ->
Concat
[
Space; t env eq_kw; Space; SplitWith Cost.Base; Nest [t env ty];
]);
t env semi;
Newline;
]
| Syntax.ContextAliasDeclaration
{
ctx_alias_attribute_spec = attr;
ctx_alias_keyword = kw;
ctx_alias_name = name;
ctx_alias_generic_parameter = generic;
ctx_alias_as_constraint = type_constraint;
ctx_alias_equal = eq_kw;
ctx_alias_context = ty;
ctx_alias_semicolon = semi;
} ->
(* TODO: revisit this for long names *)
Concat
[
t env attr;
when_present attr newline;
t env kw;
Space;
t env name;
t env generic;
Space;
handle_possible_list env type_constraint;
when_present eq_kw (function () ->
Concat
[
Space; t env eq_kw; Space; SplitWith Cost.Base; Nest [t env ty];
]);
t env semi;
Newline;
]
| Syntax.CaseTypeDeclaration
{
case_type_attribute_spec = attr;
case_type_modifiers = modifiers;
case_type_case_keyword = case_kw;
case_type_type_keyword = type_kw;
case_type_name = name;
case_type_generic_parameter = generic;
case_type_as = as_kw;
case_type_bounds = bounds;
case_type_equal = eq_kw;
case_type_variants = variants;
case_type_semicolon = semi;
} ->
let has_leading_bar =
match Syntax.syntax variants with
| Syntax.SyntaxList (hd :: _) ->
(match Syntax.syntax hd with
| Syntax.CaseTypeVariant { case_type_variant_bar = bar; _ }
when not @@ Syntax.is_missing bar ->
true
| _ -> false)
| _ -> false
in
Concat
[
t env attr;
when_present attr newline;
handle_possible_list env ~after_each:(fun _ -> Space) modifiers;
t env case_kw;
Space;
t env type_kw;
Space;
t env name;
t env generic;
when_present as_kw space;
t env as_kw;
when_present as_kw space;
handle_possible_list env bounds;
when_present eq_kw (function () ->
Concat
[
Space;
t env eq_kw;
(if has_leading_bar then
Newline
else
Space);
WithRule
( (if has_leading_bar then
Rule.Always
else
Rule.Parental),
Nest
[
handle_possible_list
~after_each:(function
| false -> space_split ()
| true -> Nothing)
env
variants;
] );
]);
t env semi;
Newline;
]
| Syntax.CaseTypeVariant
{ case_type_variant_bar = bar; case_type_variant_type = ty } ->
Span [t env bar; when_present bar space; t env ty]
| Syntax.PropertyDeclaration
{
property_attribute_spec = attr;
property_modifiers = modifiers;
property_type = prop_type;
property_declarators = declarators;
property_semicolon = semi;
} ->
let declaration =
Concat
[
handle_possible_list env ~after_each:(fun _ -> Space) modifiers;
t env prop_type;
handle_declarator_list env declarators;
t env semi;
Newline;
]
in
if Syntax.is_missing attr then
declaration
else
WithLazyRule
( Rule.Parental,
handle_attribute_spec env attr ~always_split:false,
Concat [Space; Split; declaration] )
| Syntax.NamespaceDeclaration
{ namespace_header = header; namespace_body = body } ->
Concat [t env header; t env body; Newline]
| Syntax.NamespaceDeclarationHeader
{ namespace_keyword = kw; namespace_name = name } ->
Concat [t env kw; Space; t env name]
| Syntax.NamespaceBody
{
namespace_left_brace = left_b;
namespace_declarations = decls;
namespace_right_brace = right_b;
} ->
Concat
[
Space;
braced_block_nest env left_b right_b [handle_possible_list env decls];
]
| Syntax.NamespaceEmptyBody { namespace_semicolon = semi } ->
Concat [t env semi]
| Syntax.NamespaceUseDeclaration
{
namespace_use_keyword = kw;
namespace_use_kind = use_kind;
namespace_use_clauses = clauses;
namespace_use_semicolon = semi;
} ->
Concat
[
t env kw;
Space;
t env use_kind;
when_present use_kind space;
WithRule
( Rule.Parental,
Nest
[
handle_possible_list
env
clauses
~after_each:after_each_argument;
] );
t env semi;
Newline;
]
| Syntax.NamespaceGroupUseDeclaration
{
namespace_group_use_keyword = kw;
namespace_group_use_kind = use_kind;
namespace_group_use_prefix = prefix;
namespace_group_use_left_brace = left_b;
namespace_group_use_clauses = clauses;
namespace_group_use_right_brace = right_b;
namespace_group_use_semicolon = semi;
} ->
Concat
[
t env kw;
Space;
t env use_kind;
when_present use_kind space;
t env prefix;
transform_argish env left_b clauses right_b;
t env semi;
Newline;
]
| Syntax.NamespaceUseClause
{
namespace_use_clause_kind = use_kind;
namespace_use_name = name;
namespace_use_as = as_kw;
namespace_use_alias = alias;
} ->
Concat
[
t env use_kind;
when_present use_kind space;
t env name;
when_present as_kw space;
t env as_kw;
when_present alias space;
t env alias;
]
| Syntax.FunctionDeclaration
{
function_attribute_spec = attr;
function_declaration_header = header;
function_body = body;
} ->
Concat
[
t env attr;
when_present attr newline;
t env header;
handle_possible_compound_statement env ~allow_collapse:true body;
Newline;
]
| Syntax.FunctionDeclarationHeader
{
function_modifiers = modifiers;
function_keyword = kw;
function_name = name;
function_type_parameter_list = type_params;
function_left_paren = leftp;
function_parameter_list = params;
function_right_paren = rightp;
function_contexts = ctxs;
function_colon = colon;
function_readonly_return = readonly_return;
function_type = ret_type;
function_where_clause = where;
} ->
Concat
[
Span (transform_fn_decl_name env modifiers kw name type_params leftp);
transform_fn_decl_args env params rightp;
t env ctxs;
t env colon;
when_present colon space;
t env readonly_return;
when_present readonly_return space;
t env ret_type;
when_present where space;
t env where;
]
| Syntax.WhereClause
{ where_clause_keyword = where; where_clause_constraints = constraints }
->
Concat
[
WithRule
( Rule.Parental,
Concat
[
Space;
Split;
t env where;
Nest
[
handle_possible_list
env
constraints
~before_each:space_split
~handle_last:
(transform_last_arg env ~allow_trailing:false)
~handle_element:(transform_argish_item env);
];
] );
]
| Syntax.WhereConstraint
{
where_constraint_left_type = left;
where_constraint_operator = op;
where_constraint_right_type = right;
} ->
Concat [t env left; Space; t env op; Space; t env right]
| Syntax.TypeRefinement
{
type_refinement_type = ty;
type_refinement_keyword = kw;
type_refinement_left_brace = left;
type_refinement_members = members;
type_refinement_right_brace = right;
} ->
Concat
[
t env ty;
Space;
t env kw;
Space;
t env left;
space_split ();
Nest
[
Span
[
handle_possible_list
env
~before_each:(fun _ ->
Concat
[
(if list_length members > 1 then
Newline
else
Space);
SplitWith Cost.Moderate;
])
~after_each:(fun last ->
if last then
if list_length members > 1 then
Newline
else
Space
else
Nothing)
members;
];
];
t env right;
]
| Syntax.TypeInRefinement
{
type_in_refinement_keyword = kw;
type_in_refinement_name = name;
type_in_refinement_type_parameters = type_params;
type_in_refinement_constraints = constraints;
type_in_refinement_equal = eq;
type_in_refinement_type = eq_bound;
}
| Syntax.CtxInRefinement
{
ctx_in_refinement_keyword = kw;
ctx_in_refinement_name = name;
ctx_in_refinement_type_parameters = type_params;
ctx_in_refinement_constraints = constraints;
ctx_in_refinement_equal = eq;
ctx_in_refinement_ctx_list = eq_bound;
} ->
Span
[
t env kw;
Space;
t env name;
t env type_params;
handle_possible_list env ~before_each:(fun _ -> Space) constraints;
when_present eq space;
t env eq;
when_present eq_bound (fun _ ->
Concat [Space; SplitWith Cost.High; Nest [t env eq_bound]]);
]
| Syntax.Contexts
{
contexts_left_bracket = lb;
contexts_types = tys;
contexts_right_bracket = rb;
} ->
transform_argish env lb tys rb
| Syntax.FunctionCtxTypeSpecifier
{ function_ctx_type_keyword = kw; function_ctx_type_variable = var } ->
Concat [t env kw; Space; t env var]
| Syntax.MethodishDeclaration
{
methodish_attribute = attr;
methodish_function_decl_header = func_decl;
methodish_function_body = body;
methodish_semicolon = semi;
} ->
Concat
[
t env attr;
when_present attr newline;
t env func_decl;
when_present body (fun () ->
handle_possible_compound_statement env ~allow_collapse:true body);
t env semi;
Newline;
]
| Syntax.MethodishTraitResolution
{
methodish_trait_attribute = attr;
methodish_trait_function_decl_header = func_decl;
methodish_trait_equal = equal;
methodish_trait_name = name;
methodish_trait_semicolon = semi;
} ->
Concat
[
t env attr;
when_present attr newline;
t env func_decl;
t env equal;
t env name;
t env semi;
Newline;
]
| Syntax.ClassishDeclaration
{
classish_attribute = attr;
classish_modifiers = modifiers;
classish_xhp = xhp;
classish_keyword = kw;
classish_name = name;
classish_type_parameters = type_params;
classish_extends_keyword = extends_kw;
classish_extends_list = extends;
classish_implements_keyword = impl_kw;
classish_implements_list = impls;
classish_where_clause = where;
classish_body = body;
} ->
let after_each_ancestor is_last =
if is_last then
Nothing
else
space_split ()
in
Concat
[
t env attr;
when_present attr newline;
Span
[
handle_possible_list env ~after_each:(fun _ -> Space) modifiers;
t env xhp;
when_present xhp space;
t env kw;
Space;
t env name;
t env type_params;
];
WithRule
( Rule.Parental,
Concat
[
when_present extends_kw (fun () ->
Nest
[
Space;
Split;
t env extends_kw;
WithRule
( Rule.Parental,
Nest
[
Span
[
Space;
(if list_length extends = 1 then
SplitWith Cost.Base
else
Split);
Nest
[
handle_possible_list
env
~after_each:after_each_ancestor
extends;
];
];
] );
]);
when_present impl_kw (fun () ->
Nest
[
Space;
Split;
t env impl_kw;
WithRule
( Rule.Parental,
Nest
[
Span
[
Space;
(if list_length impls = 1 then
SplitWith Cost.Base
else
Split);
Nest
[
handle_possible_list
env
~after_each:after_each_ancestor
impls;
];
];
] );
]);
when_present where space;
t env where;
] );
t env body;
]
| Syntax.ClassishBody
{
classish_body_left_brace = left_b;
classish_body_elements = body;
classish_body_right_brace = right_b;
} ->
Concat
[
Space;
braced_block_nest env left_b right_b [handle_possible_list env body];
Newline;
]
| Syntax.TraitUse
{
trait_use_keyword = kw;
trait_use_names = elements;
trait_use_semicolon = semi;
} ->
Concat
[
t env kw;
(match Syntax.syntax elements with
| Syntax.SyntaxList [x] -> Concat [Space; t env x]
| Syntax.SyntaxList _ ->
WithRule
( Rule.Parental,
Nest
[handle_possible_list env ~before_each:space_split elements]
)
| _ -> Concat [Space; t env elements]);
t env semi;
Newline;
]
| Syntax.RequireClause
{
require_keyword = kw;
require_kind = kind;
require_name = name;
require_semicolon = semi;
} ->
let name = t env name in
Concat
[
t env kw;
Space;
t env kind;
Space;
(if has_split name then
SplitWith Cost.High
else
Nothing);
Nest [name; t env semi];
Newline;
]
| Syntax.ConstDeclaration
{
const_attribute_spec = attr;
const_modifiers = modifiers;
const_keyword = kw;
const_type_specifier = const_type;
const_declarators = declarators;
const_semicolon = semi;
} ->
Concat
[
t env attr;
when_present attr newline;
handle_possible_list env ~after_each:(fun _ -> Space) modifiers;
t env kw;
when_present const_type space;
t env const_type;
handle_declarator_list env declarators;
t env semi;
Newline;
]
| Syntax.TypeConstDeclaration
{
type_const_attribute_spec = attr;
type_const_modifiers = modifiers;
type_const_keyword = kw;
type_const_type_keyword = type_kw;
type_const_name = name;
type_const_type_parameters = type_params;
type_const_type_constraints = type_constraints;
type_const_equal = eq;
type_const_type_specifier = type_spec;
type_const_semicolon = semi;
} ->
Concat
[
t env attr;
when_present attr newline;
handle_possible_list env ~after_each:(fun _ -> Space) modifiers;
Space;
t env kw;
Space;
t env type_kw;
Space;
t env name;
t env type_params;
handle_possible_list
env
~before_each:(fun _ -> Space)
type_constraints;
when_present eq space;
t env eq;
when_present type_spec (fun _ ->
Concat [Space; SplitWith Cost.Base; Nest [t env type_spec]]);
t env semi;
Newline;
]
| Syntax.ContextConstDeclaration
{
context_const_modifiers = modifiers;
context_const_const_keyword = kw;
context_const_ctx_keyword = ctx_kw;
context_const_name = name;
context_const_type_parameters = type_params;
context_const_constraint = constraint_list;
context_const_equal = eq;
context_const_ctx_list = ctx_list;
context_const_semicolon = semi;
} ->
Concat
[
handle_possible_list env ~after_each:(fun _ -> Space) modifiers;
Space;
t env kw;
Space;
t env ctx_kw;
Space;
t env name;
t env type_params;
when_present constraint_list space;
handle_possible_list
env
~after_each:(fun is_last ->
if is_last then
Nothing
else
Space)
constraint_list;
when_present eq space;
t env eq;
when_present ctx_list (fun _ ->
Concat [Space; SplitWith Cost.Base; Nest [t env ctx_list]]);
t env semi;
Newline;
]
| Syntax.ParameterDeclaration
{
parameter_attribute = attr;
parameter_visibility = visibility;
parameter_call_convention = callconv;
parameter_readonly = readonly;
parameter_type = param_type;
parameter_name = name;
parameter_default_value = default;
} ->
Concat
[
handle_attribute_spec env attr ~always_split:false;
when_present attr (fun _ -> Concat [Space; SplitWith Cost.Base]);
t env visibility;
when_present visibility space;
t env callconv;
when_present callconv space;
t env readonly;
when_present readonly space;
t env param_type;
(if
Syntax.is_missing visibility
&& Syntax.is_missing callconv
&& Syntax.is_missing param_type
then
t env name
else
Concat [Space; SplitWith Cost.Moderate; Nest [t env name]]);
t env default;
]
| Syntax.VariadicParameter
{
variadic_parameter_call_convention = callconv;
variadic_parameter_type = type_var;
variadic_parameter_ellipsis = ellipsis;
} ->
Concat
[
t env callconv;
when_present callconv space;
t env type_var;
t env ellipsis;
]
| Syntax.FileAttributeSpecification
{
file_attribute_specification_left_double_angle = left_da;
file_attribute_specification_keyword = keyword;
file_attribute_specification_colon = colon;
file_attribute_specification_attributes = attrs;
file_attribute_specification_right_double_angle = right_da;
} ->
Concat
[
t env left_da;
t env keyword;
t env colon;
when_present colon space;
transform_possible_comma_list env ~allow_trailing:false attrs right_da;
Newline;
]
| Syntax.OldAttributeSpecification _
| Syntax.AttributeSpecification _ ->
handle_attribute_spec env node ~always_split:true
| Syntax.Attribute { attribute_at = at; attribute_attribute_name = attr } ->
Concat [t env at; t env attr]
| Syntax.AttributizedSpecifier
{
attributized_specifier_attribute_spec = attr_spec;
attributized_specifier_type = attr_type;
} ->
Concat
[
handle_attribute_spec env attr_spec ~always_split:false;
Space;
t env attr_type;
]
| Syntax.InclusionExpression
{ inclusion_require = kw; inclusion_filename = expr } ->
Concat
[
t env kw;
(match Syntax.syntax expr with
| Syntax.ParenthesizedExpression _ -> Nothing
| _ -> Space);
SplitWith Cost.Base;
t env expr;
]
| Syntax.InclusionDirective
{ inclusion_expression = expr; inclusion_semicolon = semi } ->
Concat [t env expr; t env semi; Newline]
| Syntax.CompoundStatement
{ compound_left_brace; compound_statements; compound_right_brace } ->
Concat
[
handle_compound_statement
env
compound_left_brace
compound_statements
compound_right_brace;
Newline;
]
| Syntax.UnsetStatement
{
unset_keyword = kw;
unset_left_paren = left_p;
unset_variables = args;
unset_right_paren = right_p;
unset_semicolon = semi;
} ->
Concat
[
t env kw;
transform_argish env ~allow_trailing:false left_p args right_p;
t env semi;
Newline;
]
| Syntax.WhileStatement x ->
Concat
[
t env x.while_keyword;
Space;
t env x.while_left_paren;
Split;
WithRule
( Rule.Parental,
Concat
[
Nest [t env x.while_condition];
Split;
t env x.while_right_paren;
] );
handle_possible_compound_statement env x.while_body;
Newline;
]
| Syntax.UsingStatementBlockScoped x ->
Concat
[
t env x.using_block_await_keyword;
when_present x.using_block_await_keyword space;
t env x.using_block_using_keyword;
Space;
t env x.using_block_left_paren;
Split;
WithRule
( Rule.Parental,
Concat
[
Nest
[
handle_possible_list
env
~after_each:separate_with_space_split
x.using_block_expressions;
];
Split;
t env x.using_block_right_paren;
] );
handle_possible_compound_statement env x.using_block_body;
Newline;
]
| Syntax.UsingStatementFunctionScoped x ->
Concat
[
t env x.using_function_await_keyword;
when_present x.using_function_await_keyword space;
t env x.using_function_using_keyword;
Space;
t env x.using_function_expression;
t env x.using_function_semicolon;
Newline;
]
| Syntax.IfStatement
{
if_keyword = kw;
if_left_paren = left_p;
if_condition = condition;
if_right_paren = right_p;
if_statement = if_body;
if_else_clause = else_clause;
} ->
Concat
[
t env kw;
Space;
transform_condition env left_p condition right_p;
transform_consequence t env if_body right_p;
t env else_clause;
Newline;
]
| Syntax.ElseClause x ->
Concat
[
t env x.else_keyword;
(match Syntax.syntax x.else_statement with
| Syntax.IfStatement _ ->
Concat [Space; t env x.else_statement; Space]
| _ -> transform_consequence t env x.else_statement x.else_keyword);
]
| Syntax.TryStatement
{
try_keyword = kw;
try_compound_statement = body;
try_catch_clauses = catch_clauses;
try_finally_clause = finally_clause;
} ->
(* TODO: revisit *)
Concat
[
t env kw;
handle_possible_compound_statement env body;
handle_possible_list env catch_clauses;
t env finally_clause;
Newline;
]
| Syntax.CatchClause
{
catch_keyword = kw;
catch_left_paren = left_p;
catch_type = ex_type;
catch_variable = var;
catch_right_paren = right_p;
catch_body = body;
} ->
Concat
[
t env kw;
Space;
delimited_nest
env
left_p
right_p
[t env ex_type; Space; SplitWith Cost.Base; Nest [t env var]];
handle_possible_compound_statement env body;
]
| Syntax.FinallyClause { finally_keyword = kw; finally_body = body } ->
Concat [t env kw; Space; handle_possible_compound_statement env body]
| Syntax.DoStatement
{
do_keyword = do_kw;
do_body = body;
do_while_keyword = while_kw;
do_left_paren = left_p;
do_condition = cond;
do_right_paren = right_p;
do_semicolon = semi;
} ->
Concat
[
t env do_kw;
Space;
handle_possible_compound_statement env body;
t env while_kw;
Space;
transform_condition env left_p cond right_p;
t env semi;
Newline;
]
| Syntax.ForStatement
{
for_keyword = kw;
for_left_paren = left_p;
for_initializer = init;
for_first_semicolon = semi1;
for_control = control;
for_second_semicolon = semi2;
for_end_of_loop = after_iter;
for_right_paren = right_p;
for_body = body;
} ->
Concat
[
t env kw;
Space;
t env left_p;
WithRule
( Rule.Parental,
Concat
[
Split;
Nest
[
handle_possible_list
env
~after_each:separate_with_space_split
init;
t env semi1;
Space;
Split;
handle_possible_list
env
~after_each:separate_with_space_split
control;
t env semi2;
Space;
Split;
handle_possible_list
env
~after_each:separate_with_space_split
after_iter;
];
Split;
t env right_p;
] );
handle_possible_compound_statement env body;
Newline;
]
| Syntax.ForeachStatement
{
foreach_keyword = kw;
foreach_left_paren = left_p;
foreach_collection = collection;
foreach_await_keyword = await_kw;
foreach_as = as_kw;
foreach_key = key;
foreach_arrow = arrow;
foreach_value = value;
foreach_right_paren = right_p;
foreach_body = body;
} ->
Concat
[
t env kw;
Space;
delimited_nest
env
left_p
right_p
[
t env collection;
Space;
t env await_kw;
Space;
t env as_kw;
Space;
SplitWith Cost.Base;
Nest
[
Span
[
t env key;
Space;
t env arrow;
Space;
SplitWith Cost.Base;
Nest [t env value];
];
];
];
handle_possible_compound_statement env body;
Newline;
]
| Syntax.SwitchStatement
{
switch_keyword = kw;
switch_left_paren = left_p;
switch_expression = expr;
switch_right_paren = right_p;
switch_left_brace = left_b;
switch_sections = sections;
switch_right_brace = right_b;
} ->
let sections = Syntax.syntax_node_to_list sections in
Concat
[
t env kw;
Space;
delimited_nest env left_p right_p [t env expr];
Space;
braced_block_nest env left_b right_b (List.map sections ~f:(t env));
Newline;
]
| Syntax.SwitchSection
{
switch_section_labels = labels;
switch_section_statements = statements;
switch_section_fallthrough = fallthrough;
} ->
(* If there is FallThrough trivia leading the first case label, handle it
* in a BlockNest so that it is indented to the same level as the previous
* SwitchSection's statements. *)
let (labels_leading, labels) = remove_leading_trivia labels in
let (after_fallthrough, upto_fallthrough) =
List.split_while (List.rev labels_leading) ~f:(fun t ->
not (is_trivia_kind_fallthrough (Trivia.kind t)))
in
let upto_fallthrough = List.rev upto_fallthrough in
let after_fallthrough = List.rev after_fallthrough in
let labels = Syntax.syntax_node_to_list labels in
let statements = Syntax.syntax_node_to_list statements in
(* When the statements in the SwitchSection are wrapped in a single
* CompoundStatement, special-case the opening curly brace to appear on
* the same line as the case label. *)
let is_scoped_section =
match statements with
| [Syntax.{ syntax = CompoundStatement _; _ }] -> true
| _ -> false
in
Concat
[
(if List.is_empty upto_fallthrough then
transform_leading_trivia after_fallthrough
else
Concat
[
BlockNest [transform_leading_trivia upto_fallthrough; Newline];
transform_trailing_trivia after_fallthrough;
]);
handle_list env labels ~after_each:(fun is_last_label ->
if is_last_label && is_scoped_section then
Nothing
else
Newline);
(if is_scoped_section then
handle_list env statements
else
BlockNest [handle_list env statements]);
t env fallthrough;
]
| Syntax.CaseLabel
{ case_keyword = kw; case_expression = expr; case_colon = colon } ->
Concat [t env kw; Space; t env expr; t env colon]
| Syntax.DefaultLabel { default_keyword = kw; default_colon = colon } ->
Concat [t env kw; t env colon]
| Syntax.SwitchFallthrough
{ fallthrough_keyword = kw; fallthrough_semicolon = semi } ->
Concat [t env kw; t env semi]
| Syntax.MatchStatement
{
match_statement_keyword = kw;
match_statement_left_paren = left_p;
match_statement_expression = expr;
match_statement_right_paren = right_p;
match_statement_left_brace = left_b;
match_statement_arms = arms;
match_statement_right_brace = right_b;
} ->
let arms = Syntax.syntax_node_to_list arms in
Concat
[
t env kw;
Space;
delimited_nest env left_p right_p [t env expr];
Space;
braced_block_nest env left_b right_b (List.map arms ~f:(t env));
Newline;
]
| Syntax.MatchStatementArm
{
match_statement_arm_pattern = pattern;
match_statement_arm_arrow = arrow;
match_statement_arm_body = body;
} ->
Concat
[
t env pattern;
Space;
t env arrow;
Space;
(match Syntax.syntax body with
| Syntax.CompoundStatement
{ compound_left_brace; compound_statements; compound_right_brace }
->
handle_compound_statement
env
~allow_collapse:true
compound_left_brace
compound_statements
compound_right_brace
| _ -> Concat [SplitWith Cost.Base; Nest [t env body]]);
Newline;
]
| Syntax.ReturnStatement
{
return_keyword = kw;
return_expression = expr;
return_semicolon = semi;
} ->
transform_keyword_expression_statement env kw expr semi
| Syntax.YieldBreakStatement
{
yield_break_keyword = kw;
yield_break_break = y;
yield_break_semicolon = semi;
} ->
Concat [t env kw; Space; t env y; t env semi]
| Syntax.ThrowStatement
{ throw_keyword = kw; throw_expression = expr; throw_semicolon = semi }
->
transform_keyword_expression_statement env kw expr semi
| Syntax.BreakStatement { break_keyword = kw; break_semicolon = semi }
| Syntax.ContinueStatement
{ continue_keyword = kw; continue_semicolon = semi } ->
Concat [t env kw; t env semi; Newline]
| Syntax.EchoStatement
{
echo_keyword = kw;
echo_expressions = expr_list;
echo_semicolon = semi;
} ->
(match Syntax.syntax expr_list with
| Syntax.SyntaxList
[Syntax.{ syntax = ListItem { list_item = expr; _ }; _ }]
when is_syntax_kind_parenthesized_exprression (Syntax.kind expr) ->
Concat [t env kw; t env expr; t env semi; Newline]
| _ -> transform_keyword_expr_list_statement env kw expr_list semi)
| Syntax.ConcurrentStatement
{ concurrent_keyword = kw; concurrent_statement = statement } ->
Concat
[
t env kw;
Space;
handle_possible_compound_statement env statement;
Newline;
]
| Syntax.SimpleInitializer
{ simple_initializer_equal = eq_kw; simple_initializer_value = value }
->
Concat
[Space; t env eq_kw; Space; SplitWith Cost.Base; Nest [t env value]]
| Syntax.AnonymousFunction
{
anonymous_attribute_spec = attr;
anonymous_async_keyword = async_kw;
anonymous_function_keyword = fun_kw;
anonymous_left_paren = lp;
anonymous_parameters = params;
anonymous_right_paren = rp;
anonymous_ctx_list = ctx_list;
anonymous_colon = colon;
anonymous_readonly_return = readonly_ret;
anonymous_type = ret_type;
anonymous_use = use;
anonymous_body = body;
} ->
Concat
[
handle_attribute_spec env attr ~always_split:false;
when_present attr space;
t env async_kw;
when_present async_kw space;
t env fun_kw;
transform_argish_with_return_type
env
lp
params
rp
ctx_list
colon
readonly_ret
ret_type;
t env use;
handle_possible_compound_statement
env
~space:false
~allow_collapse:true
body;
]
| Syntax.AnonymousFunctionUseClause
{
anonymous_use_keyword = kw;
anonymous_use_left_paren = left_p;
anonymous_use_variables = vars;
anonymous_use_right_paren = right_p;
} ->
(* TODO: Revisit *)
Concat [Space; t env kw; Space; transform_argish env left_p vars right_p]
| Syntax.ConstructorPattern
{
constructor_pattern_constructor = name;
constructor_pattern_left_paren = lp;
constructor_pattern_members = members;
constructor_pattern_right_paren = rp;
} ->
if
Syntax.is_missing lp
&& Syntax.is_missing members
&& Syntax.is_missing rp
then
t env name
else
transform_container_literal env name lp members rp
| Syntax.RefinementPattern
{
refinement_pattern_variable = var;
refinement_pattern_colon = colon;
refinement_pattern_specifier = ty;
} ->
Concat [t env var; t env colon; Space; t env ty]
| Syntax.LambdaExpression
{
lambda_attribute_spec = attr;
lambda_async = async;
lambda_signature = signature;
lambda_arrow = arrow;
lambda_body = body;
} ->
Concat
[
handle_attribute_spec env attr ~always_split:false;
when_present attr space;
t env async;
when_present async space;
t env signature;
Space;
t env arrow;
handle_lambda_body env body;
]
| Syntax.LambdaSignature
{
lambda_left_paren = lp;
lambda_parameters = params;
lambda_right_paren = rp;
lambda_contexts = ctxs;
lambda_colon = colon;
lambda_readonly_return = readonly;
lambda_type = ret_type;
} ->
Concat
[
t env lp;
when_present params split;
transform_fn_decl_args env params rp;
t env ctxs;
t env colon;
when_present colon space;
t env readonly;
when_present readonly space;
t env ret_type;
]
| Syntax.CastExpression _ ->
Span (List.map (Syntax.children node) ~f:(t env))
| Syntax.MemberSelectionExpression _
| Syntax.SafeMemberSelectionExpression _ ->
handle_possible_chaining env node
| Syntax.YieldExpression { yield_keyword = kw; yield_operand = operand } ->
Concat [t env kw; Space; SplitWith Cost.Base; Nest [t env operand]]
| Syntax.PrefixUnaryExpression
{ prefix_unary_operator = operator; prefix_unary_operand = operand } ->
Concat
[
t env operator;
(match Syntax.syntax operator with
| Syntax.Token x ->
let is_parenthesized =
match Syntax.syntax operand with
| Syntax.ParenthesizedExpression _ -> true
| _ -> false
in
TokenKind.(
(match Token.kind x with
| Await
| Readonly
| Clone ->
Space
| Print ->
if is_parenthesized then
Nothing
else
Space
| _ -> Nothing))
| _ -> Nothing);
t env operand;
]
| Syntax.BinaryExpression
{ binary_left_operand; binary_operator; binary_right_operand } ->
transform_binary_expression
env
~is_nested:false
(binary_left_operand, binary_operator, binary_right_operand)
| Syntax.IsExpression
{ is_left_operand = left; is_operator = kw; is_right_operand = right }
| Syntax.AsExpression
{ as_left_operand = left; as_operator = kw; as_right_operand = right }
| Syntax.NullableAsExpression
{
nullable_as_left_operand = left;
nullable_as_operator = kw;
nullable_as_right_operand = right;
}
| Syntax.UpcastExpression
{
upcast_left_operand = left;
upcast_operator = kw;
upcast_right_operand = right;
} ->
Concat
[
t env left;
Space;
SplitWith Cost.Base;
Nest [t env kw; Space; t env right];
]
| Syntax.ConditionalExpression
{
conditional_test = test_expr;
conditional_question = q_kw;
conditional_consequence = true_expr;
conditional_colon = c_kw;
conditional_alternative = false_expr;
} ->
WithLazyRule
( Rule.Parental,
t env test_expr,
Nest
[
Space;
Split;
t env q_kw;
when_present true_expr (fun () ->
Concat
[
Space;
(if env.Env.indent_width = 2 then
Nest [t env true_expr]
else
t env true_expr);
Space;
Split;
]);
t env c_kw;
Space;
(if
(not (Syntax.is_missing true_expr)) && env.Env.indent_width = 2
then
Nest [t env false_expr]
else
t env false_expr);
] )
| Syntax.FunctionCallExpression _ -> handle_possible_chaining env node
| Syntax.FunctionPointerExpression _ -> transform_simple env node
| Syntax.EvalExpression
{
eval_keyword = kw;
eval_left_paren = left_p;
eval_argument = arg;
eval_right_paren = right_p;
} ->
Concat [t env kw; transform_braced_item env left_p arg right_p]
| Syntax.IssetExpression
{
isset_keyword = kw;
isset_left_paren = left_p;
isset_argument_list = args;
isset_right_paren = right_p;
} ->
Concat
[
t env kw;
transform_argish env ~allow_trailing:false left_p args right_p;
]
| Syntax.ParenthesizedExpression
{
parenthesized_expression_left_paren = left_p;
parenthesized_expression_expression = expr;
parenthesized_expression_right_paren = right_p;
} ->
Concat
[
t env left_p;
Split;
WithRule
(Rule.Parental, Concat [Nest [t env expr]; Split; t env right_p]);
]
| Syntax.ETSpliceExpression
{
et_splice_expression_dollar = dollar;
et_splice_expression_left_brace = left_p;
et_splice_expression_expression = expr;
et_splice_expression_right_brace = right_p;
} ->
Concat
[
t env dollar;
t env left_p;
Split;
WithRule
(Rule.Parental, Concat [Nest [t env expr]; Split; t env right_p]);
]
| Syntax.BracedExpression
{
braced_expression_left_brace = left_b;
braced_expression_expression = expr;
braced_expression_right_brace = right_b;
} ->
(* TODO: revisit this *)
Concat
[
t env left_b;
Split;
(let rule =
if
List.is_empty (Syntax.trailing_trivia left_b)
&& List.is_empty (Syntax.trailing_trivia expr)
then
Rule.Simple Cost.Base
else
Rule.Parental
in
WithRule (rule, Concat [Nest [t env expr]; Split; t env right_b]));
]
| Syntax.EmbeddedBracedExpression
{
embedded_braced_expression_left_brace = left_b;
embedded_braced_expression_expression = expr;
embedded_braced_expression_right_brace = right_b;
} ->
(* TODO: Consider finding a way to avoid treating these expressions as
opportunities for line breaks in long strings:
$sql = "DELETE FROM `foo` WHERE `left` BETWEEN {$res->left} AND {$res
->right} ORDER BY `level` DESC";
*)
Concat [t env left_b; Nest [t env expr]; t env right_b]
| Syntax.ListExpression
{
list_keyword = kw;
list_left_paren = lp;
list_members = members;
list_right_paren = rp;
} ->
Concat [t env kw; transform_argish env lp members rp]
| Syntax.CollectionLiteralExpression
{
collection_literal_name = name;
collection_literal_left_brace = left_b;
collection_literal_initializers = initializers;
collection_literal_right_brace = right_b;
} ->
transform_container_literal
env
~space:true
name
left_b
initializers
right_b
| Syntax.ObjectCreationExpression
{ object_creation_new_keyword = newkw; object_creation_object = what }
->
Concat [t env newkw; Space; t env what]
| Syntax.ConstructorCall
{
constructor_call_type = obj_type;
constructor_call_left_paren = left_p;
constructor_call_argument_list = arg_list;
constructor_call_right_paren = right_p;
} ->
Concat [t env obj_type; transform_argish env left_p arg_list right_p]
| Syntax.AnonymousClass
{
anonymous_class_class_keyword = classkw;
anonymous_class_left_paren = left_p;
anonymous_class_argument_list = arg_list;
anonymous_class_right_paren = right_p;
anonymous_class_extends_keyword = extends_kw;
anonymous_class_extends_list = extends;
anonymous_class_implements_keyword = impl_kw;
anonymous_class_implements_list = impls;
anonymous_class_body = body;
} ->
let after_each_ancestor is_last =
if is_last then
Nothing
else
space_split ()
in
Concat
[
t env classkw;
transform_argish env left_p arg_list right_p;
when_present extends_kw (fun () ->
Concat
[
Space;
Split;
WithRule
( Rule.Parental,
Nest
[
Span
[
t env extends_kw;
Space;
Split;
WithRule
( Rule.Parental,
Nest
[
handle_possible_list
env
~after_each:after_each_ancestor
extends;
] );
];
] );
]);
when_present impl_kw (fun () ->
Concat
[
Space;
Split;
WithRule
( Rule.Parental,
Nest
[
Span
[
t env impl_kw;
Space;
Split;
WithRule
( Rule.Parental,
Nest
[
handle_possible_list
env
~after_each:after_each_ancestor
impls;
] );
];
] );
]);
t env body;
]
| Syntax.DarrayIntrinsicExpression
{
darray_intrinsic_keyword = kw;
darray_intrinsic_explicit_type = explicit_type;
darray_intrinsic_left_bracket = left_p;
darray_intrinsic_members = members;
darray_intrinsic_right_bracket = right_p;
}
| Syntax.DictionaryIntrinsicExpression
{
dictionary_intrinsic_keyword = kw;
dictionary_intrinsic_explicit_type = explicit_type;
dictionary_intrinsic_left_bracket = left_p;
dictionary_intrinsic_members = members;
dictionary_intrinsic_right_bracket = right_p;
}
| Syntax.KeysetIntrinsicExpression
{
keyset_intrinsic_keyword = kw;
keyset_intrinsic_explicit_type = explicit_type;
keyset_intrinsic_left_bracket = left_p;
keyset_intrinsic_members = members;
keyset_intrinsic_right_bracket = right_p;
}
| Syntax.VarrayIntrinsicExpression
{
varray_intrinsic_keyword = kw;
varray_intrinsic_explicit_type = explicit_type;
varray_intrinsic_left_bracket = left_p;
varray_intrinsic_members = members;
varray_intrinsic_right_bracket = right_p;
}
| Syntax.VectorIntrinsicExpression
{
vector_intrinsic_keyword = kw;
vector_intrinsic_explicit_type = explicit_type;
vector_intrinsic_left_bracket = left_p;
vector_intrinsic_members = members;
vector_intrinsic_right_bracket = right_p;
} ->
transform_container_literal env kw ~explicit_type left_p members right_p
| Syntax.ElementInitializer
{ element_key = key; element_arrow = arrow; element_value = value } ->
transform_mapish_entry env key arrow value
| Syntax.SubscriptExpression
{
subscript_receiver = receiver;
subscript_left_bracket = lb;
subscript_index = expr;
subscript_right_bracket = rb;
} ->
Concat [t env receiver; transform_braced_item env lb expr rb]
| Syntax.AwaitableCreationExpression
{
awaitable_attribute_spec = attr;
awaitable_async = async_kw;
awaitable_compound_statement = body;
} ->
Concat
[
handle_attribute_spec env attr ~always_split:false;
when_present attr space;
t env async_kw;
when_present async_kw space;
(* TODO: rethink possible one line bodies *)
(* TODO: correctly handle spacing after the closing brace *)
handle_possible_compound_statement env ~space:false body;
]
| Syntax.XHPChildrenDeclaration
{
xhp_children_keyword = kw;
xhp_children_expression = expr;
xhp_children_semicolon = semi;
} ->
Concat [t env kw; Space; t env expr; t env semi; Newline]
| Syntax.XHPChildrenParenthesizedList
{
xhp_children_list_left_paren = left_p;
xhp_children_list_xhp_children = expressions;
xhp_children_list_right_paren = right_p;
} ->
Concat
[transform_argish env ~allow_trailing:false left_p expressions right_p]
| Syntax.XHPCategoryDeclaration
{
xhp_category_keyword = kw;
xhp_category_categories = categories;
xhp_category_semicolon = semi;
} ->
Concat
[
t env kw;
(* TODO: Eliminate code duplication *)
WithRule
( Rule.Parental,
Nest
[handle_possible_list env ~before_each:space_split categories]
);
t env semi;
Newline;
]
| Syntax.XHPEnumType
{
xhp_enum_like = l;
xhp_enum_keyword = kw;
xhp_enum_left_brace = left_b;
xhp_enum_values = values;
xhp_enum_right_brace = right_b;
} ->
Concat
[t env l; t env kw; Space; transform_argish env left_b values right_b]
| Syntax.XHPClassAttributeDeclaration
{
xhp_attribute_keyword = kw;
xhp_attribute_attributes = xhp_attributes;
xhp_attribute_semicolon = semi;
} ->
Concat
[
t env kw;
(match Syntax.syntax xhp_attributes with
| Syntax.Missing -> Nothing
| Syntax.SyntaxList [attr] ->
WithRule (Rule.Parental, Nest [Space; Split; t env attr])
| Syntax.SyntaxList attrs ->
Nest [handle_list env ~before_each:newline attrs]
| _ -> failwith "Expected SyntaxList");
t env semi;
Newline;
]
| Syntax.XHPClassAttribute
{
xhp_attribute_decl_type = attr_type;
xhp_attribute_decl_name = name;
xhp_attribute_decl_initializer = init;
xhp_attribute_decl_required = req;
} ->
(* TODO: figure out nesting here *)
Concat
[
t env attr_type;
Space;
t env name;
when_present init space;
t env init;
when_present req space;
t env req;
]
| Syntax.XHPSimpleAttribute
{
xhp_simple_attribute_name = name;
xhp_simple_attribute_equal = eq;
xhp_simple_attribute_expression = expr;
} ->
Span [t env name; t env eq; SplitWith Cost.Base; Nest [t env expr]]
| Syntax.XHPSpreadAttribute
{
xhp_spread_attribute_left_brace = l_brace;
xhp_spread_attribute_spread_operator = spread;
xhp_spread_attribute_expression = expr;
xhp_spread_attribute_right_brace = r_brace;
} ->
Span
[
t env l_brace;
t env spread;
SplitWith Cost.Base;
Nest [t env expr];
t env r_brace;
]
| Syntax.XHPOpen
{
xhp_open_left_angle = left_a;
xhp_open_name = name;
xhp_open_attributes = attrs;
xhp_open_right_angle = right_a;
} ->
Concat
[
t env left_a;
t env name;
(match Syntax.syntax attrs with
| Syntax.Missing ->
handle_xhp_open_right_angle_token env attrs right_a
| _ ->
Concat
[
Space;
Split;
WithRule
( Rule.Parental,
Concat
[
Nest
[
handle_possible_list
env
~after_each:(fun is_last ->
if not is_last then
space_split ()
else
Nothing)
attrs;
];
handle_xhp_open_right_angle_token env attrs right_a;
] );
]);
]
| Syntax.XHPExpression { xhp_open; xhp_body = body; xhp_close = close } ->
let handle_xhp_body body =
match Syntax.syntax body with
| Syntax.Missing -> when_present close split
| Syntax.SyntaxList xs ->
(* Trivia is lexed differently within an XHP body because whitespace is
semantically significant in an XHP body when it is adjacent to an
XHPBody token. Any number of whitespaces or newlines adjacent to an
XHPBody token will be rendered as a single space. In order to make it
easier to determine whether a space character should be rendered next
to an XHPBody token, all trailing trivia in an XHP body is lexed as
leading trivia for the next token (except on XHPBody tokens, where
trailing trivia is lexed normally). This ensures that any time
semantically-significant whitespace is present, at least some of it
occurs in the leading or trailing trivia list of an adjacent XHPBody
token.
To deal with this, we keep track of whether the last token we
transformed was one that trailing trivia is scanned for. If it
wasn't, we handle the next token's leading trivia list using
transform_xhp_leading_trivia, which treats all trivia up to the first
newline as trailing trivia. *)
let prev_token_was_xhpbody = ref false in
let transformed_body =
Concat
(List.map xs ~f:(fun node ->
let node_is_xhpbody =
match Syntax.syntax node with
| Syntax.Token t -> is_token_kind_xhp_body (Token.kind t)
| _ -> false
in
(* Here, we preserve newlines after XHPBody tokens and don't otherwise
add splits between them. This means that we don't reflow paragraphs
in XHP to fit in the desired line length. It would be nice to do
so, but this is not possible with the current set of Rule types.
If we were to add a split between each XHPBody token instead of
splitting only where newlines were already present, we'd need a new
Rule type to govern word-wrap style splitting, since using
independent splits (e.g. SplitWith Cost.Base) between every token
would make solving too expensive. *)
let preserve_xhpbody_whitespace trivia =
if node_is_xhpbody then
if has_newline trivia then
Newline
else if has_whitespace trivia then
Space
else
Nothing
else
Nothing
in
let (leading, node) = remove_leading_trivia node in
let trailing = Syntax.trailing_trivia node in
let leading_whitespace =
Concat
[
(* Whitespace in an XHP body is *only* significant when adjacent to
an XHPBody token, so we are free to add splits between other
nodes (like XHPExpressions and BracedExpressions). *)
(if
(not !prev_token_was_xhpbody) && not node_is_xhpbody
then
Split
else
Nothing);
(* If the previous token was an XHPBody token, the lexer will have
scanned trailing trivia for it, so we can handle the leading
trivia for this node normally. Otherwise, handle the trivia up to
the first newline as trailing trivia. *)
(if !prev_token_was_xhpbody then
transform_leading_trivia leading
else
transform_xhp_leading_trivia leading);
]
in
prev_token_was_xhpbody := node_is_xhpbody;
Concat
[
leading_whitespace;
preserve_xhpbody_whitespace leading;
t env node;
preserve_xhpbody_whitespace trailing;
]))
in
Concat
[
transformed_body;
(if !prev_token_was_xhpbody then
Nothing
else if
(* Don't collapse XHPExpressions onto a single line if they were
intentionally split across multiple lines in the original source.
If there is a newline in the body's leading trivia, we consider
that a signal that this expression was intended to be split
across multiple lines. *)
has_newline (Syntax.leading_trivia body)
then
Newline
else
Split);
]
| _ -> failwith "Expected SyntaxList"
in
WithOverridingParentalRule
(Concat
[
t env xhp_open;
Nest [handle_xhp_body body];
when_present close (fun () ->
let (leading, close) = remove_leading_trivia close in
Concat
[
(* Ignore extra newlines by treating this as trailing trivia *)
ignore_trailing_invisibles leading;
t env close;
]);
])
| Syntax.VarrayTypeSpecifier
{
varray_keyword = kw;
varray_left_angle = left_a;
varray_type;
varray_trailing_comma = trailing_comma;
varray_right_angle = right_a;
} ->
Concat
[
t env kw;
transform_braced_item_with_trailer
env
left_a
varray_type
trailing_comma
right_a;
]
| Syntax.VectorTypeSpecifier
{
vector_type_keyword = kw;
vector_type_left_angle = left_a;
vector_type_type = vec_type;
vector_type_trailing_comma = trailing_comma;
vector_type_right_angle = right_a;
} ->
Concat
[
t env kw;
transform_braced_item_with_trailer
env
left_a
vec_type
trailing_comma
right_a;
]
| Syntax.KeysetTypeSpecifier
{
keyset_type_keyword = kw;
keyset_type_left_angle = left_a;
keyset_type_type = ks_type;
keyset_type_trailing_comma = trailing_comma;
keyset_type_right_angle = right_a;
} ->
Concat
[
t env kw;
transform_braced_item_with_trailer
env
left_a
ks_type
trailing_comma
right_a;
]
| Syntax.TypeParameter
{
type_attribute_spec = attr;
type_reified = reified;
type_variance = variance;
type_name = name;
type_param_params = params;
type_constraints = constraints;
} ->
Concat
[
handle_attribute_spec env attr ~always_split:false;
when_present attr space;
t env reified;
when_present reified space;
t env variance;
t env name;
t env params;
when_present constraints space;
handle_possible_list env constraints ~after_each:(fun is_last ->
if is_last then
Nothing
else
Space);
]
| Syntax.TypeConstraint { constraint_keyword = kw; constraint_type } ->
Concat [t env kw; Space; t env constraint_type]
| Syntax.ContextConstraint
{ ctx_constraint_keyword = kw; ctx_constraint_ctx_list = ctx_list } ->
Concat [Space; t env kw; Space; t env ctx_list]
| Syntax.DarrayTypeSpecifier
{
darray_keyword = kw;
darray_left_angle = left_a;
darray_key = key;
darray_comma = comma_kw;
darray_value = value;
darray_trailing_comma = trailing_comma;
darray_right_angle = right_a;
} ->
let key_list_item = Syntax.make_list_item key comma_kw in
let val_list_item = Syntax.make_list_item value trailing_comma in
let args = make_list [key_list_item; val_list_item] in
Concat
[
t env kw; transform_argish env ~allow_trailing:true left_a args right_a;
]
| Syntax.DictionaryTypeSpecifier
{
dictionary_type_keyword = kw;
dictionary_type_left_angle = left_a;
dictionary_type_members = members;
dictionary_type_right_angle = right_a;
} ->
Concat [t env kw; transform_argish env left_a members right_a]
| Syntax.ClosureTypeSpecifier
{
closure_outer_left_paren = outer_left_p;
closure_readonly_keyword = ro;
closure_function_keyword = kw;
closure_inner_left_paren = inner_left_p;
closure_parameter_list = param_list;
closure_inner_right_paren = inner_right_p;
closure_contexts = ctxs;
closure_colon = colon;
closure_readonly_return = readonly;
closure_return_type = ret_type;
closure_outer_right_paren = outer_right_p;
} ->
Concat
[
t env outer_left_p;
t env ro;
when_present ro space;
t env kw;
t env inner_left_p;
when_present param_list split;
transform_fn_decl_args env param_list inner_right_p;
t env ctxs;
t env colon;
when_present colon space;
t env readonly;
when_present readonly space;
t env ret_type;
t env outer_right_p;
]
| Syntax.ClosureParameterTypeSpecifier
{
closure_parameter_call_convention = callconv;
closure_parameter_readonly = readonly;
closure_parameter_type = cp_type;
} ->
Concat
[
t env callconv;
when_present callconv space;
t env readonly;
when_present readonly space;
t env cp_type;
]
| Syntax.ClassnameTypeSpecifier
{
classname_keyword = kw;
classname_left_angle = left_a;
classname_type = class_type;
classname_trailing_comma = trailing_comma;
classname_right_angle = right_a;
} ->
Concat
[
t env kw;
transform_braced_item_with_trailer
env
left_a
class_type
trailing_comma
right_a;
]
| Syntax.FieldSpecifier
{
field_question = question;
field_name = name;
field_arrow = arrow_kw;
field_type;
} ->
Concat
[t env question; transform_mapish_entry env name arrow_kw field_type]
| Syntax.FieldInitializer
{
field_initializer_name = name;
field_initializer_arrow = arrow_kw;
field_initializer_value = value;
} ->
transform_mapish_entry env name arrow_kw value
| Syntax.ShapeTypeSpecifier
{
shape_type_keyword = shape_kw;
shape_type_left_paren = left_p;
shape_type_fields = type_fields;
shape_type_ellipsis = ellipsis;
shape_type_right_paren = right_p;
} ->
let fields =
if Syntax.is_missing ellipsis then
type_fields
else
let missing_separator = make_missing () in
let ellipsis_list =
[Syntax.make_list_item ellipsis missing_separator]
in
make_list (Syntax.children type_fields @ ellipsis_list)
in
transform_container_literal
env
shape_kw
left_p
fields
right_p
~allow_trailing:(Syntax.is_missing ellipsis)
| Syntax.ShapeExpression
{
shape_expression_keyword = shape_kw;
shape_expression_left_paren = left_p;
shape_expression_fields = fields;
shape_expression_right_paren = right_p;
} ->
transform_container_literal env shape_kw left_p fields right_p
| Syntax.TupleExpression
{
tuple_expression_keyword = kw;
tuple_expression_left_paren = left_p;
tuple_expression_items = items;
tuple_expression_right_paren = right_p;
} ->
Concat [t env kw; transform_argish env left_p items right_p]
| Syntax.TypeArguments
{
type_arguments_left_angle = left_a;
type_arguments_types = type_list;
type_arguments_right_angle = right_a;
} ->
transform_argish env left_a type_list right_a
| Syntax.TypeParameters
{
type_parameters_left_angle = left_a;
type_parameters_parameters = param_list;
type_parameters_right_angle = right_a;
} ->
transform_argish env left_a param_list right_a
| Syntax.TupleTypeSpecifier
{
tuple_left_paren = left_p;
tuple_types = types;
tuple_right_paren = right_p;
} ->
transform_argish env left_p types right_p
| Syntax.UnionTypeSpecifier
{
union_left_paren = left_p;
union_types = types;
union_right_paren = right_p;
} ->
delimited_nest
env
left_p
right_p
[
handle_possible_list
env
types
~after_each:(fun is_last ->
if is_last then
Split
else
space_split ())
~handle_element:(fun node ->
match Syntax.syntax node with
| Syntax.ListItem { list_item; list_separator } ->
Concat
[
t env list_item;
when_present list_separator space;
t env list_separator;
]
| _ -> t env node);
]
| Syntax.IntersectionTypeSpecifier
{
intersection_left_paren = left_p;
intersection_types = types;
intersection_right_paren = right_p;
} ->
delimited_nest
env
left_p
right_p
[
handle_possible_list
env
types
~after_each:(fun is_last ->
if is_last then
Split
else
space_split ())
~handle_element:(fun node ->
match Syntax.syntax node with
| Syntax.ListItem { list_item; list_separator } ->
Concat
[
t env list_item;
when_present list_separator space;
t env list_separator;
]
| _ -> t env node);
]
| Syntax.TupleTypeExplicitSpecifier
{
tuple_type_keyword = kw;
tuple_type_left_angle = left_a;
tuple_type_types = types;
tuple_type_right_angle = right_a;
} ->
Concat [t env kw; transform_argish env left_a types right_a]
| Syntax.PrefixedCodeExpression
{
prefixed_code_prefix = prefix;
prefixed_code_left_backtick = left_bt;
prefixed_code_body = body;
prefixed_code_right_backtick = right_bt;
} -> begin
match Syntax.syntax body with
| Syntax.CompoundStatement
{ compound_left_brace; compound_statements; compound_right_brace } ->
Concat
[
t env prefix;
t env left_bt;
handle_compound_statement
env
~allow_collapse:true
~prepend_space:false
compound_left_brace
compound_statements
compound_right_brace;
t env right_bt;
]
| _ ->
Concat [t env prefix; transform_braced_item env left_bt body right_bt]
end
| Syntax.DecoratedExpression
{
decorated_expression_decorator = op;
decorated_expression_expression = expr;
} ->
Concat
[
t env op;
begin
match Syntax.syntax op with
| Syntax.Token t when is_token_kind_in_out (Token.kind t) -> Space
| _ -> Nothing
end;
t env expr;
]
| Syntax.ErrorSyntax _ -> raise Hackfmt_error.InvalidSyntax
| Syntax.EnumClassDeclaration
{
enum_class_attribute_spec = attr_spec;
enum_class_modifiers = modifiers;
enum_class_enum_keyword = enum_kw;
enum_class_class_keyword = class_kw;
enum_class_name = name;
enum_class_colon = colon;
enum_class_base = base;
enum_class_extends = extends_kw;
enum_class_extends_list = extends_list;
enum_class_left_brace = left_brace;
enum_class_elements = elements;
enum_class_right_brace = right_brace;
} ->
let after_each_ancestor is_last =
if is_last then
Nothing
else
space_split ()
in
Concat
[
t env attr_spec;
when_present attr_spec newline;
handle_possible_list env ~after_each:(fun _ -> Space) modifiers;
t env enum_kw;
Space;
t env class_kw;
Space;
t env name;
t env colon;
Space;
SplitWith Cost.Base;
Nest [Space; t env base; Space];
when_present extends_kw (fun () ->
Nest
[
Space;
Split;
t env extends_kw;
WithRule
( Rule.Parental,
Nest
[
Span
[
Space;
(if list_length extends_list = 1 then
SplitWith Cost.Base
else
Split);
Nest
[
handle_possible_list
env
~after_each:after_each_ancestor
extends_list;
];
];
] );
]);
Space;
braced_block_nest
env
left_brace
right_brace
[handle_possible_list env elements];
Newline;
]
| Syntax.EnumClassEnumerator
{
enum_class_enumerator_modifiers = modifiers;
enum_class_enumerator_type = type_;
enum_class_enumerator_name = name;
enum_class_enumerator_initializer = init;
enum_class_enumerator_semicolon = semicolon;
} ->
Concat
[
handle_possible_list env ~after_each:(fun _ -> Space) modifiers;
t env type_;
when_present type_ space;
t env name;
t env init;
t env semicolon;
Newline;
]
| Syntax.EnumClassLabelExpression _ -> transform_simple env node
| Syntax.ModuleDeclaration
{
module_declaration_attribute_spec = attr;
module_declaration_new_keyword = new_kw;
module_declaration_module_keyword = mod_kw;
module_declaration_name = name;
module_declaration_left_brace = lb;
module_declaration_exports = exports;
module_declaration_imports = imports;
module_declaration_right_brace = rb;
} ->
Concat
[
t env attr;
when_present attr newline;
t env new_kw;
Space;
t env mod_kw;
Space;
t env name;
Space;
t env lb;
Newline;
t env exports;
when_present exports newline;
t env imports;
when_present imports newline;
t env rb;
Newline;
]
| Syntax.ModuleExports
{
module_exports_exports_keyword = exports_kw;
module_exports_left_brace = lb;
module_exports_exports = exports;
module_exports_right_brace = rb;
} ->
Concat
[
t env exports_kw;
Space;
t env lb;
Newline;
WithRule
( Rule.Parental,
Nest
[
handle_possible_list
env
exports
~after_each:after_each_argument;
] );
t env rb;
Newline;
]
| Syntax.ModuleImports
{
module_imports_imports_keyword = imports_kw;
module_imports_left_brace = lb;
module_imports_imports = imports;
module_imports_right_brace = rb;
} ->
Concat
[
t env imports_kw;
Space;
t env lb;
Newline;
WithRule
( Rule.Parental,
Nest
[
handle_possible_list
env
imports
~after_each:after_each_argument;
] );
t env rb;
Newline;
]
| Syntax.ModuleMembershipDeclaration
{
module_membership_declaration_module_keyword = mod_kw;
module_membership_declaration_name = name;
module_membership_declaration_semicolon = semicolon;
} ->
Concat [t env mod_kw; Space; t env name; t env semicolon; Newline]
| Syntax.PackageExpression
{ package_expression_keyword = pkg_kw; package_expression_name = name }
->
Concat [t env pkg_kw; Space; t env name]
| Syntax.DeclareLocalStatement
{
declare_local_keyword;
declare_local_variable;
declare_local_colon;
declare_local_type;
declare_local_initializer;
declare_local_semicolon;
} ->
Concat
[
t env declare_local_keyword;
Space;
t env declare_local_variable;
t env declare_local_colon;
SplitWith Cost.Base;
Space;
Nest [t env declare_local_type];
t env declare_local_initializer;
t env declare_local_semicolon;
Newline;
])
and when_present node f =
match Syntax.syntax node with
| Syntax.Missing -> Nothing
| _ -> f ()
and transform_simple env node =
Concat (List.map (Syntax.children node) ~f:(t env))
and transform_simple_statement env node =
Concat (List.map (Syntax.children node) ~f:(t env) @ [Newline])
and braced_block_nest env ?(allow_collapse = true) open_b close_b nodes =
let nodes = Concat nodes in
match (allow_collapse, has_printable_content nodes, Syntax.syntax open_b) with
| (true, false, Syntax.Token ob)
when List.for_all (Token.trailing ob) ~f:(fun t ->
not (is_trivia_kind_end_of_line (Trivia.kind t))) ->
Concat [t env open_b; t env close_b]
| (true, false, Syntax.Missing) -> Concat [t env open_b; t env close_b]
| _ ->
(* Remove the closing brace's leading trivia and handle it inside the
* BlockNest, so that comments will be indented correctly. *)
let (leading, close_b) = remove_leading_trivia close_b in
Concat
[
t env open_b;
Newline;
BlockNest [nodes; transform_leading_trivia leading; Newline];
t env close_b;
]
and delimited_nest
env
?(split_when_children_split = true)
?(force_newlines = false)
left_delim
right_delim
nodes =
let rule =
match () with
| _ when force_newlines -> Rule.Always
| _ when split_when_children_split -> Rule.Parental
| _ -> Rule.Simple Cost.Base
in
Span [t env left_delim; WithRule (rule, nest env right_delim nodes)]
and nest env ?(spaces = false) right_delim nodes =
(* Remove the right delimiter's leading trivia and handle it inside the
* Nest, so that comments will be indented correctly. *)
let (leading, right_delim) = remove_leading_trivia right_delim in
let nested_contents = Nest [Concat nodes; transform_leading_trivia leading] in
let content_present = has_printable_content nested_contents in
let maybe_split =
match (content_present, spaces) with
| (false, _) -> Nothing
| (true, false) -> Split
| (true, true) -> space_split ()
in
Concat [maybe_split; nested_contents; maybe_split; t env right_delim]
and after_each_argument is_last =
if is_last then
Split
else
space_split ()
and separate_with_space_split is_last =
if is_last then
Nothing
else
space_split ()
and handle_attribute_spec env node ~always_split =
match Syntax.syntax node with
| Syntax.OldAttributeSpecification
{
old_attribute_specification_left_double_angle = left_da;
old_attribute_specification_attributes = attrs;
old_attribute_specification_right_double_angle = right_da;
} ->
transform_argish env left_da attrs right_da
| Syntax.AttributeSpecification { attribute_specification_attributes = attrs }
->
handle_possible_list
env
~after_each:(fun _ ->
if always_split then
Newline
else
Space)
attrs
| Syntax.Missing -> Nothing
| _ -> failwith "Attribute specification expected"
and handle_lambda_body env node =
match Syntax.syntax node with
| Syntax.CompoundStatement
{ compound_left_brace; compound_statements; compound_right_brace } ->
handle_compound_statement
env
~allow_collapse:true
compound_left_brace
compound_statements
compound_right_brace
| Syntax.XHPExpression _ ->
WithRule (Rule.Parental, Concat [Space; Split; Nest [t env node]])
| _ -> Concat [Space; SplitWith Cost.Base; Nest [t env node]]
and handle_possible_compound_statement
env ?(space = true) ?(allow_collapse = false) node =
match Syntax.syntax node with
| Syntax.CompoundStatement
{ compound_left_brace; compound_statements; compound_right_brace } ->
Concat
[
handle_compound_statement
env
~allow_collapse
compound_left_brace
compound_statements
compound_right_brace;
(if space then
Space
else
Nothing);
]
| Syntax.Token _ -> t env node
| _ -> Concat [Newline; BlockNest [t env node]]
and handle_compound_statement
env
?(allow_collapse = false)
?(prepend_space = true)
left_b
statements
right_b =
Concat
[
(if prepend_space then
Space
else
Nothing);
braced_block_nest
env
~allow_collapse
left_b
right_b
[handle_possible_list env statements];
]
(**
* Special-case handling for lists of declarators, where we want the splits
* between declarators to break if their children break, but we want a single
* declarator to stay joined with the line preceding it if it fits, even when
* its children break.
*)
and handle_declarator_list env declarators =
match Syntax.syntax declarators with
| Syntax.Missing -> Nothing
| Syntax.SyntaxList [declarator] ->
Nest
[
Space;
(* Use an independent split, so we don't break just because a line break
* occurs in the declarator. *)
SplitWith Cost.Base;
t env declarator;
]
| Syntax.SyntaxList xs ->
(* Use Rule.Parental to break each declarator onto its own line if any
* line break occurs in a declarator, or if they can't all fit onto one
* line. *)
WithRule
( Rule.Parental,
Nest
(List.map xs ~f:(fun declarator ->
Concat [Space; Split; t env declarator])) )
| _ -> failwith "SyntaxList expected"
and handle_list
env
?(before_each = (fun () -> Nothing))
?(after_each = (fun _is_last -> Nothing))
?(handle_element = t env)
?(handle_last = handle_element)
list =
let rec aux l =
match l with
| [hd] -> Concat [before_each (); handle_last hd; after_each true]
| hd :: tl ->
Concat [before_each (); handle_element hd; after_each false; aux tl]
| [] -> Nothing
in
aux list
and list_length node =
match Syntax.syntax node with
| Syntax.Missing -> 0
| Syntax.SyntaxList x -> List.length x
| _ -> 1
and handle_possible_list
env ?before_each ?after_each ?handle_element ?handle_last node =
match Syntax.syntax node with
| Syntax.Missing -> Nothing
| Syntax.SyntaxList x ->
handle_list env x ?before_each ?after_each ?handle_element ?handle_last
| _ ->
handle_list env [node] ?before_each ?after_each ?handle_element ?handle_last
and handle_xhp_open_right_angle_token env attrs node =
match Syntax.syntax node with
| Syntax.Token token ->
Concat
[
(if String.equal (Token.text token) "/>" then
Concat [Space; when_present attrs split]
else
Nothing);
t env node;
]
| _ -> failwith "expected xhp_open right_angle token"
and handle_possible_chaining env node =
let rec handle_member_selection acc (receiver, arrow, member, targs) args =
let (first_receiver, acc) = handle_chaining acc receiver in
(first_receiver, (arrow, member, targs, args) :: acc)
and handle_fun_call acc node receiver targs lp args rp =
match Syntax.syntax receiver with
| Syntax.MemberSelectionExpression
{ member_object = obj; member_operator = arrow; member_name = member }
| Syntax.SafeMemberSelectionExpression
{
safe_member_object = obj;
safe_member_operator = arrow;
safe_member_name = member;
} ->
handle_member_selection
acc
( obj,
arrow,
member,
if Syntax.is_missing targs then
None
else
Some targs )
(Some (lp, args, rp))
| _ -> (node, [])
and handle_chaining acc node =
match Syntax.syntax node with
| Syntax.FunctionCallExpression
{
function_call_receiver = receiver;
function_call_type_args = targs;
function_call_left_paren = lp;
function_call_argument_list = args;
function_call_right_paren = rp;
} ->
handle_fun_call acc node receiver targs lp args rp
| Syntax.MemberSelectionExpression
{ member_object = obj; member_operator = arrow; member_name = member }
| Syntax.SafeMemberSelectionExpression
{
safe_member_object = obj;
safe_member_operator = arrow;
safe_member_name = member;
} ->
handle_member_selection acc (obj, arrow, member, None) None
| _ -> (node, [])
in
(* It's easy to end up with an infinite loop by passing an unexpected node
kind here, so confirm that we have an expected kind in hand. *)
let () =
match Syntax.kind node with
| SyntaxKind.FunctionCallExpression
| SyntaxKind.MemberSelectionExpression
| SyntaxKind.SafeMemberSelectionExpression ->
()
| kind ->
failwith
("Unexpected SyntaxKind in handle_possible_chaining: "
^ SyntaxKind.show kind)
in
(* Flatten nested member selection expressions into the first receiver and a
list of member selections.
E.g., transform $x->a->b->c into ($x, [->a; ->b; ->c]) *)
let (first_receiver, chain_list) = handle_chaining [] node in
let chain_list = List.rev chain_list in
let transform_chain (arrow, member, targs, argish) =
Concat
[
t env arrow;
t env member;
Option.value_map targs ~default:Nothing ~f:(t env);
Option.value_map argish ~default:Nothing ~f:(fun (lp, args, rp) ->
transform_argish env lp args rp);
]
in
(* The actual transform for function call expressions (the default transform
just calls into [handle_possible_chaining]). *)
let transform_first_receiver node =
match Syntax.syntax node with
| Syntax.FunctionCallExpression
{
function_call_receiver = receiver;
function_call_type_args = targs;
function_call_left_paren = lp;
function_call_argument_list = args;
function_call_right_paren = rp;
} ->
Concat [t env receiver; t env targs; transform_argish env lp args rp]
| Syntax.MemberSelectionExpression _
| Syntax.SafeMemberSelectionExpression _ ->
failwith
"Should not be possible for a member selection expression to be considered first_receiver"
| _ -> t env node
in
let first_receiver_has_trailing_newline =
node_has_trailing_newline first_receiver
in
match chain_list with
| [] -> transform_first_receiver first_receiver
| [hd] ->
Concat
[
Span [transform_first_receiver first_receiver];
(if first_receiver_has_trailing_newline then
Newline
else
SplitWith Cost.High);
Nest [transform_chain hd];
]
| hd :: tl ->
let transformed_hd = transform_chain hd in
let tl = List.map tl ~f:transform_chain in
let rule_type =
match hd with
| (_, trailing, None, None)
| (_, _, Some trailing, None)
| (_, _, _, Some (_, _, trailing)) ->
if node_has_trailing_newline trailing then
Rule.Always
else if first_receiver_has_trailing_newline then
Rule.Parental
else
(* If we have a chain where only the final item contains internal
splits, use a Simple rule instead of a Parental one.
This allows us to preserve this style:
return $this->fooGenerator->generateFoo(
$argument_one,
$argument_two,
$argument_three,
);
*)
let rev_tl_except_last = List.rev tl |> List.tl_exn in
let items_except_last = transformed_hd :: rev_tl_except_last in
if List.exists items_except_last ~f:has_split then
Rule.Parental
else
Rule.Simple Cost.NoCost
in
Span
[
WithLazyRule
( rule_type,
Concat
[
transform_first_receiver first_receiver;
(if first_receiver_has_trailing_newline then
Newline
else
SplitWith Cost.Base);
],
Concat
[
(* This needs to be nested separately due to the above SplitWith *)
Nest [transformed_hd];
Nest (List.map tl ~f:(fun x -> Concat [Split; x]));
] );
]
and transform_fn_decl_name env modifiers kw name type_params leftp =
let mods = handle_possible_list env ~after_each:(fun _ -> Space) modifiers in
[mods; t env kw; Space; t env name; t env type_params; t env leftp; Split]
and transform_fn_decl_args env params rightp =
(* It is a syntax error to follow a variadic parameter with a trailing
* comma, so suppress trailing commas in that case. *)
let allow_trailing =
match Syntax.syntax params with
| Syntax.SyntaxList params ->
let last_param =
match Syntax.syntax (List.last_exn params) with
| Syntax.ListItem { list_item; _ } -> list_item
| _ -> failwith "Expected ListItem"
in
begin
match Syntax.syntax last_param with
| Syntax.VariadicParameter _
| Syntax.(
ParameterDeclaration
{
parameter_name =
{
syntax =
DecoratedExpression
{
decorated_expression_decorator =
{
syntax =
Token { Token.kind = TokenKind.DotDotDot; _ };
_;
};
_;
};
_;
};
_;
}) ->
false
| _ -> true
end
| _ -> true
in
WithRule
( Rule.Parental,
Concat [transform_possible_comma_list env ~allow_trailing params rightp]
)
and transform_argish_with_return_type
env left_p params right_p ctx_list colon readonly_ret ret_type =
Concat
[
t env left_p;
when_present params split;
transform_fn_decl_args env params right_p;
t env ctx_list;
t env colon;
when_present colon space;
t env readonly_ret;
when_present readonly_ret space;
t env ret_type;
]
and transform_argish
env
?(allow_trailing = true)
?(force_newlines = false)
?(spaces = false)
left_p
arg_list
right_p =
(* It is a syntax error to follow a splat argument with a trailing comma, so
suppress trailing commas in that case. *)
let allow_trailing =
match Syntax.syntax arg_list with
| Syntax.SyntaxList args ->
let last_arg =
match Syntax.syntax (List.last_exn args) with
| Syntax.ListItem { list_item; _ } -> list_item
| _ -> failwith "Expected ListItem"
in
begin
match Syntax.syntax last_arg with
| Syntax.(
DecoratedExpression
{
decorated_expression_decorator =
{ syntax = Token { Token.kind = TokenKind.DotDotDot; _ }; _ };
_;
}) ->
false
| _ -> allow_trailing
end
| _ -> allow_trailing
in
(* When the last argument breaks across multiple lines, we want to allow the
arg list rule to stay unbroken even though the last argument contains
splits that may be broken on.
For example:
// We do not want to break f's rule even though its child splits:
f(vec[
$foo, // single-line comment forces the vec's rule to split
$bar,
]);
// We do not want to break map's rule even though the lambda has splits:
map($vec, $element ==> {
// ...
});
*)
let split_when_children_split =
if spaces then
true
else
let unwrap_list_item x =
match Syntax.syntax x with
| Syntax.ListItem { list_item; _ } -> list_item
| _ -> x
in
let is_doc_string_literal x =
let x = unwrap_list_item x in
match Syntax.syntax x with
| Syntax.LiteralExpression { literal_expression } ->
(match Syntax.syntax literal_expression with
| Syntax.Token t ->
(match Token.kind t with
| TokenKind.(HeredocStringLiteral | NowdocStringLiteral) -> true
| _ -> false)
| Syntax.SyntaxList (x :: _) ->
(match Syntax.syntax x with
| Syntax.Token t ->
(match Token.kind t with
| TokenKind.HeredocStringLiteralHead -> true
| _ -> false)
| _ -> false)
| _ -> false)
| _ -> false
in
let leading_trivia_is_all_whitespace x =
List.for_all (Syntax.leading_trivia x) ~f:(fun t ->
match Trivia.kind t with
| TriviaKind.WhiteSpace -> true
| _ -> false)
in
match Syntax.syntax arg_list with
| Syntax.SyntaxList [] -> true
| Syntax.SyntaxList [x] ->
let has_surrounding_whitespace =
not
(List.is_empty (Syntax.trailing_trivia left_p)
&& (List.is_empty (Syntax.trailing_trivia arg_list)
|| Env.version_gte env 3
&& is_doc_string_literal x
&& leading_trivia_is_all_whitespace right_p))
in
if has_surrounding_whitespace then
true
else
looks_bad_in_non_parental_braces x
| Syntax.SyntaxList items ->
let last = List.last_exn items in
let has_surrounding_whitespace =
not
(List.is_empty (Syntax.leading_trivia last)
&& (List.is_empty (Syntax.trailing_trivia arg_list)
|| Env.version_gte env 3
&& is_doc_string_literal last
&& leading_trivia_is_all_whitespace right_p))
in
if has_surrounding_whitespace then
true
else (
(* When there are multiple arguments, opt into this behavior only when we
have no splits in any of the arguments except the last. *)
match List.rev items with
| [] -> assert false
| last :: rest ->
let prev_args_may_split =
rest |> List.map ~f:(t env) |> List.exists ~f:has_split
in
if prev_args_may_split then
true
else
looks_bad_in_non_parental_braces last
)
| _ -> true
in
delimited_nest
env
~split_when_children_split
~force_newlines
left_p
right_p
[transform_arg_list env ~allow_trailing arg_list]
(** Sometimes, we want to use a non-Parental rule for function call argument
lists and other similar constructs when not breaking around the argument
list looks reasonable. For example:
f($x ==> {
return do_something_with($x);
});
Some constructs don't look so great when we do this:
f($x ==>
do_something_with($x));
f($x
? $y
: $z);
This function blacklists those constructs. *)
and looks_bad_in_non_parental_braces item =
let item =
match Syntax.syntax item with
| Syntax.ListItem { list_item; _ } -> list_item
| _ -> item
in
match Syntax.syntax item with
| Syntax.(
LambdaExpression { lambda_body = { syntax = CompoundStatement _; _ }; _ })
->
false
| Syntax.FunctionCallExpression { function_call_receiver; _ } ->
Syntax.is_member_selection_expression function_call_receiver
| Syntax.ConditionalExpression _
| Syntax.BinaryExpression _
| Syntax.MemberSelectionExpression _
| Syntax.FieldSpecifier _
| Syntax.FieldInitializer _
| Syntax.ElementInitializer _
| Syntax.LambdaExpression _
| Syntax.XHPExpression _
| Syntax.IsExpression _
| Syntax.AsExpression _
| Syntax.NullableAsExpression _ ->
true
| _ -> false
and transform_braced_item env left_p item right_p =
let has_no_surrounding_trivia =
List.is_empty (Syntax.trailing_trivia left_p)
&& List.is_empty (Syntax.leading_trivia item)
&& List.is_empty (Syntax.trailing_trivia item)
&& List.is_empty (Syntax.leading_trivia right_p)
in
if has_no_surrounding_trivia && not (looks_bad_in_non_parental_braces item)
then
Concat (List.map [left_p; item; right_p] ~f:(t env))
else
delimited_nest env left_p right_p [t env item]
and transform_argish_item env x =
match Syntax.syntax x with
| Syntax.ListItem { list_item; list_separator } ->
Concat [transform_argish_item env list_item; t env list_separator]
| Syntax.BinaryExpression
{
binary_left_operand = left;
binary_operator = op;
binary_right_operand = right;
}
when not (is_concat op) ->
transform_binary_expression env ~is_nested:true (left, op, right)
| _ -> t env x
and transform_trailing_comma env ~allow_trailing item comma =
(* PHP does not permit trailing commas in function calls. Rather than try to
* account for where PHP's parser permits trailing commas, we just never add
* them in PHP files. *)
let allow_trailing = allow_trailing && env.Env.add_trailing_commas in
match Syntax.syntax comma with
| Syntax.Token tok ->
Concat
[
transform_argish_item env item;
transform_leading_trivia (Token.leading tok);
(if allow_trailing then
TrailingComma true
else
Nothing);
Ignore (Token.text tok, Token.width tok);
transform_trailing_trivia (Token.trailing tok);
]
| Syntax.Missing ->
let (item, item_trailing) = remove_trailing_trivia item in
Concat
[
transform_argish_item env item;
(if allow_trailing then
TrailingComma false
else
Nothing);
transform_trailing_trivia item_trailing;
]
| _ -> failwith "Expected Token"
and transform_braced_item_with_trailer env left_p item comma right_p =
let has_no_surrounding_trivia =
List.is_empty (Syntax.trailing_trivia left_p)
&& List.is_empty (Syntax.leading_trivia item)
&& List.is_empty (Syntax.trailing_trivia item)
&& List.is_empty (Syntax.leading_trivia comma)
&& List.is_empty (Syntax.trailing_trivia comma)
&& List.is_empty (Syntax.leading_trivia right_p)
in
(* TODO: turn allow_trailing:true when HHVM versions that don't support
trailing commas in all these places reach end-of-life. *)
let item_and_comma =
transform_trailing_comma env ~allow_trailing:false item comma
in
if has_no_surrounding_trivia && not (looks_bad_in_non_parental_braces item)
then
Concat [t env left_p; item_and_comma; t env right_p]
else
delimited_nest env left_p right_p [item_and_comma]
and transform_arg_list env ?(allow_trailing = true) items =
handle_possible_list
env
items
~after_each:after_each_argument
~handle_last:(transform_last_arg env ~allow_trailing)
~handle_element:(transform_argish_item env)
and transform_possible_comma_list env ?(allow_trailing = true) items right_p =
nest env right_p [transform_arg_list env ~allow_trailing items]
and transform_container_literal
env
?(space = false)
?allow_trailing
?explicit_type
kw
left_p
members
right_p =
let force_newlines = node_has_trailing_newline left_p in
let ty =
match explicit_type with
| Some ex_ty -> t env ex_ty
| None -> Nothing
in
Concat
[
t env kw;
ty;
(if space then
Space
else
Nothing);
transform_argish
env
~force_newlines
?allow_trailing
left_p
members
right_p;
]
and replace_leading_trivia node new_leading_trivia =
match Syntax.leading_token node with
| None -> node
| Some leading_token ->
let rewritten_node =
Rewriter.rewrite_pre
(fun node_to_rewrite ->
match Syntax.syntax node_to_rewrite with
| Syntax.Token t when phys_equal t leading_token ->
Rewriter.Replace
(Syntax.make_token { t with Token.leading = new_leading_trivia })
| _ -> Rewriter.Keep)
node
in
rewritten_node
and remove_leading_trivia node =
match Syntax.leading_token node with
| None -> ([], node)
| Some leading_token ->
let rewritten_node =
Rewriter.rewrite_pre
(fun rewrite_node ->
match Syntax.syntax rewrite_node with
| Syntax.Token t when phys_equal t leading_token ->
Rewriter.Replace (Syntax.make_token { t with Token.leading = [] })
| _ -> Rewriter.Keep)
node
in
(Token.leading leading_token, rewritten_node)
and remove_trailing_trivia node =
match Syntax.trailing_token node with
| None -> (node, [])
| Some trailing_token ->
let rewritten_node =
Rewriter.rewrite_pre
(fun rewrite_node ->
match Syntax.syntax rewrite_node with
| Syntax.Token t when phys_equal t trailing_token ->
Rewriter.Replace (Syntax.make_token { t with Token.trailing = [] })
| _ -> Rewriter.Keep)
node
in
(rewritten_node, Token.trailing trailing_token)
and transform_last_arg env ~allow_trailing node =
match Syntax.syntax node with
| Syntax.ListItem { list_item = item; list_separator = separator } ->
transform_trailing_comma env ~allow_trailing item separator
| _ -> failwith "Expected ListItem"
and transform_mapish_entry env key arrow value =
Concat
[
t env key;
Space;
t env arrow;
Space;
SplitWith Cost.Base;
Nest [t env value];
]
and transform_keyword_expression_statement env kw expr semi =
Concat
[
t env kw;
when_present expr (fun () ->
Concat
[
Space;
SplitWith
(if Env.version_gte env 1 then
Cost.Base
else
Cost.Moderate);
Nest [t env expr];
]);
t env semi;
Newline;
]
and transform_keyword_expr_list_statement env kw expr_list semi =
Concat [t env kw; handle_declarator_list env expr_list; t env semi; Newline]
and transform_condition env left_p condition right_p =
Concat
[
t env left_p;
Split;
WithRule
(Rule.Parental, Concat [Nest [t env condition]; Split; t env right_p]);
]
and get_operator_type op =
match Syntax.syntax op with
| Syntax.Token t -> Full_fidelity_operator.trailing_from_token (Token.kind t)
| _ -> failwith "Operator should always be a token"
and is_concat op =
match get_operator_type op with
| Full_fidelity_operator.ConcatenationOperator -> true
| _ -> false
and transform_binary_expression env ~is_nested (left, operator, right) =
let operator_has_surrounding_spaces op = not (is_concat op) in
let operator_is_leading op =
match get_operator_type op with
| Full_fidelity_operator.PipeOperator -> true
| _ -> false
in
let operator_preserves_newlines op =
match get_operator_type op with
| Full_fidelity_operator.PipeOperator -> true
| _ -> false
in
let operator_t = get_operator_type operator in
if Full_fidelity_operator.is_comparison operator_t then
WithLazyRule
( Rule.Parental,
Concat [t env left; Space; t env operator],
Concat [Space; Split; Nest [t env right]] )
else if Full_fidelity_operator.is_assignment operator_t then
Concat
[
t env left;
Space;
t env operator;
Space;
SplitWith
(if Env.version_gte env 1 then
Cost.Base
else
Cost.Moderate);
Nest [t env right];
]
else
Concat
[
(let penv = Full_fidelity_parser_env.default in
let precedence = Full_fidelity_operator.precedence penv operator_t in
let rec flatten_expression expr =
match Syntax.syntax expr with
| Syntax.BinaryExpression
{
binary_left_operand = left;
binary_operator = operator;
binary_right_operand = right;
} ->
let operator_t = get_operator_type operator in
let op_precedence =
Full_fidelity_operator.precedence penv operator_t
in
if op_precedence = precedence then
flatten_expression left @ (operator :: flatten_expression right)
else
[expr]
| _ -> [expr]
in
let transform_operand operand =
match Syntax.syntax operand with
| Syntax.BinaryExpression
{ binary_left_operand; binary_operator; binary_right_operand } ->
transform_binary_expression
env
~is_nested:true
(binary_left_operand, binary_operator, binary_right_operand)
| _ -> t env operand
in
let binary_expression_syntax_list =
flatten_expression
(Syntax.make_binary_expression left operator right)
in
match binary_expression_syntax_list with
| hd :: tl ->
WithLazyRule
( Rule.Parental,
transform_operand hd,
let expression =
let last_operand = ref hd in
let last_op = ref (List.hd_exn tl) in
List.mapi tl ~f:(fun i x ->
if i mod 2 = 0 then (
let op = x in
last_op := op;
let op_has_spaces = operator_has_surrounding_spaces op in
let op_is_leading = operator_is_leading op in
let newline_before_op =
operator_preserves_newlines op
&& node_has_trailing_newline !last_operand
in
Concat
[
(if newline_before_op then
Newline
else if op_is_leading then
if op_has_spaces then
space_split ()
else
Split
else if op_has_spaces then
Space
else
Nothing);
(if is_concat op then
ConcatOperator (t env op)
else
t env op);
]
) else
let operand = x in
last_operand := x;
let op_has_spaces =
operator_has_surrounding_spaces !last_op
in
let op_is_leading = operator_is_leading !last_op in
Concat
[
(if op_is_leading then
if op_has_spaces then
Space
else
Nothing
else if op_has_spaces then
space_split ()
else
Split);
transform_operand operand;
])
in
if is_nested then
Nest expression
else
ConditionalNest expression )
| _ -> failwith "Expected non empty list of binary expression pieces");
]
and make_string text width =
let split_text = Str.split_delim (Str.regexp "\n") text in
match split_text with
| [_] -> Text (text, width)
| _ -> MultilineString (split_text, width)
(* Check the leading trivia of the node's leading token.
Treat the node's text as a multiline string if the leading trivia contains
an ignore comment. *)
and transform_node_if_ignored node =
let (leading_before, leading_including_and_after) =
leading_ignore_comment (Syntax.leading_trivia node)
in
if List.length leading_including_and_after = 0 then
None
else
let node = replace_leading_trivia node leading_including_and_after in
let (node, trailing_trivia) = remove_trailing_trivia node in
let is_fixme =
match Trivia.kind (List.hd_exn leading_including_and_after) with
| TriviaKind.(FixMe | IgnoreError) -> true
| _ -> false
in
Some
(Concat
[
transform_leading_trivia leading_before;
(* If we have a non-error-suppression comment here, then we want to
ensure that we don't join it up onto the preceding line. Since we
only scan leading trivia for hackfmt-ignore comments, and joining
the comment onto the preceding line would make it trailing trivia,
we would make the ignore comment useless if we joined it with the
preceding line (breaking idempotence of hackfmt). Adding [Newline]
here ensures a line break.
Error-suppression comments are different--they are specially
handled by the lexer to ensure that they always appear in leading
trivia. *)
(if is_fixme then
Nothing
else
Newline);
make_string (Syntax.text node) (Syntax.width node);
transform_trailing_trivia trailing_trivia;
(if has_newline trailing_trivia then
Newline
else
Nothing);
])
and ignore_re = Str.regexp_string "hackfmt-ignore"
and is_ignore_comment trivia =
match Trivia.kind trivia with
(* We don't format the node after a comment containing "hackfmt-ignore". *)
| TriviaKind.(DelimitedComment | SingleLineComment) -> begin
try Str.search_forward ignore_re (Trivia.text trivia) 0 >= 0 with
| Caml.Not_found -> false
end
| _ -> false
and leading_ignore_comment trivia_list =
let before = List.take_while trivia_list ~f:(Fn.non is_ignore_comment) in
let (_, including_and_after) =
List.split_n trivia_list (List.length before)
in
(before, including_and_after)
(* True if the trivia list contains WhiteSpace trivia.
* Note that WhiteSpace includes spaces and tabs, but not newlines. *)
and has_whitespace trivia_list =
List.exists trivia_list ~f:(fun trivia ->
is_trivia_kind_white_space (Trivia.kind trivia))
(* True if the trivia list contains EndOfLine trivia. *)
and has_newline trivia_list =
List.exists trivia_list ~f:(fun trivia ->
is_trivia_kind_end_of_line (Trivia.kind trivia))
and is_invisible trivia =
match Trivia.kind trivia with
| TriviaKind.WhiteSpace
| TriviaKind.EndOfLine ->
true
| _ -> false
and transform_leading_trivia t = transform_trivia ~is_leading:true t
and transform_trailing_trivia t = transform_trivia ~is_leading:false t
and transform_trivia ~is_leading trivia =
let new_line_regex = Str.regexp "\n" in
let indent = ref 0 in
let currently_leading = ref is_leading in
let leading_invisibles = ref [] in
let last_comment = ref None in
let last_comment_was_delimited = ref false in
let newline_followed_last_comment = ref false in
let whitespace_followed_last_comment = ref false in
let trailing_invisibles = ref [] in
let comments = ref [] in
let make_comment _ =
if Option.is_some !last_comment then (
newline_followed_last_comment := has_newline !trailing_invisibles;
whitespace_followed_last_comment := has_whitespace !trailing_invisibles
);
comments :=
Concat
[
transform_leading_invisibles (List.rev !leading_invisibles);
Option.value !last_comment ~default:Nothing;
ignore_trailing_invisibles (List.rev !trailing_invisibles);
(if !last_comment_was_delimited && !whitespace_followed_last_comment
then
Space
else if !newline_followed_last_comment then
Newline
else
Nothing);
]
:: !comments;
last_comment := None;
leading_invisibles := [];
trailing_invisibles := []
in
List.iter trivia ~f:(fun triv ->
match Trivia.kind triv with
| TriviaKind.ExtraTokenError
| TriviaKind.FixMe
| TriviaKind.IgnoreError
| TriviaKind.DelimitedComment ->
let preceded_by_whitespace =
if !currently_leading then
has_whitespace !leading_invisibles
else
has_whitespace !trailing_invisibles
in
make_comment ();
let delimited_lines = Str.split new_line_regex (Trivia.text triv) in
let map_tail str =
let prefix_space_count str =
let len = String.length str in
let rec aux i =
if i = len || Char.(str.[i] <> ' ' && str.[i] <> '\t') then
0
else
1 + aux (i + 1)
in
aux 0
in
(* If we're dealing with trailing trivia, then we don't have a good
signal for the indent level, so we just cut all leading spaces.
Otherwise, we cut a number of spaces equal to the indent before
the delimited comment opener. *)
let start_index =
if is_leading then
min !indent (prefix_space_count str)
else
prefix_space_count str
in
let len = String.length str - start_index in
let dc =
Trivia.create_delimited_comment
@@ String.sub str ~pos:start_index ~len
in
Concat
[
Ignore ("\n", 1);
Newline;
Ignore (String.make start_index ' ', start_index);
Comment (Trivia.text dc, Trivia.width dc);
]
in
let hd = List.hd_exn delimited_lines in
let tl = List.tl_exn delimited_lines in
let hd = Comment (hd, String.length hd) in
let should_break =
match Trivia.kind triv with
| TriviaKind.FixMe
| TriviaKind.IgnoreError ->
false
| _ -> !currently_leading
in
last_comment :=
Some
(Concat
[
(if should_break then
Newline
else if preceded_by_whitespace then
Space
else
Nothing);
Concat (hd :: List.map tl ~f:map_tail);
]);
last_comment_was_delimited := true;
currently_leading := false
| TriviaKind.FallThrough
| TriviaKind.SingleLineComment ->
make_comment ();
last_comment :=
Some
(Concat
[
(if !currently_leading then
Newline
else
Space);
SingleLineComment (Trivia.text triv, Trivia.width triv);
]);
last_comment_was_delimited := false;
currently_leading := false
| TriviaKind.EndOfLine ->
indent := 0;
if !currently_leading then
leading_invisibles := triv :: !leading_invisibles
else (
trailing_invisibles := triv :: !trailing_invisibles;
make_comment ()
);
currently_leading := true
| TriviaKind.WhiteSpace ->
if !currently_leading then (
indent := Trivia.width triv;
leading_invisibles := triv :: !leading_invisibles
) else
trailing_invisibles := triv :: !trailing_invisibles);
if List.is_empty !comments then
if is_leading then
transform_leading_invisibles trivia
else
ignore_trailing_invisibles trivia
else (
make_comment ();
Concat (List.rev !comments)
)
and max_consecutive_blank_lines = 1
and transform_leading_invisibles triv =
let newlines = ref 0 in
Concat
(List.map triv ~f:(fun t ->
let ignored = Ignore (Trivia.text t, Trivia.width t) in
match Trivia.kind t with
| TriviaKind.EndOfLine ->
newlines := !newlines + 1;
Concat
[
ignored;
(if !newlines <= max_consecutive_blank_lines then
BlankLine
else
Nothing);
]
| _ -> ignored))
and ignore_trailing_invisibles triv =
Concat (List.map triv ~f:(fun t -> Ignore (Trivia.text t, Trivia.width t)))
and transform_xhp_leading_trivia triv =
let (up_to_first_newline, after_newline, _) =
List.fold triv ~init:([], [], false) ~f:(fun (upto, after, seen) t ->
if seen then
(upto, t :: after, true)
else
(t :: upto, after, is_trivia_kind_end_of_line (Trivia.kind t)))
in
Concat
[
ignore_trailing_invisibles up_to_first_newline;
transform_leading_invisibles after_newline;
]
and node_has_trailing_newline node =
let trivia = Syntax.trailing_trivia node in
List.exists trivia ~f:(fun x -> is_trivia_kind_end_of_line (Trivia.kind x))
and transform_consequence
t (env : Env.t) (node_body : Syntax.t) (node_newline : Syntax.t) =
match Syntax.syntax node_body with
| Syntax.CompoundStatement _ ->
handle_possible_compound_statement env node_body
| _ ->
Concat
[
Space;
(if has_newline (Syntax.trailing_trivia node_newline) then
Concat [Newline; Nest [t env node_body]]
else
WithRule (Rule.Parental, Nest [Span [Space; Split; t env node_body]]));
]
let transform (env : Env.t) (node : Syntax.t) : Doc.t = t env node |
OCaml Interface | hhvm/hphp/hack/src/hackfmt/hack_format.mli | (*
* Copyright (c) 2018, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
val transform : Format_env.t -> Full_fidelity_editable_syntax.t -> Doc.t |
OCaml | hhvm/hphp/hack/src/hackfmt/interval.ml | (*
* Copyright (c) 2017, 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.
*
*)
(** Helpers for half-open intervals *)
open Hh_prelude
type t = int * int
let pp fmt (st, ed) = Format.fprintf fmt "[%d, %d)" st ed
let show = Format.asprintf "%a" pp
let contains ((st, ed) : t) (point : int) : bool = st <= point && point < ed
let contains_interval (a : t) (b : t) : bool =
let (a_start, a_end) = a in
let (b_start, b_end) = b in
a_start <= b_start && a_end >= b_end
let intervals_overlap (a : t) (b : t) : bool =
let (a_start, a_end) = a in
let (b_start, b_end) = b in
a_start = b_start
|| (a_start < b_start && b_start < a_end)
|| (b_start < a_start && a_start < b_end)
(* Does not union adjacent intervals *)
let union (a : t) (b : t) : t option =
if intervals_overlap a b then
Some (min (fst a) (fst b), max (snd a) (snd b))
else
None
(* Does not union adjacent intervals *)
let union_consecutive_overlapping (intervals : t list) : t list =
match intervals with
| [] -> []
| hd :: tl ->
let (last, rev_unioned_except_last) =
List.fold tl ~init:(hd, []) ~f:(fun (unioned_ival, rest) next_ival ->
match union unioned_ival next_ival with
| None -> (next_ival, unioned_ival :: rest)
| Some unioned_ival -> (unioned_ival, rest))
in
List.rev (last :: rev_unioned_except_last)
let compare (a : t) (b : t) : int =
let (a_start, a_end) = a in
let (b_start, b_end) = b in
if a_start = b_start then
a_end - b_end
else
a_start - b_start
let difference (a : t) (b : t) : t list =
let (a_start, a_end) = a in
let (b_start, b_end) = b in
if not (intervals_overlap a b) then
[a]
else if contains_interval b a then
[]
else if contains b a_start then
[(b_end, a_end)]
else if contains b a_end then
[(a_start, b_start)]
else if contains_interval a b then
[(a_start, b_start); (b_end, a_end)]
else
failwith
(Format.asprintf
"Interval.difference: invalid intervals: %a %a"
pp
a
pp
b)
(** Subtract [subtrahends] from [minuends].
Assumes both lists are sorted and non-overlapping (i.e., [List.sort
~compare:Interval.compare] and [union_consecutive_overlapping] would be
no-ops for both) *)
let diff_sorted_lists (minuends : t list) (subtrahends : t list) : t list =
let rec aux acc minuends subtrahends =
match (minuends, subtrahends) with
(* Base case: nothing to diminish *)
| ([], _) -> acc
(* Base case: nothing to subtract *)
| (minuends, []) -> List.rev_append minuends acc
(* The next subtrahend overlaps with the next minuend. Take the difference
and put any results back into minuends. Continue to the next minuend with
the same subtrahend. *)
| (minuend :: minuends_tl, subtrahend :: _)
when intervals_overlap minuend subtrahend ->
let diff = difference minuend subtrahend in
aux acc (diff @ minuends_tl) subtrahends
(* The next minuend ends before the remaining subtrahends start. Append it
to the result. Continue to the next minuend with the same subtrahend. *)
| (minuend :: minuends_tl, subtrahend :: _)
when snd minuend <= fst subtrahend ->
aux (minuend :: acc) minuends_tl subtrahends
(* The next subtrahend ends before the remaining minuends start.
Continue to the next subtrahend with the same minuend. *)
| (minuend :: _, subtrahend :: subtrahends_tl)
when snd subtrahend <= fst minuend ->
aux acc minuends subtrahends_tl
| _ -> failwith "Invalid interval lists"
in
(* Avoid double-reverse of minuends when given nothing to subtract. *)
if List.is_empty subtrahends then
minuends
else
List.rev (aux [] minuends subtrahends) |
OCaml | hhvm/hphp/hack/src/hackfmt/libhackfmt.ml | (*
* Copyright (c) 2017, 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 Env = Format_env
open Hh_prelude
open Noformat
open Boundaries
let env_from_config config =
let env = Option.value config ~default:Env.default in
if env.Env.indent_width < 0 then invalid_arg "Invalid indent width";
if env.Env.line_width < 0 then invalid_arg "Invalid line width";
env
let text_with_formatted_ranges
?(range : Interval.t option)
(text : string)
(formatted_ranges : (Interval.t * string) list) : Buffer.t =
let (start_offset, end_offset) =
match range with
| Some (start_offset, end_offset) -> (start_offset, end_offset)
| None -> (0, String.length text)
in
let buf = Buffer.create (end_offset - start_offset + 256) in
let bytes_seen = ref start_offset in
List.iter formatted_ranges ~f:(fun ((st, ed), formatted) ->
for i = !bytes_seen to st - 1 do
Buffer.add_char buf text.[i]
done;
Buffer.add_string buf formatted;
bytes_seen := ed);
for i = !bytes_seen to end_offset - 1 do
Buffer.add_char buf text.[i]
done;
buf
let format_tree ?config tree =
let source_text = SyntaxTree.text tree in
let text = SourceText.text source_text in
let env = env_from_config config in
let chunk_groups =
tree
|> SyntaxTransforms.editable_from_positioned
|> Hack_format.transform env
|> Chunk_builder.build env
in
let line_boundaries = get_line_boundaries text in
let noformat_ranges =
get_suppressed_formatting_ranges env line_boundaries tree
in
let whole_file = [(0, String.length text)] in
let ranges = Interval.diff_sorted_lists whole_file noformat_ranges in
let formatted_ranges =
List.map ranges ~f:(fun range ->
(range, Line_splitter.solve env ~range ~source_text:text chunk_groups))
in
let buf = text_with_formatted_ranges text formatted_ranges in
Buffer.contents buf
let format_range ?config range tree =
let source_text = SyntaxTree.text tree in
let text = SourceText.text source_text in
let env = env_from_config config in
let chunk_groups =
tree
|> SyntaxTransforms.editable_from_positioned
|> Hack_format.transform env
|> Chunk_builder.build env
in
let line_boundaries = get_line_boundaries text in
let noformat_ranges =
get_suppressed_formatting_ranges env line_boundaries tree
in
let ranges = Interval.diff_sorted_lists [range] noformat_ranges in
let formatted_ranges =
List.map ranges ~f:(fun range ->
(range, Line_splitter.solve env ~range ~source_text:text chunk_groups))
in
let buf = text_with_formatted_ranges ~range text formatted_ranges in
Buffer.contents buf
let format_intervals ?config intervals tree =
let source_text = SyntaxTree.text tree in
let text = SourceText.text source_text in
let env = env_from_config config in
let chunk_groups =
tree
|> SyntaxTransforms.editable_from_positioned
|> Hack_format.transform env
|> Chunk_builder.build env
in
let line_boundaries = get_line_boundaries text in
let atom_boundaries = get_atom_boundaries chunk_groups in
let ranges =
intervals
|> List.map ~f:(line_interval_to_offset_range line_boundaries)
(* If we get a range which starts or ends exactly at an atom boundary,
expand it to the NEXT atom boundary so that we get the whitespace
surrounding the formatted range. We want the whitespace surrounding the
tokens in the range, but we want to leave alone all other whitespace
outside of the range. *)
|> List.map ~f:(fun (st, ed) -> (st - 1, ed + 1))
|> List.map ~f:(expand_to_atom_boundaries atom_boundaries)
|> List.sort ~compare:Interval.compare
|> Interval.union_consecutive_overlapping
in
let noformat_ranges =
get_suppressed_formatting_ranges env line_boundaries tree
in
let ranges = Interval.diff_sorted_lists ranges noformat_ranges in
let formatted_ranges =
List.map ranges ~f:(fun range ->
( range,
Line_splitter.solve
env
~range
~include_leading_whitespace:
(not
(List.exists atom_boundaries ~f:(fun (st, _) -> fst range = st)))
~include_trailing_whitespace:
(not
(List.exists atom_boundaries ~f:(fun (_, ed) -> snd range = ed)))
~source_text:text
chunk_groups ))
in
let buf = text_with_formatted_ranges text formatted_ranges in
(* Dirty hack: Since we don't print the whitespace surrounding formatted
ranges, we don't print the trailing newline at the end of the file if the
last line in the file was modified. Add it here manually. *)
if
Buffer.length buf > 0
&& Char.(Buffer.nth buf (Buffer.length buf - 1) <> '\n')
then
Buffer.add_char buf '\n';
Buffer.contents buf
let format_at_offset ?config (tree : SyntaxTree.t) offset =
let source_text = SyntaxTree.text tree in
let env = env_from_config config in
let chunk_groups =
tree
|> SyntaxTransforms.editable_from_positioned
|> Hack_format.transform env
|> Chunk_builder.build env
in
let module PS = Full_fidelity_positioned_syntax in
(* Grab the node which is the direct parent of the token at offset. If the
* direct parent is a CompoundStatement, skip it and get the grandparent
* (so we format entire IfStatements or MethodishDeclarations when formatting
* at the closing brace). *)
let is_sk_compound_statement = function
| Full_fidelity_syntax_kind.CompoundStatement -> true
| _ -> false
in
let is_sk_syntax_list = function
| Full_fidelity_syntax_kind.SyntaxList -> true
| _ -> false
in
let (token, node) =
match PS.parentage (SyntaxTree.root tree) offset with
| token :: parent :: grandparent :: _
when is_sk_compound_statement (PS.kind parent)
&& not (is_sk_syntax_list (PS.kind grandparent)) ->
(token, grandparent)
| token :: parent :: _ -> (token, parent)
| _ -> invalid_arg "Invalid offset"
in
(* Only format at the end of a token. *)
if offset <> PS.end_offset token then
invalid_arg "Offset must point to the last character of a token";
(* Our ranges are half-open, so the range end is the token end offset + 1. *)
let ed = offset + 1 in
(* Take a half-open range which starts at the beginning of the parent node *)
let range = (PS.start_offset node, ed) in
(* Expand the start offset to the nearest line boundary in the original
* source, since we want to add a leading newline before the node we're
* formatting if one should be there and isn't already present. *)
let range = (fst (expand_to_line_boundaries source_text range), ed) in
(* Expand the start offset to the nearest atom boundary in the original
* source, so that all whitespace preceding the formatted atoms is included in
* the range. *)
let atom_boundaries = get_atom_boundaries chunk_groups in
let range = (fst (expand_to_atom_boundaries atom_boundaries range), ed) in
(* Produce the formatted text *)
let formatted =
Line_splitter.solve
env
~range
~include_leading_whitespace:false
~include_trailing_whitespace:false
~source_text:(SourceText.text source_text)
chunk_groups
in
(range, formatted)
let format_doc (env : Env.t) (doc : Doc.t) =
doc |> Chunk_builder.build env |> Line_splitter.solve env
let format_doc_unbroken (env : Env.t) (doc : Doc.t) =
doc
|> Chunk_builder.build env
|> Line_splitter.unbroken env
|> Line_splitter.print env |
OCaml Interface | hhvm/hphp/hack/src/hackfmt/libhackfmt.mli | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(** Format an entire file. *)
val format_tree : ?config:Format_env.t -> Noformat.SyntaxTree.t -> string
val format_doc : Format_env.t -> Doc.t -> string
val format_doc_unbroken : Format_env.t -> Doc.t -> string
(** Format a node at the given offset.
*
* Finds the node which is the direct parent of the token at the given byte
* offset and formats a range containing that node which ends at the given
* offset. The range that was formatted is returned (as a pair of 0-based byte
* offsets in the original file) along with the formatted text.
*
* The provided offset must point to the last byte in a token. If not, an
* invalid_arg exception will be raised.
*
* Designed to be suitable for as-you-type-formatting. *)
val format_at_offset :
?config:Format_env.t -> Noformat.SyntaxTree.t -> int -> (int * int) * string
(** Return the source of the entire file with the given intervals formatted.
*
* The intervals are a list of half-open intervals of 1-based line numbers.
* They are permitted to overlap. *)
val format_intervals :
?config:Format_env.t -> (int * int) list -> Noformat.SyntaxTree.t -> string
(** Format a given range in a file.
*
* The range is a half-open interval of byte offsets into the file.
*
* If the range boundaries would bisect a token, the entire token will appear in
* the formatted output.
*
* If the first token in the range would have indentation preceding it in the
* full formatted file, the leading indentation will be included in the output.
*
* If the last token in the range would have a trailing newline in the full
* formatted file, the trailing newline will be included in the output.
*
* Non-indentation space characters are not included at the beginning or end of
* the formatted output (unless they are in a comment or string literal). *)
val format_range :
?config:Format_env.t -> Interval.t -> Noformat.SyntaxTree.t -> string
val env_from_config : Format_env.t option -> Format_env.t |
OCaml | hhvm/hphp/hack/src/hackfmt/line_splitter.ml | (*
* Copyright (c) 2016, 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 Env = Format_env
open Hh_prelude
open Common
let expand_state env state =
let { Solve_state.chunk_group; rbm; _ } = state in
let rule_ids = ISet.elements @@ Solve_state.get_candidate_rules state in
let (_, next_rbms) =
List.map_env rbm rule_ids ~f:(fun env_rbm rule_id ->
if Solve_state.is_rule_bound state rule_id then
(env_rbm, None)
else
let next_rbm_opt =
Some (IMap.add rule_id true env_rbm)
|> Option.filter
~f:(Chunk_group.are_rule_bindings_valid chunk_group)
in
let env_rbm =
if Option.is_some next_rbm_opt then
IMap.add rule_id false env_rbm
else
env_rbm
in
(env_rbm, next_rbm_opt))
in
next_rbms |> List.filter_opt |> List.map ~f:(Solve_state.make env chunk_group)
let find_best_state env init_state =
let queue = State_queue.make_empty 7 in
List.iter (expand_state env init_state) ~f:(State_queue.push queue);
let rec aux count best =
if count > 100 then
None
else if State_queue.is_empty queue || best.Solve_state.overflow = 0 then
Some best
else
let next_state = State_queue.pop queue in
List.iter (expand_state env next_state) ~f:(State_queue.push queue);
aux (count + 1) (Solve_state.pick_best_state next_state best)
in
aux 0 init_state
let solve_chunk_group env ?range ?source_text chunk_group =
let rbm =
match range with
| Some range
when let group_range = Chunk_group.get_char_range chunk_group in
let (st, ed) = range in
Interval.contains group_range st || Interval.contains group_range ed
->
let source_rbm =
match source_text with
| Some st -> Solve_state.rbm_from_source st chunk_group
| None -> Solve_state.rbm_broken_everywhere chunk_group
in
(* Build two lists of rule IDs: the rules associated with at least one
split outside of the formatting range, and the rules associated with at
least one split inside the formatting range. A rule may occur in both
lists if it is associated with splits both inside and outside the
formatting range. *)
let (rules_in_range, rules_out_of_range) =
(* Contract the range to work around edge cases: if a chunk starts on
the first character of the range, we don't want to consider its split
to be inside the range (otherwise we might attempt to join onto the
previous line, which is out of range and can't be modified). *)
let range = (fst range + 1, snd range) in
List.partition_map chunk_group.Chunk_group.chunks ~f:(fun chunk ->
(* Each chunk is preceded by a split, and contains the ID of the rule
governing that split. *)
let rule = chunk.Chunk.rule in
(* We consider that split to be within the range when the range
contains the first character in the chunk. *)
if Interval.contains range chunk.Chunk.start_char then
First rule
else
Second rule)
in
let iset_of_list = List.fold_right ~init:ISet.empty ~f:ISet.add in
let rules_in_range = iset_of_list rules_in_range in
let rules_out_of_range = iset_of_list rules_out_of_range in
let always_rules =
iset_of_list (Chunk_group.get_always_rules chunk_group)
in
let rules_entirely_in_range =
ISet.diff rules_in_range rules_out_of_range
in
let always_rules_in_range = ISet.inter always_rules rules_in_range in
let bindings =
source_rbm
(* If we have a rule associated with a split outside of the formatting
range which was broken in the original source, the output will look
strange if we don't break all of that rule's associated splits inside
the formatting range, too. *)
|> IMap.filter (fun id broke -> broke && ISet.mem id rules_out_of_range)
(* We should also break any rule which is configured to ALWAYS break
(such as the rule governing the split after a single-line comment)
and has a split inside the formatting range. *)
|> ISet.fold (fun id -> IMap.add id true) always_rules_in_range
in
let propagated =
bindings
(* Break any Parental rules which contain the rules we decided to break
above... *)
|> Chunk_group.propagate_breakage chunk_group
(* ...But only do this for rules which do not have any associated splits
outside of the formatting range. *)
|> IMap.filter (fun id _ -> ISet.mem id rules_entirely_in_range)
in
IMap.union bindings propagated
| _ -> Chunk_group.get_initial_rule_bindings chunk_group
in
let init_state = Solve_state.make env chunk_group rbm in
match find_best_state env init_state with
| Some state -> state
| None -> begin
match source_text with
| Some s -> Solve_state.from_source env s chunk_group
| None ->
let rbm = Solve_state.rbm_broken_everywhere chunk_group in
Solve_state.from_rbm env rbm chunk_group
end
let find_solve_states
(env : Env.t)
?(range : Interval.t option)
?(source_text : string option)
(chunk_groups : Chunk_group.t list) : Solve_state.t list =
let chunk_groups =
match range with
| None -> chunk_groups
| Some range ->
List.filter chunk_groups ~f:(fun chunk_group ->
let group_range = Chunk_group.get_char_range chunk_group in
Interval.intervals_overlap range group_range)
in
chunk_groups |> List.map ~f:(solve_chunk_group ?range env ?source_text)
let print
(env : Env.t)
?(range : Interval.t option)
?(include_leading_whitespace = true)
?(include_trailing_whitespace = true)
(solve_states : Solve_state.t list) : string =
let filter_to_range subchunks =
match range with
| None -> subchunks
| Some range ->
Subchunk.subchunks_in_range
~include_leading_whitespace
~include_trailing_whitespace
subchunks
range
in
solve_states
|> List.concat_map ~f:Subchunk.subchunks_of_solve_state
|> filter_to_range
|> Subchunk.string_of_subchunks env
let solve
(env : Env.t)
?(range : Interval.t option)
?(include_leading_whitespace : bool option)
?(include_trailing_whitespace : bool option)
?(source_text : string option)
(chunk_groups : Chunk_group.t list) : string =
chunk_groups
|> find_solve_states env ?range ?source_text
|> print env ?range ?include_leading_whitespace ?include_trailing_whitespace
let unbroken_solve_state env chunk_group =
let rbm = Chunk_group.get_initial_rule_bindings chunk_group in
Solve_state.make env chunk_group rbm
let unbroken env chunk_groups =
chunk_groups |> List.map ~f:(unbroken_solve_state env) |
OCaml | hhvm/hphp/hack/src/hackfmt/nesting.ml | (*
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
type t = {
id: int;
indent: bool;
parent: t option;
skip_parent_if_nested: bool;
}
let dummy =
{ id = -1; indent = false; parent = None; skip_parent_if_nested = false }
let make ~id ~indent parent skip_parent =
{ id; indent; parent; skip_parent_if_nested = skip_parent }
let get_indent_level nesting nesting_set =
let rec aux acc n =
match n with
| None -> acc
| Some n ->
let in_set = ISet.mem n.id nesting_set in
let acc =
if n.indent && in_set then
acc + 1
else
acc
in
aux acc
@@
if in_set && n.skip_parent_if_nested then
Option.( >>= ) n.parent (fun p -> p.parent)
else
n.parent
in
aux 0 (Some nesting)
let get_self_and_parent_list nesting =
let rec aux acc n =
Option.value_map n ~default:acc ~f:(fun n -> aux (n.id :: acc) n.parent)
in
aux [] nesting |
OCaml | hhvm/hphp/hack/src/hackfmt/nesting_allocator.ml | (*
* Copyright (c) 2016, 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.
*
*)
type t = {
next_id: int;
current_nesting: Nesting.t;
}
let make () =
{ next_id = 1; current_nesting = Nesting.make ~id:0 ~indent:false None false }
let nest t conditional =
let current_nesting =
Nesting.make ~id:t.next_id ~indent:true (Some t.current_nesting) conditional
in
{ next_id = t.next_id + 1; current_nesting }
let unnest t =
let current_nesting =
match t.current_nesting.Nesting.parent with
| Some p -> p
| None -> raise (Failure "unnested too far")
in
{ t with current_nesting }
let is_nested t =
match t.current_nesting.Nesting.parent with
| Some _ -> true
| None -> false |
OCaml | hhvm/hphp/hack/src/hackfmt/noformat.ml | (*
* Copyright (c) 2017, 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 SourceText = Full_fidelity_source_text
module Syntax = Full_fidelity_positioned_syntax
module SyntaxTree =
Full_fidelity_syntax_tree.WithSyntax (Full_fidelity_positioned_syntax)
module Token = Full_fidelity_positioned_token
module Trivia = Full_fidelity_positioned_trivia
open Hh_prelude
open Boundaries
open Format_env
let generated_tag = "@" ^ "generated"
let partially_generated_tag = "@" ^ "partially-generated"
let begin_manual_section_regexp =
Str.regexp "/\\* BEGIN MANUAL SECTION [^*]*\\*/"
let end_manual_section_tag = "/* END MANUAL SECTION */"
let lint_ignore_tag = "@" ^ "lint-ignore"
let is_generated_file text = String.is_substring text ~substring:generated_tag
let is_partially_generated_file text =
String.is_substring text ~substring:partially_generated_tag
let is_begin_manual_section_tag text =
try
let (_ : int) = Str.search_forward begin_manual_section_regexp text 0 in
true
with
| Caml.Not_found -> false
let is_end_manual_section_tag text = String.equal text end_manual_section_tag
let is_lint_ignore text = String.is_substring text ~substring:lint_ignore_tag
let add_fixme_ranges fixmes trivia =
let trivium_range trivium =
(Trivia.start_offset trivium, Trivia.end_offset trivium)
in
let add_fixme_range fixmes trivium =
match Trivia.kind trivium with
| Full_fidelity_trivia_kind.(FixMe | IgnoreError) ->
trivium_range trivium :: fixmes
| Full_fidelity_trivia_kind.(DelimitedComment | SingleLineComment)
when is_lint_ignore (Trivia.text trivium) ->
trivium_range trivium :: fixmes
| _ -> fixmes
in
List.fold trivia ~init:fixmes ~f:add_fixme_range
let add_manual_tags manual_tags trivia =
let add_manual_tag manual_tags trivium =
match Trivia.kind trivium with
| Full_fidelity_trivia_kind.DelimitedComment
when is_begin_manual_section_tag (Trivia.text trivium) ->
`Begin (Trivia.end_offset trivium) :: manual_tags
| Full_fidelity_trivia_kind.DelimitedComment
when is_end_manual_section_tag (Trivia.text trivium) ->
`End (Trivia.start_offset trivium) :: manual_tags
| _ -> manual_tags
in
List.fold trivia ~init:manual_tags ~f:add_manual_tag
(** Return the start and end offsets of every fixme comment and every manual
section (of partially-generated files), sorted by order of appearance in the
file. *)
let get_fixme_ranges_and_manual_sections tree :
Interval.t list * Interval.t list =
let rec aux acc node =
match Syntax.get_token node with
| None -> List.fold (List.rev (Syntax.children node)) ~init:acc ~f:aux
| Some t ->
let (fixmes, manual_tags) = acc in
let trailing = List.rev (Token.trailing t) in
let leading = List.rev (Token.leading t) in
let fixmes = add_fixme_ranges fixmes trailing in
let fixmes = add_fixme_ranges fixmes leading in
let manual_tags = add_manual_tags manual_tags trailing in
let manual_tags = add_manual_tags manual_tags leading in
(fixmes, manual_tags)
in
let (fixmes, manual_tags) = aux ([], []) (SyntaxTree.root tree) in
let (manual_sections, _) =
List.fold
manual_tags
~init:([], None)
~f:(fun (manual_sections, section_start) tag ->
match (section_start, tag) with
| (None, `Begin start_offset) -> (manual_sections, Some start_offset)
| (Some start_offset, `End end_offset) ->
((start_offset, end_offset) :: manual_sections, None)
(* Malformed: multiple BEGIN tags in a row. Ignore the earlier. *)
| (Some _, `Begin start_offset) -> (manual_sections, Some start_offset)
(* Malformed: an END tag with no BEGIN. Ignore it. *)
| (None, `End _) -> (manual_sections, section_start))
in
(fixmes, List.rev manual_sections)
(** Return the start and end offsets of every range in which formatting is
suppressed, sorted by order of appearance in the file. Formatting is
suppressed around HH_FIXME/HH_IGNORE_ERROR comments, in generated
sections of partially-generated files, and in generated files. *)
let get_suppressed_formatting_ranges env line_boundaries tree =
let source_text = SyntaxTree.text tree in
let (fixme_ranges, manual_sections) =
get_fixme_ranges_and_manual_sections tree
in
let expand_to_line_boundaries =
expand_to_line_boundaries ~ranges:line_boundaries source_text
in
(* Expand each range to contain the entire line the fixme is on, then add one
to the range end and expand again to include the next line, since the fixme
suppresses errors on both the line in which it appears and the line
following it. *)
let fixme_ranges =
fixme_ranges
|> List.map ~f:expand_to_line_boundaries
|> List.map ~f:(fun (st, ed) -> (st, ed + 1))
|> List.map ~f:expand_to_line_boundaries
in
if env.format_generated_code then
Interval.union_consecutive_overlapping fixme_ranges
else
let generated_sections =
let text = SourceText.text source_text in
let whole_file = [(0, String.length text)] in
if is_generated_file text then
whole_file
else if is_partially_generated_file text then
Interval.diff_sorted_lists whole_file manual_sections
|> List.map ~f:expand_to_line_boundaries
else
[]
in
List.merge fixme_ranges generated_sections ~compare:Interval.compare
|> Interval.union_consecutive_overlapping |
OCaml | hhvm/hphp/hack/src/hackfmt/rule.ml | (*
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
type kind =
| Simple of Cost.t
| Always
| Parental
[@@deriving eq]
let is_always = function
| Always -> true
| Parental
| Simple _ ->
false
type t = {
id: int;
kind: kind;
}
let null_rule_id = -1
let get_cost kind =
Cost.get_cost
@@
match kind with
| Simple cost -> cost
| Always -> Cost.NoCost
| Parental -> Cost.Base
let cares_about_children kind =
match kind with
| Simple _ -> false
| Always -> false
| Parental -> true
let compare r1 r2 = Core.Int.compare r1.id r2.id
let to_string rule =
let kind =
match rule.kind with
| Simple cost -> Printf.sprintf "Simple %d" @@ Cost.get_cost cost
| Always -> "Always"
| Parental -> "Parental"
in
string_of_int rule.id ^ " - " ^ kind |
OCaml | hhvm/hphp/hack/src/hackfmt/ruleSet.ml | (*
* Copyright (c) 2016, 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 Set.Make (Rule) |
OCaml | hhvm/hphp/hack/src/hackfmt/rule_allocator.ml | (*
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
type t = {
rule_map: Rule.t IMap.t;
dependency_map: int list IMap.t;
next_id: int;
}
let make () =
{ rule_map = IMap.empty; dependency_map = IMap.empty; next_id = 0 }
let make_rule t rule_kind =
let rule = { Rule.id = t.next_id; kind = rule_kind } in
let t =
{
t with
rule_map = IMap.add rule.Rule.id rule t.rule_map;
next_id = t.next_id + 1;
}
in
(t, rule)
(* TODO: figure out how to share this logic with chunk_group.ml *)
let get_rule_kind t id =
let r = IMap.find id t.rule_map in
r.Rule.kind
let mark_dependencies t lazy_rules active_rule_ids child_id =
let lazy_rule_list = ISet.elements lazy_rules in
let rule_ids = lazy_rule_list @ active_rule_ids in
let new_dep_map =
List.fold_left rule_ids ~init:t.dependency_map ~f:(fun dep_map id ->
let rule = IMap.find id t.rule_map in
if Rule.cares_about_children rule.Rule.kind then
let dependency_list = IMap.find_opt child_id dep_map in
IMap.add
child_id
(match dependency_list with
| Some l -> id :: l
| None -> [id])
dep_map
else
dep_map)
in
{ t with dependency_map = new_dep_map } |
OCaml | hhvm/hphp/hack/src/hackfmt/solve_state.ml | (*
* Copyright (c) 2016, 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 Env = Format_env
open Hh_prelude
type t = {
chunk_group: Chunk_group.t;
lines: (int * ISet.t) list;
(* Rule bindings map.
* Rules in this map are bound to be broken on or not broken on in this solve
* state. Rules not in the map are not yet bound. A rule that is bound to be
* broken on will have all its splits broken in the solution. *)
rbm: bool IMap.t;
nesting_set: ISet.t;
cost: int;
overflow: int;
candidate_rules: ISet.t;
(* Expensive calculation cache *)
unprocessed_overflow: int Lazy.t;
rules_on_partially_bound_lines: ISet.t Lazy.t;
}
let chunks t = t.chunk_group.Chunk_group.chunks
let rbm_has_split_before_chunk c rbm =
let rule_id = c.Chunk.rule in
IMap.find_opt rule_id rbm |> Option.value ~default:false
let rbm_has_comma_after_chunk c rbm =
Option.value_map c.Chunk.comma ~default:false ~f:(fun (rule_id, _) ->
IMap.find_opt rule_id rbm |> Option.value ~default:false)
let has_split_before_chunk t ~chunk = rbm_has_split_before_chunk chunk t.rbm
let has_comma_after_chunk t ~chunk = rbm_has_comma_after_chunk chunk t.rbm
let get_bound_ruleset rbm = ISet.of_list @@ IMap.keys rbm
let get_overflow env len = max (len - env.Env.line_width) 0
let compute_indent_level chunk_group nesting_set chunk =
let block_indentation = chunk_group.Chunk_group.block_indentation in
block_indentation + Nesting.get_indent_level chunk.Chunk.nesting nesting_set
let get_indent_level t chunk =
compute_indent_level t.chunk_group t.nesting_set chunk
let get_indent_columns env chunk_group nesting_set chunk =
env.Env.indent_width * compute_indent_level chunk_group nesting_set chunk
(**
* Create a list of lines
*
* Each element of lines a tuple of (int, ISet.t)
* Which correspond to the overflow and set of rules that correspond to
* a particular line of output for a given Solve_state
*)
let build_lines env chunk_group rbm nesting_set =
let { Chunk_group.chunks; _ } = chunk_group in
let get_text_length chunk ~has_comma =
let comma_len =
if has_comma then
1
else
0
in
comma_len + chunk.Chunk.length
in
let get_prefix_whitespace_length env chunk ~is_split =
if is_split && chunk.Chunk.indentable then
get_indent_columns env chunk_group nesting_set chunk
else if chunk.Chunk.space_if_not_split then
1
else
0
in
let rec aux remaining_chunks acc =
let (acc_len, acc_rules) = acc in
match remaining_chunks with
| [] -> [(get_overflow env acc_len, acc_rules)]
| hd :: tl ->
(* TODO: consider adding parent rules *)
let rule = hd.Chunk.rule in
let is_split = rbm_has_split_before_chunk hd rbm in
let has_comma = rbm_has_comma_after_chunk hd rbm in
let chunk_len =
get_text_length hd ~has_comma
+ get_prefix_whitespace_length env hd ~is_split
in
if is_split then
(get_overflow env acc_len, acc_rules)
:: aux tl (chunk_len, ISet.add rule ISet.empty)
else
aux tl (chunk_len + acc_len, ISet.add rule acc_rules)
in
aux chunks (0, ISet.empty)
let build_candidate_rules_and_update_rbm rbm lines rule_dependency_map =
let bound_rules = get_bound_ruleset rbm in
let rec get_candidate_and_dead_rules lines dead_rules =
match lines with
| [] -> (ISet.empty, dead_rules)
| hd :: tl ->
let (overflow, rules) = hd in
let unbound_rules = ISet.diff rules bound_rules in
if overflow = 0 || ISet.is_empty unbound_rules then
get_candidate_and_dead_rules tl @@ ISet.union dead_rules unbound_rules
else
(rules, dead_rules)
in
let (base_candidate_rules, dead_rules) =
get_candidate_and_dead_rules lines ISet.empty
in
(* Also add parent rules *)
let deps = rule_dependency_map in
let candidate_rules =
ISet.fold
(fun id acc ->
let rules = Option.value ~default:[] (IMap.find_opt id deps) in
ISet.union acc @@ ISet.of_list rules)
base_candidate_rules
base_candidate_rules
in
let dead_rules = ISet.diff dead_rules candidate_rules in
let rbm =
ISet.fold
(fun r acc ->
if not (IMap.mem r rbm) then
IMap.add r false acc
else
acc)
dead_rules
rbm
in
(candidate_rules, rbm)
let calculate_unprocessed_overflow lines bound_ruleset =
List.fold lines ~init:0 ~f:(fun acc (overflow, rules) ->
if ISet.is_empty @@ ISet.diff rules bound_ruleset then
acc
else
acc + overflow)
let calculate_rules_on_partially_bound_lines lines bound_ruleset =
let rules_per_line = List.map lines ~f:snd in
List.fold rules_per_line ~init:ISet.empty ~f:(fun acc set ->
let diff = ISet.diff set bound_ruleset in
if
ISet.cardinal diff <> 0
(* Fully bound line *)
(* Add rules for partially bound lines *)
then
ISet.union acc @@ ISet.inter set bound_ruleset
else
acc)
let make env chunk_group rbm =
let { Chunk_group.chunks; rule_dependency_map; _ } = chunk_group in
let (nesting_set, _) =
List.fold_left
chunks
~init:(ISet.empty, ISet.empty)
(* We only care about the first occurance of each nesting id *)
~f:(fun (nset, idset) c ->
let nid = Chunk.get_nesting_id c in
if ISet.mem nid idset then
(nset, idset)
else if rbm_has_split_before_chunk c rbm then
(ISet.add nid nset, ISet.add nid idset)
else
(nset, ISet.add nid idset))
in
let lines = build_lines env chunk_group rbm nesting_set in
(* calculate the overflow of the last chunk *)
let overflow = List.fold ~init:0 ~f:( + ) @@ List.map ~f:fst lines in
(* add to cost the number of spans that are split
* (implicitly giving each span a cost of 1) *)
let broken_spans =
List.fold chunks ~init:ISet.empty ~f:(fun acc c ->
if rbm_has_split_before_chunk c rbm then
c.Chunk.spans
|> List.map ~f:Span.id
|> List.fold_right ~init:acc ~f:ISet.add
else
acc)
in
let span_cost = ISet.cardinal broken_spans in
(* add to cost the cost of all rules that are split *)
let rule_cost =
IMap.fold
(fun r_id v acc ->
if v then
acc + Rule.get_cost (Chunk_group.get_rule_kind chunk_group r_id)
else
acc)
rbm
0
in
let cost = span_cost + rule_cost in
(* Precompute candidate_rules and update the rbm by binding unbound rules on
* lines with 0 overflow to false *)
let (candidate_rules, rbm) =
build_candidate_rules_and_update_rbm rbm lines rule_dependency_map
in
let bound_ruleset = get_bound_ruleset rbm in
let unprocessed_overflow =
lazy (calculate_unprocessed_overflow lines bound_ruleset)
in
let rules_on_partially_bound_lines =
lazy (calculate_rules_on_partially_bound_lines lines bound_ruleset)
in
{
chunk_group;
lines;
rbm;
cost;
overflow;
nesting_set;
candidate_rules;
unprocessed_overflow;
rules_on_partially_bound_lines;
}
let add_breaks_from_source rbm source_text chunk_group =
let (rbm, _) =
List.fold
chunk_group.Chunk_group.chunks
~init:(rbm, 0)
~f:(fun (rbm, prev_chunk_end) chunk ->
let (chunk_start, chunk_end) = Chunk.get_range chunk in
let rbm =
let rec aux i =
i < chunk_start && (Char.equal source_text.[i] '\n' || aux (i + 1))
in
if aux prev_chunk_end then
IMap.add chunk.Chunk.rule true rbm
else
rbm
in
(rbm, chunk_end))
in
rbm
let rbm_from_source source_text chunk_group =
let rbm = IMap.empty in
add_breaks_from_source rbm source_text chunk_group
(** When we are unable to find a good solution, this function produces a
"best-effort" solution based on the original source text. We break the rules
configured to always break, then break any rules which appear to be broken
in the original source text, then propagate breakage (breaking any parental
rules containing those rules we already bound to be broken on). *)
let from_source env source_text chunk_group =
let rbm = Chunk_group.get_always_rule_bindings chunk_group in
let rbm = add_breaks_from_source rbm source_text chunk_group in
let rbm = Chunk_group.propagate_breakage chunk_group rbm in
make env chunk_group rbm
(** Every rule is broken. Everything is going hog wild. *)
let rbm_broken_everywhere chunk_group =
Chunk_group.get_rules chunk_group
|> List.fold ~init:IMap.empty ~f:(fun acc k -> IMap.add k true acc)
let from_rbm env rbm chunk_group = make env chunk_group rbm
let is_rule_bound t rule_id = IMap.mem rule_id t.rbm
let get_candidate_rules t = t.candidate_rules
let get_unprocessed_overflow t = Lazy.force t.unprocessed_overflow
let get_rules_on_partially_bound_lines t =
Lazy.force t.rules_on_partially_bound_lines
(**
* The idea behind overlapping states, is that sometimes we have two states in
* the queue where all expansions of one will be strictly worse than all
* expansions of the other. In this case we want to only keep one of the states
* in order to reduce branching.
*
* The implementation here is meant to target list-like structures where
* we come up with different solutions for a particular list item.
*)
let is_overlapping s1 s2 =
get_unprocessed_overflow s1 = get_unprocessed_overflow s2
&&
let s1_rules = get_rules_on_partially_bound_lines s1 in
let s2_rules = get_rules_on_partially_bound_lines s2 in
ISet.cardinal s1_rules = ISet.cardinal s2_rules
&& ISet.for_all
(fun s1_key ->
Option.equal
Bool.equal
(IMap.find_opt s1_key s1.rbm)
(IMap.find_opt s1_key s2.rbm))
s1_rules
let compare_rule_sets s1 s2 =
let bound_rule_ids =
Caml.List.sort_uniq Int.compare @@ IMap.keys s1.rbm @ IMap.keys s2.rbm
in
let is_split rule_id state =
IMap.find_opt rule_id state.rbm |> Option.value ~default:false
in
let rec aux = function
| [] -> 0
| rule_id :: ids ->
let diff = Bool.compare (is_split rule_id s1) (is_split rule_id s2) in
if diff <> 0 then
diff
else
aux ids
in
aux bound_rule_ids
let compare s1 s2 =
if s1.cost <> s2.cost then
s1.cost - s2.cost
else if s1.overflow <> s2.overflow then
s1.overflow - s2.overflow
else
compare_rule_sets s1 s2
let pick_best_state s1 s2 =
if s1.overflow <> s2.overflow then
if s1.overflow < s2.overflow then
s1
else
s2
else if compare s1 s2 < 0 then
s1
else
s2
let compare_overlap s1 s2 =
if not (is_overlapping s1 s2) then
None
else
Some (pick_best_state s1 s2)
let __debug t =
(* TODO: make a new rule strings string *)
let rule_strings =
List.map (IMap.bindings t.rbm) ~f:(fun (k, v) ->
string_of_int k ^ ": " ^ string_of_bool v)
in
let rule_count = string_of_int (Chunk_group.get_rule_count t.chunk_group) in
let rule_str =
rule_count ^ " [" ^ String.concat ~sep:"," rule_strings ^ "]"
in
string_of_int t.overflow ^ "," ^ string_of_int t.cost ^ " " ^ rule_str |
OCaml | hhvm/hphp/hack/src/hackfmt/span.ml | (*
* Copyright (c) 2016, 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.
*
*)
type t = { id: int }
let id t = t.id |
OCaml | hhvm/hphp/hack/src/hackfmt/span_allocator.ml | (*
* Copyright (c) 2016, 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.
*
*)
type t = { next_id: int }
let make () = { next_id = 0 }
let make_span t =
let id = t.next_id in
({ next_id = t.next_id + 1 }, { Span.id }) |
OCaml | hhvm/hphp/hack/src/hackfmt/state_queue.ml | (*
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
module SolveStateKey = struct
type t = Solve_state.t
let compare = Solve_state.compare
end
include PriorityQueue.Make (SolveStateKey)
(**
* This kind of defeats the purpose of having a priority queue in the first
* place, since it degrades worst case performance back to O(n^2), but in
* practice it leads to a speed up by reducing the branching factor.
*)
let find_overlap t state =
let rec aux i =
if i = t.size then
false
else
match t.__queue.(i) with
| None -> failwith "Unexpected null index when finding overlap"
| Some e -> begin
match Solve_state.compare_overlap state e with
| Some s ->
t.__queue.(i) <- Some s;
__bubble_down t.__queue t.size t.__queue.(i) i;
__bubble_up t.__queue i;
true
| None -> aux (i + 1)
end
in
aux 0
(* Override PriorityQueue's push *)
let push t state = if not (find_overlap t state) then push t state |
OCaml | hhvm/hphp/hack/src/hackfmt/subchunk.ml | (*
* Copyright (c) 2016, 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 Env = Format_env
open Hh_prelude
(* A subchunk is one of these variants, representing a substring of the final
* string representation of a chunk in the formatted output.
*
* This representation is a convenient intermediate step because it allows us to
* trim whitespace and trailing commas at the edges of formatted ranges as
* needed.
*)
type t =
| Atom of {
text: string;
range: Interval.t;
}
| Comma
| Space
| Newline
| Indent of int
let string_of_subchunks (env : Env.t) (subchunks : t list) : string =
let buf = Buffer.create 200 in
List.iter subchunks ~f:(function
| Atom { text; _ } -> Buffer.add_string buf text
| Comma -> Buffer.add_char buf ','
| Space -> Buffer.add_char buf ' '
| Newline -> Buffer.add_char buf '\n'
| Indent indent ->
Buffer.add_string buf
@@
if env.Env.indent_with_tabs then
String.make indent '\t'
else
String.make (indent * env.Env.indent_width) ' ');
Buffer.contents buf
let subchunks_in_range
~(include_leading_whitespace : bool)
~(include_trailing_whitespace : bool)
(subchunks : t list)
(range : Interval.t) : t list =
let (range_start, range_end) = range in
(* Filter to the atoms which overlap with the range, including the leading and
* trailing non-Atom subchunks. *)
let subchunks =
List.take_while subchunks ~f:(function
| Atom { range = (st, ed); _ } ->
st < range_end || (st = range_end && ed = range_end)
| _ -> true)
in
let subchunks = List.rev subchunks in
let subchunks =
List.take_while subchunks ~f:(function
| Atom { range = (st, ed); _ } ->
ed > range_start || (st = range_start && ed = range_start)
| _ -> true)
in
(* Drop trailing spaces and indentation *)
let subchunks =
List.drop_while subchunks ~f:(function
| Space
| Indent _ ->
true
| _ -> false)
in
(* When omitting trailing whitespace, drop trailing newlines *)
let subchunks =
if include_trailing_whitespace then
subchunks
else
List.drop_while subchunks ~f:(function
| Newline -> true
| _ -> false)
in
let subchunks = List.rev subchunks in
(* Drop leading newline. Also drop leading Commas. Comma represents a
* trailing comma that was added because its associated split was broken on.
* Since we don't have source mapping information for Commas (since there may
* have been no trailing comma in the original source), we only want to print
* them when the atom preceding the trailing comma is printed. If a Comma is
* at the beginning of the range, then the atom preceding it was not
* included, and neither should the Comma. *)
let subchunks =
List.drop_while subchunks ~f:(function
| Newline
| Space
| Comma ->
true
| _ -> false)
in
(* When omitting leading whitespace, drop leading indentation *)
let subchunks =
if include_leading_whitespace then
subchunks
else
List.drop_while subchunks ~f:(function
| Indent _ -> true
| _ -> false)
in
subchunks
let subchunks_of_solve_state (state : Solve_state.t) : t list =
let subchunks = ref [] in
let add_subchunk sc = subchunks := sc :: !subchunks in
List.iter (Solve_state.chunks state) ~f:(fun chunk ->
if Solve_state.has_split_before_chunk state ~chunk then (
add_subchunk Newline;
if (not (Chunk.is_empty chunk)) && chunk.Chunk.indentable then
add_subchunk (Indent (Solve_state.get_indent_level state chunk))
) else if chunk.Chunk.space_if_not_split then
add_subchunk Space;
List.iter chunk.Chunk.atoms ~f:(fun atom ->
let { Chunk.leading_space; text; range } = atom in
if leading_space then add_subchunk Space;
add_subchunk (Atom { text; range }));
if Solve_state.has_comma_after_chunk state ~chunk then
match Chunk.get_comma_range chunk with
| Some range -> add_subchunk (Atom { text = ","; range })
| None -> add_subchunk Comma);
(* Every chunk group has a newline trailing it, but chunks are associated with
* the split preceding them. In order to ensure that we print trailing
* newlines and not leading newlines, we always add a newline here, and strip
* leading newlines below. *)
add_subchunk Newline;
let subchunks = List.rev !subchunks in
let subchunks =
List.drop_while subchunks ~f:(function
| Newline -> true
| _ -> false)
in
subchunks
let debug (subchunks : t list) : string =
let buf = Buffer.create 200 in
List.iter subchunks ~f:(function
| Atom { text; range = (st, ed) } ->
Buffer.add_string buf (Printf.sprintf "Atom %d,%d %S\n" st ed text)
| Comma -> Buffer.add_string buf "Comma\n"
| Space -> Buffer.add_string buf "Space\n"
| Newline -> Buffer.add_string buf "Newline\n"
| Indent indent ->
Buffer.add_string buf (Printf.sprintf "Indent %d\n" indent));
Buffer.contents buf |
OCaml | hhvm/hphp/hack/src/hackfmt/debug/hackfmt_debug.ml | (*
* Copyright (c) 2016, 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 SourceText = Full_fidelity_source_text
module Syntax = Full_fidelity_positioned_syntax
module SyntaxTree = Full_fidelity_syntax_tree.WithSyntax (Syntax)
open Hh_prelude
type debug_config = {
print_doc: bool;
print_nesting_graph: bool;
print_rule_dependencies: bool;
chunk_ids: int list option;
}
let debug_config =
ref
{
print_doc = false;
print_nesting_graph = false;
print_rule_dependencies = false;
chunk_ids = None;
}
let init_with_options () =
[
( "--doc",
Arg.Unit
(fun () -> debug_config := { !debug_config with print_doc = true }),
" Print out a dump of the Doc IR" );
( "--ids",
Arg.String
(fun s ->
debug_config :=
{
!debug_config with
chunk_ids =
Some
(try
List.map (Str.split (Str.regexp ",") s) ~f:int_of_string
with
| Failure _ -> raise (Failure "Invalid id list specification"));
}),
" Comma separate list of chunk ids to inspect (default is all)" );
( "--nesting",
Arg.Unit
(fun () ->
debug_config := { !debug_config with print_nesting_graph = true }),
" Print out a representation of the nesting graph below each chunk group"
);
( "--rule-deps",
Arg.Unit
(fun () ->
debug_config := { !debug_config with print_rule_dependencies = true }),
" Print out a representation of the rule dependenies below each chunk group"
);
]
let debug_nesting chunk_group =
List.iteri chunk_group.Chunk_group.chunks ~f:(fun i c ->
let nesting_list =
Nesting.get_self_and_parent_list (Some c.Chunk.nesting)
in
let list_string =
String.concat ~sep:", " @@ List.map nesting_list ~f:string_of_int
in
Printf.printf "Chunk %d - [ %s ]\n" i list_string)
let debug_rule_deps chunk_group =
Printf.printf "%s\n" (Chunk_group.dependency_map_to_string chunk_group)
let debug_chunk_groups env ~range source_text chunk_groups =
let print_chunk =
match !debug_config.chunk_ids with
| None -> (fun id c -> Some (id, c))
| Some id_list ->
fun id c ->
if List.exists id_list ~f:(fun x -> x = id) then
Some (id, c)
else
None
in
chunk_groups
|> List.filter_mapi ~f:print_chunk
|> List.filter ~f:(fun (_i, cg) ->
let group_range = Chunk_group.get_char_range cg in
Interval.intervals_overlap range group_range)
|> List.iter ~f:(fun (i, cg) ->
Printf.printf "Group Id: %d\n" i;
Printf.printf "Indentation: %d\n" cg.Chunk_group.block_indentation;
Printf.printf "Chunk count: %d\n" (List.length cg.Chunk_group.chunks);
List.iteri cg.Chunk_group.chunks ~f:(fun i c ->
Printf.printf
"%8d rule_id:%d [%d,%d)\t%s\n"
i
c.Chunk.rule
c.Chunk.start_char
c.Chunk.end_char
(Chunk.text c));
Printf.printf "Rule count %d\n" (IMap.cardinal cg.Chunk_group.rule_map);
IMap.iter
(fun k v -> Printf.printf "%8d - %s\n" k (Rule.to_string v))
cg.Chunk_group.rule_map;
if !debug_config.print_rule_dependencies then debug_rule_deps cg;
if !debug_config.print_nesting_graph then debug_nesting cg;
Printf.printf
"%s\n"
(Line_splitter.solve
env
~range
~source_text:(SourceText.text source_text)
[cg]))
let debug_full_text source_text =
Printf.printf "%s\n" (SourceText.text source_text)
let debug_text_range source_text start_char end_char =
Printf.printf "Subrange passed:\n%s\n"
@@ String.sub
(SourceText.text source_text)
~pos:start_char
~len:(end_char - start_char)
let debug env ~range source_text doc chunk_groups =
if !debug_config.print_doc then ignore (Doc.dump doc);
let range =
Option.value range ~default:(0, Full_fidelity_source_text.length source_text)
in
debug_chunk_groups env ~range source_text chunk_groups |
OCaml | hhvm/hphp/hack/src/hackfmt/error/hackfmt_error.ml | (*
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
exception InvalidSyntax
exception InvalidCliArg of string
exception InvalidDiff of string
let get_exception_exit_value = function
| InvalidSyntax -> 2
| InvalidCliArg _ -> 3
| InvalidDiff _ -> 4
| _ -> 255
let get_error_string_from_exit_value = function
| 2 -> "File failed to parse without errors"
| 3 -> "Invalid argument"
| 4 -> "Invalid diff"
| _ -> "Internal Error"
let get_error_string_from_exn exn =
get_exception_exit_value exn |> get_error_string_from_exit_value |
OCaml | hhvm/hphp/hack/src/hackrs/compare_folded_decls_file.ml | (*
* 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.
*
*)
open Hh_prelude
open Direct_decl_parser
let popt
~auto_namespace_map
~enable_xhp_class_modifier
~disable_xhp_element_mangling
~keep_user_attributes
~interpret_soft_types_as_like_types
~everything_sdt
~enable_strict_const_semantics =
let po = ParserOptions.default in
let po =
ParserOptions.with_disable_xhp_element_mangling
po
disable_xhp_element_mangling
in
let po = ParserOptions.with_keep_user_attributes po keep_user_attributes in
let po = ParserOptions.with_auto_namespace_map po auto_namespace_map in
let po =
ParserOptions.with_enable_xhp_class_modifier po enable_xhp_class_modifier
in
let po =
ParserOptions.with_interpret_soft_types_as_like_types
po
interpret_soft_types_as_like_types
in
let po = ParserOptions.with_everything_sdt po everything_sdt in
let po =
{
po with
GlobalOptions.tco_enable_strict_const_semantics =
enable_strict_const_semantics;
}
in
po
let init ~enable_strict_const_semantics popt : Provider_context.t =
let (_handle : SharedMem.handle) =
SharedMem.init ~num_workers:0 SharedMem.default_config
in
let tcopt =
{
popt with
GlobalOptions.tco_higher_kinded_types = true;
GlobalOptions.tco_enable_strict_const_semantics =
enable_strict_const_semantics;
}
in
let ctx =
Provider_context.empty_for_tool
~popt
~tcopt
~backend:Provider_backend.Shared_memory
~deps_mode:(Typing_deps_mode.InMemoryMode None)
in
(* Push local stacks here so we don't include shared memory in our timing. *)
File_provider.local_changes_push_sharedmem_stack ();
Decl_provider.local_changes_push_sharedmem_stack ();
Shallow_classes_provider.local_changes_push_sharedmem_stack ();
ctx
let direct_decl_parse ctx fn text =
let popt = Provider_context.get_popt ctx in
let opts = DeclParserOptions.from_parser_options popt in
let parsed_file = Direct_decl_parser.parse_decls opts fn text in
parsed_file.pf_decls
let print_diff ~expected_name ~actual_name ~expected_contents ~actual_contents =
Tempfile.with_real_tempdir @@ fun dir ->
let temp_dir = Path.to_string dir in
let expected = Caml.Filename.temp_file ~temp_dir "expected" ".txt" in
let actual = Caml.Filename.temp_file ~temp_dir "actual" ".txt" in
Disk.write_file ~file:expected ~contents:(expected_contents ^ "\n");
Disk.write_file ~file:actual ~contents:(actual_contents ^ "\n");
Ppxlib_print_diff.print
~diff_command:
(Printf.sprintf
"diff -U9999 --label '%s' --label '%s'"
expected_name
actual_name)
~file1:expected
~file2:actual
()
let compare_folded
ctx
rupro_decls
~print_ocaml
~print_rupro
~test_ocamlrep_marshal
multifile
filename
text =
let class_names =
direct_decl_parse ctx filename text
|> List.rev_filter_map ~f:(function
| (name, Shallow_decl_defs.Class _) -> Some name
| _ -> None)
in
let ocaml_folded_classes =
List.map class_names ~f:(fun cid ->
Decl_provider.declare_folded_class_in_file_FOR_TESTS_ONLY ctx cid)
in
let rupro_folded_classes = Relative_path.Map.find rupro_decls filename in
(if test_ocamlrep_marshal then
let folded_class_decls = List.zip_exn class_names ocaml_folded_classes in
let test_marshaling (c, o) =
let ocaml_marshaled = Marshal.to_string o [] in
let rust_marshaled = Ocamlrep_marshal_ffi.to_string o [] in
let _ =
if not (String.equal rust_marshaled ocaml_marshaled) then
failwith
(Printf.sprintf
"Marshaling of '%s' differs between Rust and OCaml. This indicates 'ocamlrep_marshal_output_value_to_string' is broken.\nocaml:\n%S\nrust:\n%S\n"
c
ocaml_marshaled
rust_marshaled)
else
()
in
let rust_read_back = Ocamlrep_marshal_ffi.from_string rust_marshaled 0 in
let _ =
if
not
(String.equal
(Decl_defs.show_decl_class_type o)
(Decl_defs.show_decl_class_type rust_read_back))
then
failwith
(Printf.sprintf
"Rust unmarshaling of '%s' is wrong. This indicates 'ocamlrep_marshal_input_value' is broken."
c)
in
()
in
List.iter folded_class_decls ~f:test_marshaling);
let show_folded_decls decls =
decls
|> List.map ~f:Decl_folded_class_rupro.show_decl_class_type
|> String.concat ~sep:"\n"
in
let folded = show_folded_decls ocaml_folded_classes in
if print_ocaml then Format.eprintf "OCaml folded decls:\n%s\n\n" folded;
let rupro_folded = show_folded_decls rupro_folded_classes in
if print_rupro then Format.eprintf "rupro folded decls:\n%s\n\n" rupro_folded;
let matched = String.equal folded rupro_folded in
if not matched then (
(* All output is printed to stderr because that's the output
channel Ppxlib_print_diff prints to. *)
if multifile then
Printf.eprintf "File %s\n%!" (Relative_path.storage_to_string filename);
print_diff
~expected_name:"ocaml"
~actual_name:"rupro"
~expected_contents:folded
~actual_contents:rupro_folded
);
matched
let () =
let usage = Printf.sprintf "Usage: %s [OPTIONS] filename\n" Sys.argv.(0) in
let usage_and_exit () =
prerr_endline usage;
exit 1
in
let file = ref None in
let set_file f =
match !file with
| None -> file := Some f
| Some _ -> usage_and_exit ()
in
let auto_namespace_map = ref [] in
let enable_xhp_class_modifier = ref false in
let disable_xhp_element_mangling = ref false in
let keep_user_attributes = ref false in
let disallow_static_memoized = ref false in
let interpret_soft_types_as_like_types = ref false in
let everything_sdt = ref false in
let enable_strict_const_semantics = ref 0 in
let print_ocaml = ref false in
let print_rupro = ref false in
let test_ocamlrep_marshal = ref false in
let ignored_flag flag = (flag, Arg.Unit (fun _ -> ()), "(ignored)") in
let ignored_arg flag = (flag, Arg.String (fun _ -> ()), "(ignored)") in
Arg.parse
[
( "--auto-namespace-map",
Arg.String
(fun m ->
auto_namespace_map := ServerConfig.convert_auto_namespace_to_map m),
"Namespace aliases" );
( "--enable-xhp-class-modifier",
Arg.Set enable_xhp_class_modifier,
"Enable the XHP class modifier, xhp class name {} will define an xhp class."
);
( "--disable-xhp-element-mangling",
Arg.Set disable_xhp_element_mangling,
"." );
("--keep-user-attributes", Arg.Set keep_user_attributes, ".");
( "--disallow-static-memoized",
Arg.Set disallow_static_memoized,
" Disallow static memoized methods on non-final methods" );
( "--interpret-soft-types-as-like-types",
Arg.Set interpret_soft_types_as_like_types,
"Interpret <<__Soft>> type hints as like types" );
( "--everything-sdt",
Arg.Set everything_sdt,
" Treat all classes, functions, and traits as though they are annotated with <<__SupportDynamicType>>, unless they are annotated with <<__NoAutoDynamic>>"
);
( "--enable-strict-const-semantics",
Arg.Int (fun x -> enable_strict_const_semantics := x),
" Raise an error when a concrete constants is overridden or multiply defined"
);
( "--print-ocaml",
Arg.Set print_ocaml,
" Print OCaml folded decls to stdout" );
( "--print-rupro",
Arg.Set print_rupro,
" Print rupro folded decls to stdout" );
( "--test-marshaling",
Arg.Set test_ocamlrep_marshal,
" Test ocamlrep_marshal (rust) marshaling/unmarshaling" );
(* The following options do not affect the direct decl parser and can be ignored
(they are used by hh_single_type_check, and we run hh_single_decl over all of
the typecheck test cases). *)
ignored_flag "--enable-global-access-check";
ignored_flag "--abstract-static-props";
ignored_arg "--allowed-decl-fixme-codes";
ignored_arg "--allowed-fixme-codes-strict";
ignored_flag "--allow-toplevel-requires";
ignored_flag "--check-xhp-attribute";
ignored_flag "--complex-coercion";
ignored_flag "--const-attribute";
ignored_flag "--const-static-props";
ignored_arg "--disable-hh-ignore-error";
ignored_flag "--disable-modes";
ignored_flag "--disable-partially-abstract-typeconsts";
ignored_flag "--disable-unset-class-const";
ignored_flag "--disable-xhp-children-declarations";
ignored_flag "--disallow-discarded-nullable-awaitables";
ignored_flag "--disallow-fun-and-cls-meth-pseudo-funcs";
ignored_flag "--disallow-func-ptrs-in-constants";
ignored_flag "--disallow-invalid-arraykey-constraint";
ignored_flag "--disallow-php-lambdas";
ignored_flag "--disallow-silence";
ignored_flag "--disallow-trait-reuse";
ignored_flag "--enable-class-level-where-clauses";
ignored_flag "--enable-higher-kinded-types";
ignored_flag "--forbid_nullable_cast";
( "--hh-log-level",
Arg.Tuple [Arg.String (fun _ -> ()); Arg.String (fun _ -> ())],
"(ignored)" );
ignored_flag "--is-systemlib";
ignored_flag "--like-type-hints";
ignored_flag "--method-call-inference";
ignored_flag "--no-builtins";
ignored_flag "--no-strict-contexts";
ignored_flag "--report-pos-from-reason";
ignored_arg "--timeout";
ignored_flag "--union-intersection-type-hints";
ignored_flag "--enable-strict-string-concat-interp";
ignored_arg "--extra-builtin";
ignored_flag "--disallow-inst-meth";
ignored_flag "--ignore-unsafe-cast";
ignored_flag "--inc-dec-new-code";
ignored_flag "--math-new-code";
ignored_flag "--disallow-partially-abstract-typeconst-definitions";
ignored_flag "--typeconst-concrete-concrete-error";
ignored_arg "--strict-wellformedness";
ignored_arg "--meth-caller-only-public-visibility";
ignored_flag "--require-extends-implements-ancestors";
ignored_flag "--strict-value-equality";
ignored_flag "--enable-sealed-subclasses";
ignored_flag "--enable-sound-dynamic-type";
ignored_arg "--explicit-consistent-constructors";
ignored_arg "--require-types-class-consts";
ignored_flag "--skip-tast-checks";
ignored_flag "--expression-tree-virtualize-functions";
]
set_file
usage;
match !file with
| None -> usage_and_exit ()
| Some file ->
let file = Path.make file in
let auto_namespace_map = !auto_namespace_map in
let enable_xhp_class_modifier = !enable_xhp_class_modifier in
let disable_xhp_element_mangling = !disable_xhp_element_mangling in
let keep_user_attributes = !keep_user_attributes in
let interpret_soft_types_as_like_types =
!interpret_soft_types_as_like_types
in
let enable_strict_const_semantics = !enable_strict_const_semantics in
let everything_sdt = !everything_sdt in
let print_ocaml = !print_ocaml in
let print_rupro = !print_rupro in
let test_ocamlrep_marshal = !test_ocamlrep_marshal in
let popt =
popt
~auto_namespace_map
~enable_xhp_class_modifier
~disable_xhp_element_mangling
~keep_user_attributes
~interpret_soft_types_as_like_types
~everything_sdt
~enable_strict_const_semantics
in
let tco_experimental_features =
TypecheckerOptions.experimental_from_flags
~disallow_static_memoized:!disallow_static_memoized
in
let popt = { popt with GlobalOptions.tco_experimental_features } in
(* Temporarily set the root to the location of the test file so that
Multifile will strip the dirname prefix. *)
Relative_path.(set_path_prefix Root (Path.dirname file));
let file = Relative_path.(create Root (Path.to_string file)) in
let files =
Multifile.file_to_file_list file
|> List.map ~f:(fun (file, contents) ->
(Relative_path.to_absolute file, contents))
in
Tempfile.with_real_tempdir @@ fun tmpdir ->
(* Set the Relative_path root to the tmpdir. *)
Relative_path.(set_path_prefix Root tmpdir);
(* Write the files to a tempdir so that rupro can read them, then map
them to relative paths. *)
let files =
List.map files ~f:(fun (filename, contents) ->
let tmpdir = Path.to_string tmpdir in
let basename = Filename.basename filename in
let filename = Filename.concat tmpdir basename in
Disk.write_file ~file:filename ~contents;
(Relative_path.(create Root filename), contents))
in
let ctx = init ~enable_strict_const_semantics popt in
let iter_files f =
let multifile = List.length files > 1 in
List.fold files ~init:true ~f:(fun matched (filename, contents) ->
Provider_utils.respect_but_quarantine_unsaved_changes
~ctx
~f:(fun () -> f multifile filename contents)
&& matched)
in
let all_matched =
let files = List.map files ~f:fst in
let () =
List.iter files ~f:(fun filename ->
let _ =
Direct_decl_utils.direct_decl_parse_and_cache ctx filename
in
())
in
(* Compute OCaml folded decls *)
List.iter files ~f:(fun filename ->
Decl.make_env ~sh:SharedMem.Uses ctx filename);
(* Compute rupro folded decls *)
let rupro_decls =
match
Decl_folded_class_rupro.fold_classes_in_files
~root:(Path.to_string tmpdir)
popt
files
with
| Ok rupro_decls -> rupro_decls
| Error e ->
Printf.eprintf "%s\n%!" e;
exit 1
in
iter_files
(compare_folded
ctx
rupro_decls
~print_ocaml
~print_rupro
~test_ocamlrep_marshal)
in
if not all_matched then exit 1 |
OCaml | hhvm/hphp/hack/src/hackrs/compare_folded_decls_repo.ml | (**
* 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.
*
*)
open Hh_prelude
let purpose = "Compare Rust and OCaml Decl Folding on www repo"
let usage =
Printf.sprintf "Usage: %s <options> www-root\n%s" Sys.argv.(0) purpose
let make_workers
(root : Path.t)
(server_config : ServerConfig.t)
(server_local_config : ServerLocalConfig.t) : MultiWorker.worker list =
let num_workers = Sys_utils.nbr_procs in
let gc_control = Gc.get () in
let hhconfig_version =
server_config |> ServerConfig.version |> Config_file.version_to_string_opt
in
let shmem_config = ServerConfig.sharedmem_config server_config in
let heap_handle = SharedMem.init ~num_workers shmem_config in
ServerWorker.make
~longlived_workers:true
~nbr_procs:num_workers
gc_control
heap_handle
~logging_init:(fun () ->
HackEventLogger.init_worker
~root
~custom_columns:[]
~rollout_flags:(ServerLocalConfig.to_rollout_flags server_local_config)
~rollout_group:server_local_config.ServerLocalConfig.rollout_group
~hhconfig_version
~init_id:(Random_id.short_string ())
~time:(Unix.gettimeofday ())
~per_file_profiling:
server_local_config.ServerLocalConfig.per_file_profiling)
let measure_time (action : string) (f : unit -> 'a) : 'a =
Hh_logger.log "Start %s..." action;
let start_time = Unix.gettimeofday () in
let result = f () in
let _ =
Hh_logger.log_duration (Printf.sprintf "Finished %s" action) start_time
in
result
let init (root : Path.t) (naming_table_path : string option) :
Provider_context.t * Naming_table.t option * MultiWorker.worker list option
=
Relative_path.set_path_prefix Relative_path.Root root;
Relative_path.set_path_prefix Relative_path.Tmp (Path.make "tmpdir_NOT_USED");
Relative_path.set_path_prefix Relative_path.Hhi (Hhi.get_hhi_root ());
let server_args = ServerArgs.default_options ~root:(Path.to_string root) in
let (server_config, server_local_config) =
ServerConfig.load ~silent:true server_args
in
let popt = ServerConfig.parser_options server_config in
let tcopt = { popt with GlobalOptions.tco_higher_kinded_types = true } in
let ctx =
Provider_context.empty_for_tool
~popt
~tcopt
~backend:Provider_backend.Shared_memory
~deps_mode:(Typing_deps_mode.InMemoryMode None)
in
let workers = make_workers root server_config server_local_config in
Hh_logger.log
"About to decl %s with %d workers %s"
(Path.to_string root)
(List.length workers)
(match naming_table_path with
| Some path -> Printf.sprintf "with a naming table at %s" path
| None -> "without a naming table");
let naming_table =
Option.map naming_table_path ~f:(fun path ->
Naming_table.load_from_sqlite ctx path)
in
(ctx, naming_table, Some workers)
let parse_repo
(ctx : Provider_context.t)
(root : Path.t)
(workers : MultiWorker.worker list option) : FileInfo.t Relative_path.Map.t
=
let get_next =
ServerUtils.make_next
~hhi_filter:(fun _ -> true)
~indexer:
(Find.make_next_files ~name:"root" ~filter:FindUtils.is_hack root)
~extra_roots:(ServerConfig.extra_paths ServerConfig.default_config)
in
measure_time "parsing repo" @@ fun () ->
Direct_decl_service.go
ctx
workers
~ide_files:Relative_path.Set.empty
~get_next
~trace:false
~cache_decls:true
let fold_and_compare_single_decl
output_dir should_print (ctx : Provider_context.t) decl_class_name rust_decl
: bool =
let ocaml_decl_opt =
Decl_folded_class.class_decl_if_missing
~sh:SharedMem.Uses
ctx
decl_class_name
in
(* Incidentally test here that Rust and OCaml produce the same marshaled
bytes. *)
let ocaml_marshaled = Marshal.to_string ocaml_decl_opt [] in
let rust_marshaled = Ocamlrep_marshal_ffi.to_string ocaml_decl_opt [] in
let _ =
if not (String.equal rust_marshaled ocaml_marshaled) then
failwith
(Printf.sprintf
"Marshaling of '%s' differs between Rust and OCaml. This indicates 'ocamlrep_marshal_output_value_to_string' is broken."
decl_class_name)
else
()
in
(* Another incidental test here, this time that Rust unmarshaling works as
expected. *)
let rust_decl_opt = Ocamlrep_marshal_ffi.from_string rust_marshaled 0 in
let rust_read_back_matched =
match (ocaml_decl_opt, rust_decl_opt) with
| (Some (ocaml_decl, _), Some (rust_decl, _)) ->
String.equal
(Decl_defs.show_decl_class_type ocaml_decl)
(Decl_defs.show_decl_class_type rust_decl)
| (None, None) -> true
| _ -> false
in
let _ =
if not rust_read_back_matched then begin
Printf.printf "Rust decl unmarshaling failed:\n%!";
if Option.is_some ocaml_decl_opt then
Printf.printf
"ocaml:\n%s\n!"
(Decl_defs.show_decl_class_type
(fst (Option.value_exn ocaml_decl_opt)))
else
Printf.printf "ocaml:\nNone\n";
if Option.is_some rust_decl_opt then
Printf.printf
"rust:\n%s\n!"
(Decl_defs.show_decl_class_type
(fst (Option.value_exn rust_decl_opt)))
else
Printf.printf "ocaml:\nNone\n"
end
in
(* The real test: are the Rust decl and OCaml decl the same? *)
match ocaml_decl_opt with
| Some (ocaml_decl, _) ->
let is_identical =
Decl_folded_class_rupro.decls_equal ocaml_decl rust_decl
in
let () =
if (not is_identical) && should_print then
let ocaml_decl_str =
Decl_folded_class_rupro.show_decl_class_type ocaml_decl
in
let rust_decl_str =
Decl_folded_class_rupro.show_decl_class_type rust_decl
in
let file_path =
let file_path_len_limit = 250 in
let file_path = decl_class_name ^ ".rust.folded_decl" in
let file_path_len = String.length file_path in
let file_path =
if file_path_len > file_path_len_limit then
String.sub
file_path
~pos:(file_path_len - file_path_len_limit)
~len:file_path_len_limit
else
file_path
in
Path.to_string (Path.concat output_dir file_path)
in
Disk.write_file
~file:file_path
~contents:
("OCaml Decl:\n"
^ ocaml_decl_str
^ "\n"
^ "Rust Decl:\n"
^ rust_decl_str
^ "\n")
in
is_identical
| None ->
let _ = Hh_logger.error "[OCaml] Could not fold class %s" decl_class_name in
false
let fold_repo
(ctx : Provider_context.t)
(workers : MultiWorker.worker list option)
rust_decl_map
output_dir
print_limit =
let rust_decls = SMap.bindings rust_decl_map in
measure_time "folding repo" @@ fun () ->
let (num_correct, _num_checked) =
MultiWorker.call
workers
~job:(fun _ batch ->
List.fold
~f:(fun (num_correct, num_checked) (rust_class_name, rust_decl) ->
let same =
fold_and_compare_single_decl
output_dir
(num_checked - num_correct < print_limit)
ctx
rust_class_name
rust_decl
in
if same then
(num_correct + 1, num_checked + 1)
else
(num_correct, num_checked + 1))
~init:(0, 0)
batch)
~merge:(fun (i_correct, i_total) (j_correct, j_total) ->
(i_correct + j_correct, i_total + j_total))
~neutral:(0, 0)
~next:(MultiWorker.next workers rust_decls)
in
(num_correct, List.length rust_decls)
let () =
Daemon.check_entry_point ();
Folly.ensure_folly_init ();
let repo = ref None in
let naming_table_path = ref None in
let output_dir = ref None in
let num_partitions = ref 1 in
let partition_index = ref 0 in
let print_limit = ref 10 in
let args =
[
( "--naming-table",
Arg.String (fun s -> naming_table_path := Some s),
" Path to a SQLite naming table (allowing parsing to be done lazily instead of up-front)"
);
( "--output-dir",
Arg.String (fun s -> output_dir := Some s),
" Path to write decl differences to" );
( "--partition-index",
Arg.Int (fun i -> partition_index := i),
" What section of folded decls we compare" );
( "--num-partitions",
Arg.Int (fun i -> num_partitions := i),
" How many ranges there should be" );
( "--print-limit",
Arg.Int (fun i -> print_limit := i),
" How many diffs should be written per OCaml process" );
]
in
Arg.parse args (fun filepath -> repo := Some filepath) usage;
let (www_root, output_dir) =
match (!repo, !output_dir) with
| (Some root, Some path_to_write) ->
(Path.make root, Path.make path_to_write)
| _ ->
Arg.usage args usage;
Exit.exit Exit_status.Input_error
in
let rust_popt_init () =
Relative_path.set_path_prefix Relative_path.Root www_root;
Relative_path.set_path_prefix
Relative_path.Tmp
(Path.make "tmpdir_NOT_USED");
Relative_path.set_path_prefix Relative_path.Hhi (Hhi.get_hhi_root ());
let server_args =
ServerArgs.default_options ~root:(Path.to_string www_root)
in
let (server_config, _server_local_config) =
ServerConfig.load ~silent:true server_args
in
let popt = ServerConfig.parser_options server_config in
popt
in
let popt = rust_popt_init () in
let rust_decl_map =
Decl_folded_class_rupro.partition_and_fold_dir
~www_root:(Path.to_string www_root)
popt
!num_partitions
!partition_index
in
let (ctx, _naming_table_opt, workers) = init www_root !naming_table_path in
let _ = parse_repo ctx www_root workers in
let (number_correct, number_total) =
fold_repo ctx workers rust_decl_map output_dir !print_limit
in
let _ =
Hh_logger.log "num correct: %d out of %d" number_correct number_total
in
if Int.equal number_correct number_total then
exit 0
else
exit 1 |
Rust | hhvm/hphp/hack/src/hackrs/decl_file_rust.rs | // Copyright (c) Meta Platforms, Inc. and affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::path::PathBuf;
use std::sync::Arc;
use clap::Parser;
use decl_parser::DeclParser;
use decl_parser::DeclParserOptions;
use folded_decl_provider::FoldedDeclProvider;
use hackrs_test_utils::decl_provider::make_folded_decl_provider;
use hackrs_test_utils::serde_store::StoreOpts;
use hackrs_test_utils::store::make_shallow_decl_store;
use hackrs_test_utils::store::populate_shallow_decl_store;
use jwalk::WalkDir;
use pos::Prefix;
use pos::RelativePath;
use pos::RelativePathCtx;
use ty::decl::shallow;
use ty::reason::BReason;
use ty::reason::NReason;
use ty::reason::Reason;
#[derive(Parser, Debug)]
struct CliOptions {
/// The Hack source files to declare.
#[clap(value_name("FILEPATH"))]
filenames: Vec<PathBuf>,
/// The repository root (where .hhconfig is), e.g., ~/www
#[clap(long)]
root: Option<PathBuf>,
/// Path to a SQLite naming table (allowing declaration of a single file in a large repo).
#[clap(long)]
naming_table: Option<PathBuf>,
/// Allocate decls with positions instead of allocating position-free decls.
#[clap(long)]
with_pos: bool,
/// Print the shallow decls in the file.
#[clap(long)]
shallow: bool,
/// Print the folded decls of the classes in the file.
#[clap(long)]
folded: bool,
}
fn main() {
let mut opts = CliOptions::parse();
// If no modes were specified, print the shallow decls at least.
if !opts.shallow && !opts.folded {
opts.shallow = true;
}
if opts.with_pos {
decl_files::<BReason>(&opts);
} else {
decl_files::<NReason>(&opts);
}
}
fn decl_files<R: Reason>(opts: &CliOptions) {
// Add hhi files to the given list of filenames
let hhi_root = tempdir::TempDir::new("rupro_decl_file_hhi").unwrap();
hhi::write_hhi_files(hhi_root.path()).unwrap();
let path_ctx = Arc::new(RelativePathCtx {
root: opts.root.clone().unwrap_or_else(PathBuf::new),
hhi: hhi_root.path().into(),
dummy: PathBuf::new(),
tmp: PathBuf::new(),
});
let filenames: Vec<RelativePath> = opts
.filenames
.iter()
.map(|path| {
if let Some(root) = opts.root.as_ref() {
if let Ok(suffix) = path.strip_prefix(root) {
return RelativePath::new(Prefix::Root, suffix);
}
}
RelativePath::new(Prefix::Dummy, path)
})
.collect();
let mut all_filenames = WalkDir::new(&path_ctx.hhi)
.into_iter()
.filter_map(|e| e.ok())
.filter(|e| !e.file_type().is_dir())
.map(|e| RelativePath::new(Prefix::Hhi, e.path().strip_prefix(&path_ctx.hhi).unwrap()))
.collect::<Vec<_>>();
let file_provider: Arc<dyn file_provider::FileProvider> =
Arc::new(file_provider::DiskProvider::new(path_ctx, Some(hhi_root)));
let parser_opts = oxidized::parser_options::ParserOptions::default();
let decl_parser = DeclParser::<R>::new(
Arc::clone(&file_provider),
DeclParserOptions::from_parser_options(&parser_opts),
parser_opts.po_deregister_php_stdlib,
);
all_filenames.extend(&filenames);
let shallow_decl_store = make_shallow_decl_store(StoreOpts::Unserialized);
populate_shallow_decl_store(&shallow_decl_store, decl_parser.clone(), &all_filenames);
let folded_decl_provider = Arc::new(make_folded_decl_provider(
StoreOpts::Unserialized,
opts.naming_table.as_ref(),
shallow_decl_store,
Arc::new(parser_opts),
decl_parser.clone(),
));
let mut saw_err = false;
for path in filenames {
for decl in decl_parser.parse(path).unwrap() {
match decl {
shallow::NamedDecl::Class(name, decl) => {
if opts.shallow {
println!("{:#?}", decl);
}
if opts.folded {
match folded_decl_provider.get_class(name) {
Ok(decl) => println!(
"{:#?}",
decl.expect("expected decl provider to return Some")
),
Err(e) => {
saw_err = true;
eprintln!("Error: {}", e);
}
}
}
}
shallow::NamedDecl::Fun(_, decl) => println!("{:#?}", decl),
shallow::NamedDecl::Typedef(_, decl) => println!("{:#?}", decl),
shallow::NamedDecl::Const(_, decl) => println!("{:#?}", decl),
shallow::NamedDecl::Module(_, decl) => println!("{:#?}", decl),
}
}
}
if saw_err {
std::process::exit(1);
}
} |
Rust | hhvm/hphp/hack/src/hackrs/decl_folded_class_ffi.rs | // Copyright (c) Meta Platforms, Inc. and affiliates.
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::cmp;
use std::collections::BTreeMap;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use bumpalo::Bump;
use decl_parser::DeclParser;
use decl_parser::DeclParserOptions;
use folded_decl_provider::FoldedDeclProvider;
use hackrs_test_utils::serde_store::Compression;
use hackrs_test_utils::serde_store::StoreOpts;
use hackrs_test_utils::store::make_shallow_decl_store;
use hackrs_test_utils::store::populate_shallow_decl_store;
use indicatif::ParallelProgressIterator;
use jwalk::WalkDir;
use ocamlrep::FromOcamlRep;
use ocamlrep::FromOcamlRepIn;
use ocamlrep::ToOcamlRep;
use ocamlrep_ocamlpool::ocaml_ffi;
use ocamlrep_ocamlpool::ocaml_ffi_with_arena;
use oxidized::parser_options::ParserOptions;
use oxidized_by_ref::decl_defs::DeclClassType;
use pos::Prefix;
use pos::RelativePath;
use pos::RelativePathCtx;
use pos::ToOxidized;
use pos::TypeName;
use rayon::iter::IntoParallelIterator;
use rayon::iter::ParallelIterator;
use ty::decl::folded::FoldedClass;
use ty::decl::shallow;
use ty::reason::BReason;
fn find_hack_files(path: impl AsRef<Path>) -> impl Iterator<Item = PathBuf> {
WalkDir::new(path)
.into_iter()
.filter_map(|e| e.ok())
.filter(|e| !e.file_type().is_dir())
.map(|e| e.path())
.filter(|path| find_utils::is_hack(path))
}
/// Panic if the (possibly-handwritten) impl of ToOcamlRep doesn't match the
/// result of invoking to_oxidized followed by to_ocamlrep (since oxidized types
/// have a generated ToOcamlRep impl with stronger correctness guarantees).
fn verify_to_ocamlrep<'a, T>(bump: &'a Bump, value: &'a T)
where
T: ToOcamlRep + FromOcamlRep,
T: ToOxidized<'a> + From<<T as ToOxidized<'a>>::Output>,
T: std::fmt::Debug + PartialEq,
<T as ToOxidized<'a>>::Output: std::fmt::Debug + PartialEq + FromOcamlRepIn<'a>,
{
let alloc = &ocamlrep::Arena::new();
let oxidized_val = value.to_oxidized(bump);
let ocaml_val = unsafe { ocamlrep::Value::from_bits(value.to_ocamlrep(alloc).to_bits()) };
let ocamlrep_round_trip_val =
<T as ToOxidized<'_>>::Output::from_ocamlrep_in(ocaml_val, bump).unwrap();
let type_name = std::any::type_name::<T>();
assert_eq!(
ocamlrep_round_trip_val, oxidized_val,
"{}::to_ocamlrep does not match {}::to_oxidized",
type_name, type_name
);
let from_ocaml_val = T::from_ocamlrep(ocaml_val).unwrap();
assert_eq!(
from_ocaml_val,
T::from(ocamlrep_round_trip_val),
"{}::from_ocamlrep does not match From<oxidized_by_ref> value",
type_name
);
}
ocaml_ffi! {
fn fold_classes_in_files_ffi(
root: PathBuf,
opts: ParserOptions,
files: Vec<relative_path::RelativePath>,
) -> Result<BTreeMap<RelativePath, Vec<Arc<FoldedClass<BReason>>>>, String> {
let files: Vec<RelativePath> = files.iter().map(Into::into).collect();
let path_ctx = Arc::new(RelativePathCtx {
root,
..Default::default()
});
let file_provider: Arc<dyn file_provider::FileProvider> =
Arc::new(file_provider::DiskProvider::new(path_ctx, None));
let decl_parser = DeclParser::new(file_provider,
DeclParserOptions::from_parser_options(&opts),
opts.po_deregister_php_stdlib);
let shallow_decl_store = make_shallow_decl_store(StoreOpts::Unserialized);
let reverse_files = files.iter().copied().rev().collect::<Vec<_>>();
for path in &reverse_files {
let mut decls = decl_parser.parse(*path).unwrap();
decls.reverse(); // To match OCaml behavior for name collisions
shallow_decl_store.add_decls(decls).unwrap();
};
let folded_decl_provider =
hackrs_test_utils::decl_provider::make_folded_decl_provider(
StoreOpts::Unserialized,
None,
shallow_decl_store,
Arc::new(opts),
decl_parser.clone(),
);
files.into_iter().map(|filename| {
let decls = decl_parser
.parse(filename)
.map_err(|e| format!("Failed to parse {:?}: {:?}", filename, e))?;
for decl in decls.iter() {
match decl {
shallow::NamedDecl::Class(_, decl) => verify_to_ocamlrep(&Bump::new(), decl),
shallow::NamedDecl::Fun(_, decl) => verify_to_ocamlrep(&Bump::new(), decl),
shallow::NamedDecl::Typedef(_, decl) => verify_to_ocamlrep(&Bump::new(), decl),
shallow::NamedDecl::Const(_, decl) => verify_to_ocamlrep(&Bump::new(), decl),
shallow::NamedDecl::Module(_, decl) => verify_to_ocamlrep(&Bump::new(), decl),
}
}
let classes: Vec<TypeName> = decls
.into_iter()
.filter_map(|decl: ty::decl::shallow::NamedDecl<BReason>| match decl {
shallow::NamedDecl::Class(name, _) => Some(name),
_ => None,
})
.collect();
// Declare the classes in the reverse of their order in the file, to
// match the OCaml behavior. This should only matter when emitting
// errors for cyclic definitions.
for &name in classes.iter().rev() {
folded_decl_provider.get_class(name)
.map_err(|e| format!("Failed to fold class {}: {:?}", name, e))?;
}
Ok((filename, classes.into_iter().map(|name| {
let folded_class = folded_decl_provider
.get_class(name)
.map_err(|e| format!("Failed to fold class {}: {:?}", name, e))?
.ok_or_else(|| format!("Decl not found: class {}", name))?;
verify_to_ocamlrep(&Bump::new(), &*folded_class);
Ok(folded_class)
}).collect::<Result<_, String>>()?))
})
.collect()
}
}
ocaml_ffi_with_arena! {
fn show_decl_class_type_ffi<'a>(arena: &'a Bump, decl: &'a DeclClassType<'a>) -> String {
let decl = <FoldedClass<BReason>>::from(decl);
format!("{:#?}", decl)
}
fn decls_equal_ffi<'a>(
arena: &'a Bump,
ocaml_decl: &'a DeclClassType<'a>,
rust_decl: &'a DeclClassType<'a>
) -> bool {
let ocaml_decl = <FoldedClass<BReason>>::from(ocaml_decl);
let rust_decl = <FoldedClass<BReason>>::from(rust_decl);
ocaml_decl == rust_decl
}
}
ocaml_ffi! {
// Due to memory constraints when folding over a large directory, it may be necessary to
// fold over www in parts. This is achieved by finding the shallow decls of all of the files
// in the directory but then only folding over a portion of the classes in those files
// num_partitions controls the numbers of partitions (>= 1) the classes are divided into
// and partition_index controls which partition is being folded
// Returns a SMap from class_name to folded_decl
fn partition_and_fold_dir_ffi(
www_root: PathBuf,
opts: ParserOptions,
num_partitions: usize,
partition_index: usize,
) -> BTreeMap<String, Arc<FoldedClass<BReason>>> {
// Collect hhi files
let hhi_root = tempdir::TempDir::new("rupro_decl_repo_hhi").unwrap();
hhi::write_hhi_files(hhi_root.path()).unwrap();
let hhi_root_path: PathBuf = hhi_root.path().into();
let mut filenames: Vec<RelativePath> = find_hack_files(&hhi_root_path)
.map(|path| RelativePath::new(Prefix::Hhi, path.strip_prefix(&hhi_root_path).unwrap()))
.collect();
// Collect www files
filenames.extend(
find_hack_files(&www_root).map(|path| match path.strip_prefix(&www_root) {
Ok(suffix) => RelativePath::new(Prefix::Root, suffix),
Err(..) => RelativePath::new(Prefix::Dummy, &path),
}),
);
let path_ctx = Arc::new(RelativePathCtx {
root: www_root,
hhi: hhi_root_path,
..Default::default()
});
// Parse and gather shallow decls
let file_provider: Arc<dyn file_provider::FileProvider> =
Arc::new(file_provider::DiskProvider::new(path_ctx, Some(hhi_root)));
let decl_parser: DeclParser<BReason> = DeclParser::new(
file_provider,
DeclParserOptions::from_parser_options(&opts),
opts.po_deregister_php_stdlib
);
let shallow_decl_store =
make_shallow_decl_store(StoreOpts::Serialized(Compression::default()));
let mut classes =
populate_shallow_decl_store(&shallow_decl_store, decl_parser.clone(), &filenames);
classes.sort();
let folded_decl_provider = hackrs_test_utils::decl_provider::make_folded_decl_provider(
StoreOpts::Serialized(Compression::default()),
None,
shallow_decl_store,
Arc::new(opts),
decl_parser,
);
let len = classes.len();
// Add 1 to size to ensure that we only have num_partitions
let size_of_slices = (len / num_partitions) + 1;
// Account for edge case where partition_index * size goes out of bounds of the array
let start_index = cmp::min(len, partition_index * size_of_slices);
// end_index is exclusive, so no need to say len - 1
let end_index = cmp::min((partition_index + 1) * size_of_slices, len);
// If start_index = end_index, this will be empty vec
let s: Vec<(String, Arc<FoldedClass<BReason>>)> = (&classes[start_index..end_index])
.into_par_iter()
.progress_count(len.try_into().unwrap())
.map(|class| {
let folded_decl = folded_decl_provider
.get_class(*class)
.expect("failed to fold class")
.expect("failed to look up class");
(class.as_str().into(), folded_decl)
})
.collect();
s.into_iter()
.map(|(name, fc)| (name, fc))
.collect()
}
} |
OCaml | hhvm/hphp/hack/src/hackrs/decl_folded_class_rupro.ml | (*
* 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.
*
*)
external fold_classes_in_files :
root:string ->
ParserOptions.t ->
Relative_path.t list ->
(Decl_defs.decl_class_type list Relative_path.Map.t, string) result
= "fold_classes_in_files_ffi"
external show_decl_class_type : Decl_defs.decl_class_type -> string
= "show_decl_class_type_ffi"
external partition_and_fold_dir :
www_root:string ->
ParserOptions.t ->
int ->
int ->
Decl_defs.decl_class_type SMap.t = "partition_and_fold_dir_ffi"
external decls_equal :
Decl_defs.decl_class_type -> Decl_defs.decl_class_type -> bool
= "decls_equal_ffi" |
OCaml | hhvm/hphp/hack/src/hackrs/decl_repo_ocaml.ml | (**
* 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.
*
*)
open Hh_prelude
let purpose = "Profile Decl Folding on www repo"
let usage =
Printf.sprintf "Usage: %s <options> www-root\n%s" Sys.argv.(0) purpose
let make_workers
(root : Path.t)
(server_config : ServerConfig.t)
(server_local_config : ServerLocalConfig.t)
~(longlived_workers : bool)
~(log_sharedmem_stats : bool) : MultiWorker.worker list =
let num_workers = Sys_utils.nbr_procs in
let gc_control = Gc.get () in
let hhconfig_version =
server_config |> ServerConfig.version |> Config_file.version_to_string_opt
in
let shmem_config = ServerConfig.sharedmem_config server_config in
let log_level =
if log_sharedmem_stats then
1
else
0
in
let heap_handle =
SharedMem.(init ~num_workers { shmem_config with log_level })
in
ServerWorker.make
~longlived_workers
~nbr_procs:num_workers
gc_control
heap_handle
~logging_init:(fun () ->
HackEventLogger.init_worker
~root
~custom_columns:[]
~rollout_flags:(ServerLocalConfig.to_rollout_flags server_local_config)
~rollout_group:server_local_config.ServerLocalConfig.rollout_group
~hhconfig_version
~init_id:(Random_id.short_string ())
~time:(Unix.gettimeofday ())
~per_file_profiling:
server_local_config.ServerLocalConfig.per_file_profiling)
let measure_time (action : string) (f : unit -> 'a) : 'a =
Hh_logger.log "Start %s..." action;
let start_time = Unix.gettimeofday () in
let result = f () in
let _ =
Hh_logger.log_duration (Printf.sprintf "Finished %s" action) start_time
in
result
let init
(root : Path.t)
(naming_table_path : string option)
~(longlived_workers : bool)
~(rust_provider_backend : bool)
~(log_sharedmem_stats : bool) :
Provider_context.t * Naming_table.t option * MultiWorker.worker list option
=
Relative_path.set_path_prefix Relative_path.Root root;
Relative_path.set_path_prefix Relative_path.Tmp (Path.make "tmpdir_NOT_USED");
Relative_path.set_path_prefix Relative_path.Hhi (Hhi.get_hhi_root ());
let server_args = ServerArgs.default_options ~root:(Path.to_string root) in
let server_args =
ServerArgs.(
set_config
server_args
([
("rust_provider_backend", string_of_bool rust_provider_backend);
("shm_use_sharded_hashtbl", "true");
("shm_cache_size", string_of_int (60 * (1024 * 1024 * 1024)));
("populate_member_heaps", "false");
]
@ config server_args))
in
let (server_config, server_local_config) =
ServerConfig.load ~silent:true server_args
in
let popt = ServerConfig.parser_options server_config in
let tcopt = { popt with GlobalOptions.tco_higher_kinded_types = true } in
if rust_provider_backend then Provider_backend.set_rust_backend popt;
let ctx =
Provider_context.empty_for_tool
~popt
~tcopt
~backend:(Provider_backend.get ())
~deps_mode:(Typing_deps_mode.InMemoryMode None)
in
let workers =
make_workers
root
server_config
server_local_config
~longlived_workers
~log_sharedmem_stats
in
Hh_logger.log
"About to decl %s with %d workers %s"
(Path.to_string root)
(List.length workers)
(match naming_table_path with
| Some path -> Printf.sprintf "with a naming table at %s" path
| None -> "without a naming table");
let naming_table =
Option.map naming_table_path ~f:(fun path ->
if Sys.file_exists path then
Naming_table.load_from_sqlite ctx path
else
failwith (Printf.sprintf "The file '%s' does not exist" path))
in
(ctx, naming_table, Some workers)
let parse_repo
(ctx : Provider_context.t)
(root : Path.t)
(workers : MultiWorker.worker list option) : FileInfo.t Relative_path.Map.t
=
let get_next =
ServerUtils.make_next
~hhi_filter:(fun _ -> true)
~indexer:
(Find.make_next_files ~name:"root" ~filter:FindUtils.is_hack root)
~extra_roots:(ServerConfig.extra_paths ServerConfig.default_config)
in
measure_time "parsing repo" @@ fun () ->
Direct_decl_service.go
ctx
workers
~ide_files:Relative_path.Set.empty
~get_next
~trace:false
~cache_decls:true
let populate_naming_table
(ctx : Provider_context.t)
(file_summaries : FileInfo.t Relative_path.Map.t)
(workers : MultiWorker.worker list option) : unit =
measure_time "populating naming table" @@ fun () ->
let summaries = Relative_path.Map.elements file_summaries in
MultiWorker.call
workers
~job:(fun _ batch ->
List.iter
~f:(fun (path, fileinfo) ->
Naming_global.ndecl_file_skip_if_already_bound ctx path fileinfo)
batch)
~merge:(fun _ _ -> ())
~neutral:()
~next:(MultiWorker.next workers summaries)
let fold_single_file
(ctx : Provider_context.t)
((_file, summary) : Relative_path.t * FileInfo.names) : unit =
let class_names = summary.FileInfo.n_classes in
SSet.iter
(fun class_name ->
match Decl_provider.get_class ctx class_name with
| Some _ -> ()
| None -> failwith ("missing class: " ^ class_name))
class_names
let fold_repo
(ctx : Provider_context.t)
(workers : MultiWorker.worker list option)
(summaries : (Relative_path.t * FileInfo.names) list) : unit =
measure_time "folding repo" @@ fun () ->
MultiWorker.call
workers
~job:(fun _ batch -> List.iter ~f:(fold_single_file ctx) batch)
~merge:(fun _ _ -> ())
~neutral:()
~next:(MultiWorker.next workers summaries)
let () =
Daemon.check_entry_point ();
Folly.ensure_folly_init ();
let repo = ref None in
let naming_table_path = ref None in
let longlived_workers = ref false in
let rust_provider_backend = ref false in
let log_sharedmem_stats = ref false in
let num_files = ref None in
let args =
[
( "--naming-table",
Arg.String (fun s -> naming_table_path := Some s),
" Path to a SQLite naming table (allowing parsing to be done lazily instead of up-front)"
);
( "--longlived-workers",
Arg.Set longlived_workers,
" Enable longlived worker processes" );
( "--rust-provider-backend",
Arg.Set rust_provider_backend,
" Use the Rust implementation of Provider_backend (including decl-folding)"
);
( "--num-files",
Arg.Int (fun n -> num_files := Some n),
" Fold only this number of files instead of the entire repository" );
( "--log-sharedmem-stats",
Arg.Set log_sharedmem_stats,
" Record sharedmem telemetry and print before exit" );
]
in
Arg.parse args (fun filepath -> repo := Some filepath) usage;
let root =
match !repo with
| Some root -> Path.make root
| _ ->
Arg.usage args usage;
Exit.exit Exit_status.Input_error
in
let (ctx, naming_table_opt, workers) =
init
root
!naming_table_path
~longlived_workers:!longlived_workers
~rust_provider_backend:!rust_provider_backend
~log_sharedmem_stats:!log_sharedmem_stats
in
let file_summaries =
match naming_table_opt with
| Some naming_table ->
(try
Naming_table.to_defs_per_file
~warn_on_naming_costly_iter:false
naming_table
with
| _ ->
Hh_logger.log
"Failed to query classes from the naming table. Falling back to parsing the whole repo.";
parse_repo ctx root workers
|> Relative_path.Map.map ~f:FileInfo.simplify)
| None ->
let file_summaries = parse_repo ctx root workers in
populate_naming_table ctx file_summaries workers;
Relative_path.Map.map file_summaries ~f:FileInfo.simplify
in
let files_in_repo = Relative_path.Map.cardinal file_summaries in
Hh_logger.log "Collected %d file summaries" files_in_repo;
let file_summaries =
match !num_files with
| None -> file_summaries
| Some n ->
let files = Relative_path.Map.elements file_summaries in
let files = List.drop files ((files_in_repo - n) / 2) in
let files = List.take files n in
Relative_path.Map.of_list files
in
let with_shmem_logging f =
if SharedMem.SMTelemetry.hh_log_level () > 0 then Measure.push_global ();
f ();
if SharedMem.SMTelemetry.hh_log_level () > 0 then
Measure.print_stats () ~record:(Measure.pop_global ())
in
Hh_logger.log "Phase: writing folded decls";
with_shmem_logging (fun () ->
fold_repo ctx workers (Relative_path.Map.elements file_summaries));
Hh_logger.log "Phase: reading back folded decls";
with_shmem_logging (fun () ->
fold_repo ctx workers (Relative_path.Map.elements file_summaries));
() |
Rust | hhvm/hphp/hack/src/hackrs/decl_repo_rust.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.
// 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::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use decl_parser::DeclParser;
use decl_parser::DeclParserOptions;
use folded_decl_provider::FoldedDeclProvider;
use hackrs_test_utils::decl_provider::make_folded_decl_provider;
use hackrs_test_utils::serde_store::Compression;
use hackrs_test_utils::serde_store::StoreOpts;
use hackrs_test_utils::store::make_shallow_decl_store;
use hackrs_test_utils::store::populate_shallow_decl_store;
use indicatif::ParallelProgressIterator;
use jwalk::WalkDir;
use pos::Prefix;
use pos::RelativePath;
use pos::RelativePathCtx;
use pos::TypeName;
use rayon::prelude::*;
use tempdir::TempDir;
use ty::reason::BReason;
use ty::reason::NReason;
use ty::reason::Reason;
#[derive(clap::Parser, Debug)]
struct CliOptions {
/// The repository root (where .hhconfig is), e.g., ~/www
root: PathBuf,
/// Set the number of threads to use for parsing and folding.
///
/// If omitted or set to 0, uses the rayon default (the value of the
/// `RAYON_NUM_THREADS` environment variable if set, or the number of
/// logical CPUs otherwise).
#[clap(long)]
num_threads: Option<usize>,
/// Path to a SQLite naming table (allowing parsing to be done lazily instead of up-front).
#[clap(long)]
naming_table: Option<PathBuf>,
/// Allocate decls with positions instead of allocating position-free decls.
#[clap(long)]
with_pos: bool,
/// In addition to parsing shallow decls, compute folded class decls.
#[clap(long)]
fold: bool,
/// Keep all decls in memory rather than serializing and compressing them.
#[clap(long)]
no_serialize: bool,
/// Use the given compression algorithm when serializing decls (if serialization is enabled).
#[clap(default_value = "none", long)]
compression: Compression,
/// Output profiling results for folding (in JSON format) to a separate file.
#[clap(long)]
profile_output: Option<PathBuf>,
}
#[derive(serde::Serialize, Debug, Default)]
struct ProfileFoldResult {
real_time: f64,
rss: f64,
}
fn main() {
let opts = <CliOptions as clap::Parser>::parse();
if let Some(num_threads) = opts.num_threads {
rayon::ThreadPoolBuilder::new()
.num_threads(num_threads)
.build_global()
.unwrap();
}
let hhi_root = TempDir::new("rupro_decl_repo_hhi").unwrap();
hhi::write_hhi_files(hhi_root.path()).unwrap();
let path_ctx = Arc::new(RelativePathCtx {
root: opts.root.clone(),
hhi: hhi_root.path().into(),
dummy: PathBuf::new(),
tmp: PathBuf::new(),
});
if opts.with_pos {
decl_repo::<BReason>(&opts, path_ctx, hhi_root);
} else {
decl_repo::<NReason>(&opts, path_ctx, hhi_root);
}
}
fn decl_repo<R: Reason>(opts: &CliOptions, ctx: Arc<RelativePathCtx>, hhi_root: TempDir) {
use oxidized::parser_options::ParserOptions;
let names = collect_file_or_class_names(opts, &ctx);
let file_provider: Arc<dyn file_provider::FileProvider> = Arc::new(
file_provider::DiskProvider::new(Arc::clone(&ctx), Some(hhi_root)),
);
let parser_opts = ParserOptions::default();
let parser = DeclParser::new(
file_provider,
DeclParserOptions::from_parser_options(&parser_opts),
parser_opts.po_deregister_php_stdlib,
);
let shallow_decl_store = make_shallow_decl_store::<R>(if opts.no_serialize {
StoreOpts::Unserialized
} else {
StoreOpts::Serialized(opts.compression)
});
let classes = match names {
Names::Classnames(classes) => classes,
Names::Filenames(filenames) => {
let (classes, time_taken) = time(|| {
populate_shallow_decl_store(&shallow_decl_store, parser.clone(), &filenames)
});
println!(
"Parsed {} classes in repo in {:?}",
classes.len(),
time_taken
);
print_rss();
classes
}
};
let folded_decl_provider = make_folded_decl_provider(
if opts.no_serialize {
StoreOpts::Unserialized
} else {
StoreOpts::Serialized(opts.compression)
},
opts.naming_table.as_ref(),
shallow_decl_store,
Arc::new(parser_opts),
parser,
);
if opts.fold {
let len = classes.len();
let ((), time_taken) = time(|| fold(&folded_decl_provider, classes));
println!("Folded {} classes in repo in {:?}", len, time_taken);
let rss = print_rss();
if let Some(output_path) = &opts.profile_output {
write_profile_fold_result(
output_path,
ProfileFoldResult {
real_time: time_taken.as_secs_f64(),
rss,
},
)
}
}
// Avoid running the decl provider's destructor or destructors for hcons
// tables, since our stores are huge and full of Arcs which reference one
// another.
std::process::exit(0);
}
fn write_profile_fold_result(output_path: &Path, profile: ProfileFoldResult) {
let mut output_file = std::fs::File::create(output_path).unwrap();
serde_json::to_writer(&mut output_file, &profile).unwrap();
}
enum Names {
Filenames(Vec<RelativePath>),
Classnames(Vec<TypeName>),
}
fn collect_file_or_class_names(opts: &CliOptions, ctx: &RelativePathCtx) -> Names {
if let Some(naming_table) = &opts.naming_table {
let (classes, time_taken) = time(|| {
let conn = rusqlite::Connection::open(naming_table).unwrap();
let mut stmt = conn
.prepare("select classes from naming_file_info")
.unwrap();
let mut rows = stmt.query(rusqlite::params![]).unwrap();
let mut classes = vec![];
while let Some(row) = rows.next().unwrap() {
let row: Option<String> = row.get(0).unwrap();
if let Some(row) = row {
classes.extend(row.split('|').filter(|s| !s.is_empty()).map(TypeName::from));
}
}
classes
});
println!(
"Queried {} classes from naming table in {:?}",
classes.len(),
time_taken
);
Names::Classnames(classes)
} else {
let mut filenames: Vec<RelativePath> = find_hack_files(&ctx.hhi)
.map(|path| RelativePath::new(Prefix::Hhi, path.strip_prefix(&ctx.hhi).unwrap()))
.collect();
let ((), time_taken) = time(|| {
filenames.extend(find_hack_files(&opts.root).map(|path| {
match path.strip_prefix(&ctx.root) {
Ok(suffix) => RelativePath::new(Prefix::Root, suffix),
Err(..) => RelativePath::new(Prefix::Dummy, &path),
}
}))
});
println!(
"Collected {} filenames in {:?}",
filenames.len(),
time_taken
);
Names::Filenames(filenames)
}
}
fn fold<R: Reason>(provider: &impl FoldedDeclProvider<R>, classes: Vec<TypeName>) {
let len = classes.len();
classes
.into_par_iter()
.progress_count(len as u64)
.for_each(|class| {
provider
.get_class(class)
.unwrap_or_else(|e| panic!("failed to fold class {}: {:?}", class, e))
.unwrap_or_else(|| panic!("failed to look up class {}", class));
})
}
fn find_hack_files(path: impl AsRef<Path>) -> impl Iterator<Item = PathBuf> {
WalkDir::new(path)
.into_iter()
.filter_map(|e| e.ok())
.filter(|e| !e.file_type().is_dir())
.map(|e| e.path())
.filter(|path| find_utils::is_hack(path))
}
fn print_rss() -> f64 {
let me = procfs::process::Process::myself().unwrap();
let page_size = procfs::page_size().unwrap();
let rss = (me.stat.rss * page_size) as f64 / 1024.0 / 1024.0 / 1024.0;
println!("RSS: {:.3}GiB", rss);
rss
}
fn time<T>(f: impl FnOnce() -> T) -> (T, std::time::Duration) {
let start = std::time::Instant::now();
let result = f();
let time_taken = start.elapsed();
(result, time_taken)
} |
TOML | hhvm/hphp/hack/src/hackrs/cargo/decl_file_rust/Cargo.toml | # @generated by autocargo
[package]
name = "decl_file_rust"
version = "0.0.0"
edition = "2021"
[[bin]]
name = "decl_file_rust"
path = "../../decl_file_rust.rs"
[dependencies]
clap = { version = "4.3.5", features = ["derive", "env", "string", "unicode", "wrap_help"] }
decl_parser = { version = "0.0.0", path = "../../decl_parser/cargo/decl_parser" }
file_provider = { version = "0.0.0", path = "../../file_provider/cargo/file_provider" }
folded_decl_provider = { version = "0.0.0", path = "../../folded_decl_provider/cargo/folded_decl_provider" }
hackrs_test_utils = { version = "0.0.0", path = "../../hackrs_test_utils/cargo/hackrs_test_utils" }
hhi = { version = "0.0.0", path = "../../../hhi/rust" }
jwalk = "0.6"
oxidized = { version = "0.0.0", path = "../../../oxidized" }
pos = { version = "0.0.0", path = "../../pos/cargo/pos" }
tempdir = "0.3"
ty = { version = "0.0.0", path = "../../ty/cargo/ty" } |
TOML | hhvm/hphp/hack/src/hackrs/cargo/decl_folded_class_ffi/Cargo.toml | # @generated by autocargo
[package]
name = "decl_folded_class_ffi"
version = "0.0.0"
edition = "2021"
[lib]
path = "../../decl_folded_class_ffi.rs"
test = false
doctest = false
crate-type = ["lib", "staticlib"]
[dependencies]
bumpalo = { version = "3.11.1", features = ["collections"] }
decl_parser = { version = "0.0.0", path = "../../decl_parser/cargo/decl_parser" }
file_provider = { version = "0.0.0", path = "../../file_provider/cargo/file_provider" }
find_utils = { version = "0.0.0", path = "../../../utils/find_utils" }
folded_decl_provider = { version = "0.0.0", path = "../../folded_decl_provider/cargo/folded_decl_provider" }
hackrs_test_utils = { version = "0.0.0", path = "../../hackrs_test_utils/cargo/hackrs_test_utils" }
hhi = { version = "0.0.0", path = "../../../hhi/rust" }
indicatif = { version = "0.17.3", features = ["improved_unicode", "rayon", "tokio"] }
jwalk = "0.6"
ocamlrep = { version = "0.1.0", git = "https://github.com/facebook/ocamlrep/", branch = "main" }
ocamlrep_ocamlpool = { version = "0.1.0", git = "https://github.com/facebook/ocamlrep/", branch = "main" }
oxidized = { version = "0.0.0", path = "../../../oxidized" }
oxidized_by_ref = { version = "0.0.0", path = "../../../oxidized_by_ref" }
pos = { version = "0.0.0", path = "../../pos/cargo/pos" }
rayon = "1.2"
relative_path = { version = "0.0.0", path = "../../../utils/rust/relative_path" }
tempdir = "0.3"
ty = { version = "0.0.0", path = "../../ty/cargo/ty" } |
TOML | hhvm/hphp/hack/src/hackrs/cargo/decl_repo_rust/Cargo.toml | # @generated by autocargo
[package]
name = "decl_repo_rust"
version = "0.0.0"
edition = "2021"
[[bin]]
name = "decl_repo_rust"
path = "../../decl_repo_rust.rs"
test = false
[dependencies]
clap = { version = "4.3.5", features = ["derive", "env", "string", "unicode", "wrap_help"] }
decl_parser = { version = "0.0.0", path = "../../decl_parser/cargo/decl_parser" }
file_provider = { version = "0.0.0", path = "../../file_provider/cargo/file_provider" }
find_utils = { version = "0.0.0", path = "../../../utils/find_utils" }
folded_decl_provider = { version = "0.0.0", path = "../../folded_decl_provider/cargo/folded_decl_provider" }
hackrs_test_utils = { version = "0.0.0", path = "../../hackrs_test_utils/cargo/hackrs_test_utils" }
hhi = { version = "0.0.0", path = "../../../hhi/rust" }
indicatif = { version = "0.17.3", features = ["improved_unicode", "rayon", "tokio"] }
jwalk = "0.6"
oxidized = { version = "0.0.0", path = "../../../oxidized" }
pos = { version = "0.0.0", path = "../../pos/cargo/pos" }
procfs = "0.10.1"
rayon = "1.2"
rusqlite = { version = "0.29.0", features = ["backup", "blob", "column_decltype", "limits"] }
serde = { version = "1.0.176", features = ["derive", "rc"] }
serde_json = { version = "1.0.100", features = ["float_roundtrip", "unbounded_depth"] }
tempdir = "0.3"
ty = { version = "0.0.0", path = "../../ty/cargo/ty" } |
TOML | hhvm/hphp/hack/src/hackrs/datastore/Cargo.toml | # @generated by autocargo
[package]
name = "datastore"
version = "0.0.0"
edition = "2021"
[lib]
path = "datastore.rs"
[dependencies]
anyhow = "1.0.71"
dashmap = { version = "5.4", features = ["rayon", "serde"] }
hash = { version = "0.0.0", path = "../../utils/hash" }
parking_lot = { version = "0.12.1", features = ["send_guard"] } |
Rust | hhvm/hphp/hack/src/hackrs/datastore/changes_store.rs | // Copyright (c) Meta Platforms, Inc. and affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::hash::Hash;
use std::sync::Arc;
use anyhow::Result;
use dashmap::DashMap;
use parking_lot::RwLock;
use crate::Store;
/// A stack of temporary changes on top of a fallback data store.
pub struct ChangesStore<K, V> {
stack: RwLock<Vec<DashMap<K, Option<V>>>>,
fallback: Arc<dyn Store<K, V>>,
}
impl<K: Copy + Hash + Eq, V: Clone> ChangesStore<K, V> {
pub fn new(fallback: Arc<dyn Store<K, V>>) -> Self {
Self {
stack: Default::default(),
fallback,
}
}
pub fn contains_key(&self, key: K) -> Result<bool> {
for store in self.stack.read().iter().rev() {
if let Some(opt) = store.get(&key) {
return Ok(opt.is_some());
}
}
self.fallback.contains_key(key)
}
pub fn get(&self, key: K) -> Result<Option<V>> {
for store in self.stack.read().iter().rev() {
if let Some(val_opt) = store.get(&key) {
return Ok(val_opt.clone());
}
}
self.fallback.get(key)
}
pub fn has_local_change(&self, key: K) -> bool {
for store in self.stack.read().iter().rev() {
if store.contains_key(&key) {
return true;
}
}
false
}
pub fn has_local_changes(&self) -> bool {
!self.stack.read().is_empty()
}
pub fn insert(&self, key: K, val: V) -> Result<()> {
if let Some(store) = self.stack.read().last() {
store.insert(key, Some(val));
} else {
self.fallback.insert(key, val)?;
}
Ok(())
}
pub fn push_local_changes(&self) {
self.stack.write().push(Default::default());
}
pub fn pop_local_changes(&self) {
self.stack.write().pop();
}
pub fn move_batch(&self, keys: &mut dyn Iterator<Item = (K, K)>) -> Result<()> {
if let Some(store) = self.stack.read().last() {
for (old_key, new_key) in keys {
match self.get(old_key)? {
val_opt @ Some(_) => {
store.insert(old_key, None);
store.insert(new_key, val_opt);
}
None => {
anyhow::bail!("move_batch: Trying to remove a non-existent value");
}
}
}
} else {
self.fallback.move_batch(keys)?;
}
Ok(())
}
pub fn remove_batch(&self, keys: &mut dyn Iterator<Item = K>) -> Result<()> {
if let Some(store) = self.stack.read().last() {
for key in keys {
if self.contains_key(key)? {
store.insert(key, None);
}
}
} else {
self.fallback.remove_batch(keys)?;
}
Ok(())
}
}
impl<K, V> Store<K, V> for ChangesStore<K, V>
where
K: Copy + Hash + Eq + Send + Sync,
V: Clone + Send + Sync,
{
fn contains_key(&self, key: K) -> Result<bool> {
ChangesStore::contains_key(self, key)
}
fn get(&self, key: K) -> Result<Option<V>> {
ChangesStore::get(self, key)
}
fn insert(&self, key: K, val: V) -> Result<()> {
ChangesStore::insert(self, key, val)
}
fn move_batch(&self, keys: &mut dyn Iterator<Item = (K, K)>) -> Result<()> {
ChangesStore::move_batch(self, keys)
}
fn remove_batch(&self, keys: &mut dyn Iterator<Item = K>) -> Result<()> {
ChangesStore::remove_batch(self, keys)
}
}
impl<K: Copy, V> std::fmt::Debug for ChangesStore<K, V> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ChangesStore").finish()
}
} |
Rust | hhvm/hphp/hack/src/hackrs/datastore/datastore.rs | // Copyright (c) Meta Platforms, Inc. and affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
mod changes_store;
mod delta_store;
mod empty;
mod non_evicting;
use std::fmt::Debug;
use anyhow::Result;
pub use changes_store::ChangesStore;
pub use delta_store::DeltaStore;
pub use empty::EmptyStore;
pub use non_evicting::NonEvictingLocalStore;
pub use non_evicting::NonEvictingStore;
/// A threadsafe datastore, intended for global decl storage. The key type is
/// intended to be a `Symbol` or tuple of `Symbol`s, and the value type is
/// intended to be a ref-counted pointer (like `Arc` or `Hc`).
pub trait Store<K: Copy, V>: Debug + Send + Sync {
fn get(&self, key: K) -> Result<Option<V>>;
fn insert(&self, key: K, val: V) -> Result<()>;
/// Return `true` if the store contains a value for the given key (i.e.,
/// `self.get(key)?.is_some()` would evaluate to `true`).
///
/// A default implementation is provided which uses the store's
/// implementation of `Store::get`, but some implementors will be able to
/// implement `contains_key` more efficiently than `get`.
fn contains_key(&self, key: K) -> Result<bool> {
Ok(self.get(key)?.is_some())
}
/// Implementations are free to ignore a key to be removed if it does not
/// exist.
fn remove_batch(&self, keys: &mut dyn Iterator<Item = K>) -> Result<()>;
/// Implementations should return an error if a key to be moved does not
/// exist and well defined behavior is not a requirement if a key occurs in
/// both an old and new position.
fn move_batch(&self, keys: &mut dyn Iterator<Item = (K, K)>) -> Result<()> {
for (old_key, new_key) in keys {
if let Some(val) = self.get(old_key)? {
self.remove_batch(&mut std::iter::once(old_key))?;
self.insert(new_key, val)?;
} else {
anyhow::bail!("move_batch: Trying to remove a non-existent value");
}
}
Ok(())
}
}
/// A thread-local datastore, intended for decl caching in typechecker workers.
/// The key type is intended to be a `Symbol` or tuple of `Symbol`s, and the
/// value type is intended to be a ref-counted pointer (like `Rc`).
pub trait LocalStore<K: Copy, V>: Debug {
fn get(&self, key: K) -> Option<V>;
fn insert(&mut self, key: K, val: V);
fn remove_batch(&mut self, keys: &mut dyn Iterator<Item = K>);
}
/// A readonly threadsafe datastore, intended to model readonly data sources
/// (like the filesystem in file_provider, or the naming SQLite database in
/// naming_provider) in terms of `datastore` traits (for purposes like
/// `DeltaStore`).
pub trait ReadonlyStore<K: Copy, V>: Send + Sync {
fn get(&self, key: K) -> Result<Option<V>>;
fn contains_key(&self, key: K) -> Result<bool> {
Ok(self.get(key)?.is_some())
}
}
impl<T: Store<K, V>, K: Copy, V> ReadonlyStore<K, V> for T {
fn contains_key(&self, key: K) -> Result<bool> {
Store::contains_key(self, key)
}
fn get(&self, key: K) -> Result<Option<V>> {
Store::get(self, key)
}
} |
Rust | hhvm/hphp/hack/src/hackrs/datastore/delta_store.rs | // Copyright (c) Meta Platforms, Inc. and affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::hash::Hash;
use std::sync::Arc;
use anyhow::Result;
use crate::ReadonlyStore;
use crate::Store;
/// A mutable set of changes on top of a readonly fallback data store.
///
/// Reads from the fallback store are cached in the delta, so it is important
/// not to use `DeltaStore` in scenarios where the fallback store may mutate and
/// those mutations need to be observable.
pub struct DeltaStore<K, V> {
delta: Arc<dyn Store<K, Option<V>>>,
fallback: Arc<dyn ReadonlyStore<K, V>>,
}
impl<K: Copy + Hash + Eq, V: Clone> DeltaStore<K, V> {
pub fn new(
delta: Arc<dyn Store<K, Option<V>>>,
fallback: Arc<dyn ReadonlyStore<K, V>>,
) -> Self {
Self { delta, fallback }
}
pub fn contains_key(&self, key: K) -> Result<bool> {
if let Some(opt) = self.delta.get(key)? {
Ok(opt.is_some())
} else {
self.fallback.contains_key(key)
}
}
pub fn get(&self, key: K) -> Result<Option<V>> {
if let Some(val_opt) = self.delta.get(key)? {
Ok(val_opt)
} else {
let val_opt = self.fallback.get(key)?;
self.delta.insert(key, val_opt.clone())?;
Ok(val_opt)
}
}
pub fn insert(&self, key: K, val: V) -> Result<()> {
self.delta.insert(key, Some(val))
}
pub fn remove(&self, key: K) -> Result<()> {
self.delta.insert(key, None)
}
pub fn remove_batch(&self, keys: &mut dyn Iterator<Item = K>) -> Result<()> {
for key in keys {
if self.get(key)?.is_some() {
self.remove(key)?;
}
}
Ok(())
}
}
impl<K: Copy + Hash + Eq, V: Clone> Store<K, V> for DeltaStore<K, V> {
fn contains_key(&self, key: K) -> Result<bool> {
DeltaStore::contains_key(self, key)
}
fn get(&self, key: K) -> Result<Option<V>> {
DeltaStore::get(self, key)
}
fn insert(&self, key: K, val: V) -> Result<()> {
DeltaStore::insert(self, key, val)
}
fn remove_batch(&self, keys: &mut dyn Iterator<Item = K>) -> Result<()> {
DeltaStore::remove_batch(self, keys)
}
}
impl<K: Copy, V> std::fmt::Debug for DeltaStore<K, V> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DeltaStore").finish()
}
} |
Rust | hhvm/hphp/hack/src/hackrs/datastore/empty.rs | // Copyright (c) Meta Platforms, Inc. and affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use anyhow::Result;
/// A zero-sized store which retains no data, returns `false` for any call to
/// `contains_key` and returns `None` for every `get`.
#[derive(Debug)]
pub struct EmptyStore;
impl<K: Copy, V> crate::Store<K, V> for EmptyStore {
fn contains_key(&self, _key: K) -> Result<bool> {
Ok(false)
}
fn get(&self, _key: K) -> Result<Option<V>> {
Ok(None)
}
fn insert(&self, _key: K, _val: V) -> Result<()> {
Ok(())
}
fn remove_batch(&self, _keys: &mut dyn Iterator<Item = K>) -> Result<()> {
Ok(())
}
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.