language
stringlengths 0
24
| filename
stringlengths 9
214
| code
stringlengths 99
9.93M
|
---|---|---|
Rust | hhvm/hphp/hack/src/elab/passes/elab_enum_class.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 nast::Abstraction;
use nast::Class_;
use nast::ClassishKind;
use nast::Expr_;
use nast::Hint;
use nast::Hint_;
use nast::Id;
use nast::Pos;
use nast::UserAttributes;
use crate::prelude::*;
#[derive(Clone, Copy, Default)]
pub struct ElabEnumClassPass;
impl Pass for ElabEnumClassPass {
fn on_ty_class__bottom_up(&mut self, _: &Env, elem: &mut Class_) -> ControlFlow<()> {
if let Some(enum_) = &elem.enum_ {
let Id(pos, _) = &elem.name;
let enum_hint = Hint(
pos.clone(),
Box::new(Hint_::Happly(elem.name.clone(), vec![])),
);
let (cls_name, bounds) = match elem.kind {
ClassishKind::CenumClass(Abstraction::Concrete) => (
sn::classes::HH_BUILTIN_ENUM_CLASS,
vec![Hint(
pos.clone(),
Box::new(Hint_::Happly(
Id(pos.clone(), sn::classes::MEMBER_OF.to_string()),
vec![enum_hint, enum_.base.clone()],
)),
)],
),
ClassishKind::CenumClass(Abstraction::Abstract) => {
(sn::classes::HH_BUILTIN_ABSTRACT_ENUM_CLASS, vec![])
}
_ => (sn::classes::HH_BUILTIN_ENUM, vec![enum_hint]),
};
let extend_hint = Hint(
pos.clone(),
Box::new(Hint_::Happly(Id(pos.clone(), cls_name.to_string()), bounds)),
);
elem.extends.push(extend_hint)
}
Continue(())
}
fn on_ty_hint__bottom_up(&mut self, env: &Env, elem: &mut Hint_) -> ControlFlow<()> {
if !(env.is_hhi() || env.is_systemlib()) {
match elem {
Hint_::Happly(Id(pos, ty_name), _)
if ty_name == sn::classes::HH_BUILTIN_ENUM
|| ty_name == sn::classes::HH_BUILTIN_ENUM_CLASS
|| ty_name == sn::classes::HH_BUILTIN_ABSTRACT_ENUM_CLASS =>
{
env.emit_error(NamingError::UsingInternalClass {
pos: pos.clone(),
class_name: core_utils_rust::strip_ns(ty_name).to_string(),
})
}
_ => (),
}
}
Continue(())
}
fn on_ty_user_attributes_bottom_up(
&mut self,
env: &Env,
elem: &mut UserAttributes,
) -> ControlFlow<()> {
elem.iter_mut().for_each(|ua| {
let attr_name = ua.name.name();
if sn::user_attributes::MEMOIZE == attr_name
|| sn::user_attributes::MEMOIZE_LSB == attr_name
{
ua.params.iter_mut().for_each(|expr| {
if let Expr_::EnumClassLabel(box (cnm_opt, _)) = &mut expr.2 {
match &cnm_opt {
Some(id) => {
if id.name() != sn::hh::MEMOIZE_OPTION {
env.emit_error(NamingError::InvalidMemoizeLabel {
pos: id.pos().clone(),
attr_name: attr_name.to_string(),
})
}
}
None => {
// Elaborate.
*cnm_opt =
Some(Id(Pos::default(), sn::hh::MEMOIZE_OPTION.to_string()))
}
}
}
})
}
});
Continue(())
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use nast::Enum_;
use nast::Pos;
use nast::UserAttributes;
use oxidized::namespace_env;
use oxidized::s_map::SMap;
use super::*;
fn make_enum_class_(kind: ClassishKind, enum_: Enum_) -> Class_ {
Class_ {
span: Pos::NONE,
annotation: (),
mode: file_info::Mode::Mstrict,
final_: false,
is_xhp: false,
has_xhp_keyword: false,
kind,
name: Id(Pos::NONE, "Classy".to_string()),
tparams: vec![],
extends: vec![],
uses: vec![],
xhp_attr_uses: vec![],
xhp_category: None,
reqs: vec![],
implements: vec![],
where_constraints: vec![],
consts: vec![],
typeconsts: vec![],
vars: vec![],
methods: vec![],
xhp_children: vec![],
xhp_attrs: vec![],
namespace: Arc::new(namespace_env::Env {
ns_uses: SMap::default(),
class_uses: SMap::default(),
fun_uses: SMap::default(),
const_uses: SMap::default(),
name: None,
is_codegen: false,
disable_xhp_element_mangling: false,
}),
user_attributes: UserAttributes::default(),
file_attributes: vec![],
docs_url: None,
enum_: Some(enum_),
doc_comment: None,
emit_id: None,
internal: false,
module: None,
}
}
#[test]
fn test_enum_class_concrete() {
let env = Env::default();
let mut pass = ElabEnumClassPass;
let mut elem = make_enum_class_(
ClassishKind::CenumClass(Abstraction::Concrete),
Enum_ {
base: Hint(Pos::NONE, Box::new(Hint_::Herr)),
constraint: None,
includes: vec![],
},
);
elem.transform(&env, &mut pass);
let Hint(_, hint_) = &mut elem.extends.pop().unwrap();
assert!(match &mut **hint_ {
Hint_::Happly(Id(_, cname), bounds) => {
cname == sn::classes::HH_BUILTIN_ENUM_CLASS
&& bounds.pop().map_or(false, |Hint(_, hint_)| match *hint_ {
Hint_::Happly(Id(_, member_of), mut tparams) => {
(member_of == sn::classes::MEMBER_OF)
&& (tparams
.pop()
.map_or(false, |Hint(_, hint_)| matches!(*hint_, Hint_::Herr)))
&& (tparams.pop().map_or(false, |Hint(_, hint_)| {
matches!(*hint_, Hint_::Happly(..))
}))
}
_ => false,
})
}
_ => false,
})
}
#[test]
fn test_enum_class_abstract() {
let env = Env::default();
let mut pass = ElabEnumClassPass;
let mut elem = make_enum_class_(
ClassishKind::CenumClass(Abstraction::Abstract),
Enum_ {
base: Hint(Pos::NONE, Box::new(Hint_::Herr)),
constraint: None,
includes: vec![],
},
);
elem.transform(&env, &mut pass);
let Hint(_, hint_) = &mut elem.extends.pop().unwrap();
assert!(match &mut **hint_ {
Hint_::Happly(Id(_, cname), bounds) => {
cname == sn::classes::HH_BUILTIN_ABSTRACT_ENUM_CLASS && bounds.is_empty()
}
_ => false,
})
}
#[test]
fn test_enum() {
let env = Env::default();
let mut pass = ElabEnumClassPass;
let mut elem = make_enum_class_(
ClassishKind::Cenum,
Enum_ {
base: Hint(Pos::NONE, Box::new(Hint_::Herr)),
constraint: None,
includes: vec![],
},
);
elem.transform(&env, &mut pass);
let Hint(_, hint_) = &mut elem.extends.pop().unwrap();
assert!(match &mut **hint_ {
Hint_::Happly(Id(_, cname), bounds) => {
cname == sn::classes::HH_BUILTIN_ENUM
&& bounds
.pop()
.map_or(false, |Hint(_, hint_)| matches!(*hint_, Hint_::Happly(..)))
}
_ => false,
})
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/elab_everything_sdt.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 naming_special_names_rust as sn;
use nast::ClassConst;
use nast::Class_;
use nast::ConstraintKind;
use nast::Enum_;
use nast::Expr_;
use nast::FunDef;
use nast::HfParamInfo;
use nast::Hint;
use nast::Hint_;
use nast::Id;
use nast::Method_;
use nast::NastShapeInfo;
use nast::ParamKind;
use nast::Pos;
use nast::Tparam;
use nast::Typedef;
use nast::TypedefVisibility;
use nast::UserAttribute;
use nast::UserAttributes;
use crate::prelude::*;
#[derive(Clone, Default, Copy)]
pub struct ElabEverythingSdtPass {
in_is_as: bool,
in_enum_class: bool,
under_no_auto_dynamic: bool,
under_no_auto_likes: bool,
}
impl ElabEverythingSdtPass {
fn implicit_sdt(&self, env: &Env) -> bool {
env.everything_sdt() && !self.under_no_auto_dynamic
}
}
fn no_auto_dynamic(user_attributes: &UserAttributes) -> bool {
user_attributes
.iter()
.any(|ua| ua.name.name() == sn::user_attributes::NO_AUTO_DYNAMIC)
}
fn no_auto_likes(user_attributes: &UserAttributes) -> bool {
user_attributes
.iter()
.any(|ua| ua.name.name() == sn::user_attributes::NO_AUTO_LIKES)
}
fn no_auto_bound(user_attributes: &UserAttributes) -> bool {
user_attributes
.iter()
.any(|ua| ua.name.name() == sn::user_attributes::NO_AUTO_BOUND)
}
fn wrap_like(hint: Hint) -> Hint {
let Hint(ref p, _) = hint;
Hint(p.clone(), Box::new(Hint_::Hlike(hint)))
}
fn wrap_like_mut(hint: &mut Hint) {
// Steal the contents of `hint`.
let Hint(pos, hint_) = std::mem::replace(hint, elab_utils::hint::null());
// Make a new `Hint` from them wrapped in a `Hlike` and write the result
// back to `hint`.
*hint = wrap_like(Hint(pos, hint_));
}
fn wrap_supportdyn(Hint(pos, hint_): Hint) -> Hint {
let wrapped = Hint_::Happly(
Id(pos.clone(), sn::classes::SUPPORT_DYN.to_string()),
vec![Hint(pos.clone(), hint_)],
);
Hint(pos, Box::new(wrapped))
}
fn wrap_supportdyn_mut(hint: &mut Hint) {
// Steal the contents of `hint`.
let h = std::mem::replace(hint, elab_utils::hint::null());
// Wrap them in a `Happly(\\HH\\supportdyn, ...)`.
let wrapped = wrap_supportdyn(h);
// Write the result back into `hint`.
*hint = wrapped;
}
fn add_support_dynamic_type_attribute_mut(pos: Pos, user_attributes: &mut UserAttributes) {
// Push a "supports dynamic type" attribute on the front (the order
// probably doesn't matter but we do it this way to match OCaml).
user_attributes.insert(
0,
UserAttribute {
name: Id(pos, sn::user_attributes::SUPPORT_DYNAMIC_TYPE.to_string()),
params: vec![],
},
);
}
impl Pass for ElabEverythingSdtPass {
fn on_ty_fun_def_top_down(&mut self, _env: &Env, fd: &mut FunDef) -> ControlFlow<()> {
self.under_no_auto_dynamic = no_auto_dynamic(&fd.fun.user_attributes);
self.under_no_auto_likes = no_auto_likes(&fd.fun.user_attributes);
Continue(())
}
fn on_ty_class__top_down(&mut self, _env: &Env, class: &mut Class_) -> ControlFlow<()> {
self.in_enum_class = class.kind.is_cenum_class();
self.under_no_auto_dynamic = no_auto_dynamic(&class.user_attributes);
Continue(())
}
fn on_ty_method__top_down(&mut self, _env: &Env, method: &mut Method_) -> ControlFlow<()> {
self.under_no_auto_dynamic |= no_auto_dynamic(&method.user_attributes);
self.under_no_auto_likes = no_auto_likes(&method.user_attributes);
Continue(())
}
fn on_ty_expr__top_down(&mut self, _env: &Env, expr_: &mut Expr_) -> ControlFlow<()> {
self.in_is_as = matches!(expr_, Expr_::Is(_) | Expr_::As(_));
Continue(())
}
fn on_ty_typedef_top_down(&mut self, _env: &Env, typedef: &mut Typedef) -> ControlFlow<()> {
self.under_no_auto_dynamic = no_auto_dynamic(&typedef.user_attributes);
self.under_no_auto_likes = no_auto_likes(&typedef.user_attributes);
Continue(())
}
fn on_ty_hint_bottom_up(&mut self, env: &Env, hint: &mut Hint) -> ControlFlow<()> {
if !self.implicit_sdt(env) {
return Continue(());
}
match hint {
Hint(_, box (Hint_::Hmixed | Hint_::Hnonnull)) if !self.in_is_as => {
wrap_supportdyn_mut(hint);
}
Hint(
_,
box Hint_::Hshape(NastShapeInfo {
allows_unknown_fields: true,
..
}),
) => {
wrap_supportdyn_mut(hint);
}
// Return types and inout parameter types are pessimised.
Hint(_, box Hint_::Hfun(hint_fun)) if !self.under_no_auto_likes => {
for (p, ty) in std::iter::zip(&hint_fun.param_info, &mut hint_fun.param_tys) {
if matches!(
p,
Some(HfParamInfo {
kind: ParamKind::Pinout(_),
..
})
) {
wrap_like_mut(ty);
}
}
wrap_like_mut(&mut hint_fun.return_ty);
wrap_supportdyn_mut(hint);
}
_ => (),
}
Continue(())
}
fn on_ty_fun_def_bottom_up(&mut self, env: &Env, fd: &mut FunDef) -> ControlFlow<()> {
self.under_no_auto_dynamic = no_auto_dynamic(&fd.fun.user_attributes);
self.under_no_auto_likes = no_auto_likes(&fd.fun.user_attributes);
if !self.implicit_sdt(env) {
return Continue(());
}
add_support_dynamic_type_attribute_mut(fd.name.pos().clone(), &mut fd.fun.user_attributes);
Continue(())
}
fn on_ty_tparam_bottom_up(&mut self, env: &Env, tp: &mut Tparam) -> ControlFlow<()> {
if !self.implicit_sdt(env) || no_auto_bound(&tp.user_attributes) {
return Continue(());
}
// Push a "as supports dynamic mixed" constraint on the front of
// `tp.constraints` (the order probably doesn't matter but we do it this
// way to match OCaml).
tp.constraints.insert(
0,
(
ConstraintKind::ConstraintAs,
wrap_supportdyn(Hint(tp.name.pos().clone(), Box::new(Hint_::Hmixed))),
),
);
Continue(())
}
fn on_ty_class__bottom_up(&mut self, env: &Env, class: &mut Class_) -> ControlFlow<()> {
self.under_no_auto_dynamic = no_auto_dynamic(&class.user_attributes);
if !self.implicit_sdt(env) {
return Continue(());
}
let kind = &class.kind;
if kind.is_cclass() || kind.is_cinterface() || kind.is_ctrait() {
add_support_dynamic_type_attribute_mut(
class.name.pos().clone(),
&mut class.user_attributes,
);
}
Continue(())
}
fn on_fld_class__consts_bottom_up(
&mut self,
env: &Env,
consts: &mut Vec<ClassConst>,
) -> ControlFlow<()> {
if !env.everything_sdt() || !self.in_enum_class {
return Continue(());
}
for c in consts {
match &mut c.type_ {
Some(Hint(_, box Hint_::Happly(Id(_, c_member_of), hints)))
if c_member_of == sn::classes::MEMBER_OF
&& matches!(&hints[..], [Hint(_, box Hint_::Happly(_, _)), _]) =>
{
wrap_like_mut(&mut hints[1]);
hints[1].0 = hints[0].0.clone(); // Match OCaml.
}
_ => {}
}
}
Continue(())
}
fn on_ty_enum__bottom_up(&mut self, env: &Env, enum_: &mut Enum_) -> ControlFlow<()> {
if !env.everything_sdt() || !self.in_enum_class {
return Continue(());
}
wrap_like_mut(&mut enum_.base);
Continue(())
}
fn on_ty_typedef_bottom_up(&mut self, env: &Env, td: &mut Typedef) -> ControlFlow<()> {
self.under_no_auto_dynamic = no_auto_dynamic(&td.user_attributes);
self.under_no_auto_likes = no_auto_likes(&td.user_attributes);
if !self.implicit_sdt(env) {
return Continue(());
}
// If there isn't an "as constraint", and this is not just a type alias, produce a
// `Happly(\\HH\\supportdyn, Hmixed)` and write it into
// `td.as_constraint` in-place.
if td.as_constraint.is_none() && td.vis != TypedefVisibility::Transparent {
let pos = td.name.pos().clone();
td.as_constraint = Some(wrap_supportdyn(Hint(pos, Box::new(Hint_::Hmixed))));
}
Continue(())
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/elab_expr_call_call_user_func.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 nast::CallExpr;
use nast::Expr;
use nast::Expr_;
use nast::Id;
use nast::ParamKind;
use nast::Pos;
use crate::prelude::*;
#[derive(Clone, Copy, Default)]
pub struct ElabExprCallCallUserFuncPass;
impl Pass for ElabExprCallCallUserFuncPass {
fn on_ty_expr__bottom_up(&mut self, env: &Env, elem: &mut Expr_) -> ControlFlow<()> {
match elem {
Expr_::Call(box CallExpr {
func: Expr(_, fn_expr_pos, Expr_::Id(box Id(_, fn_name))),
args: fn_param_exprs,
..
}) if fn_name == sn::std_lib_functions::CALL_USER_FUNC && fn_param_exprs.is_empty() => {
// We're cloning here since we need to preserve the entire expression
env.emit_error(NamingError::DeprecatedUse {
pos: fn_expr_pos.clone(),
fn_name: fn_name.clone(),
});
env.emit_error(NamingError::TooFewArguments(fn_expr_pos.clone()));
let inner_expr_ = std::mem::replace(elem, Expr_::Null);
let inner_expr = elab_utils::expr::from_expr_(inner_expr_);
*elem = Expr_::Invalid(Box::new(Some(inner_expr)));
Break(())
}
Expr_::Call(box CallExpr {
func,
args,
unpacked_arg,
..
}) if is_expr_call_user_func(env, func) && !args.is_empty() => {
// remove the first element of `args`
let (param_kind, head_expr) = args.remove(0);
// raise an error if this is an inout param
if let ParamKind::Pinout(pk_pos) = ¶m_kind {
let pos = Pos::merge(pk_pos, &head_expr.1).unwrap();
env.emit_error(NastCheckError::InoutInTransformedPseudofunction {
pos,
fn_name: core_utils_rust::strip_ns(sn::std_lib_functions::CALL_USER_FUNC)
.to_string(),
})
}
// use the first argument as the function expression
*func = head_expr;
// TODO[mjt] why are we dropping the unpacked variadic arg here?
*unpacked_arg = None;
Continue(())
}
_ => Continue(()),
}
}
}
fn is_expr_call_user_func(env: &Env, expr: &Expr) -> bool {
match expr {
Expr(_, pos, Expr_::Id(box id)) if id.name() == sn::std_lib_functions::CALL_USER_FUNC => {
env.emit_error(NamingError::DeprecatedUse {
pos: pos.clone(),
fn_name: id.name().to_string(),
});
true
}
_ => false,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_valid() {
let env = Env::default();
let mut pass = ElabExprCallCallUserFuncPass;
let mut elem = Expr_::Call(Box::new(CallExpr {
func: Expr(
(),
elab_utils::pos::null(),
Expr_::Id(Box::new(Id(
elab_utils::pos::null(),
sn::std_lib_functions::CALL_USER_FUNC.to_string(),
))),
),
targs: vec![],
args: vec![(ParamKind::Pnormal, elab_utils::expr::null())],
unpacked_arg: None,
}));
elem.transform(&env, &mut pass);
// Expect one deprecation error in the valid case
let depr_err_opt = env.into_errors().pop();
assert!(matches!(
depr_err_opt,
Some(NamingPhaseError::Naming(NamingError::DeprecatedUse { .. }))
));
// Expect our parameter to be the call expression and the args to now
// be empty
assert!(match elem {
Expr_::Call(cc) => {
let CallExpr {
func: Expr(_, _, expr_),
args,
..
} = *cc;
matches!(expr_, Expr_::Null) && args.is_empty()
}
_ => false,
})
}
#[test]
fn test_no_args() {
let env = Env::default();
let mut pass = ElabExprCallCallUserFuncPass;
let mut elem = Expr_::Call(Box::new(CallExpr {
func: Expr(
(),
elab_utils::pos::null(),
Expr_::Id(Box::new(Id(
elab_utils::pos::null(),
sn::std_lib_functions::CALL_USER_FUNC.to_string(),
))),
),
targs: vec![],
args: vec![],
unpacked_arg: None,
}));
elem.transform(&env, &mut pass);
let mut errs = env.into_errors();
// Expect errors for too few args and deprecation
let too_few_args_err_opt = errs.pop();
assert!(matches!(
too_few_args_err_opt,
Some(NamingPhaseError::Naming(NamingError::TooFewArguments(_)))
));
let depr_err_opt = errs.pop();
assert!(matches!(
depr_err_opt,
Some(NamingPhaseError::Naming(NamingError::DeprecatedUse { .. }))
));
// Expect our original expression to be wrapped in `Invalid`
assert!(match elem {
Expr_::Invalid(expr) => {
if let Some(Expr(
_,
_,
Expr_::Call(box CallExpr {
func: Expr(_, _, Expr_::Id(id)),
..
}),
)) = *expr
{
id.name() == sn::std_lib_functions::CALL_USER_FUNC
} else {
false
}
}
_ => false,
})
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/elab_expr_call_hh_invariant.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 nast::Block;
use nast::CallExpr;
use nast::Expr;
use nast::Expr_;
use nast::Id;
use nast::ParamKind;
use nast::Pos;
use nast::Stmt;
use nast::Stmt_;
use nast::Uop;
use crate::prelude::*;
#[derive(Clone, Copy, Default)]
pub struct ElabExprCallHhInvariantPass;
impl Pass for ElabExprCallHhInvariantPass {
// We are elaborating a `Call` `Expr` into a `Stmt` so the transformation
// is defined on `Stmt`
fn on_ty_stmt__bottom_up(&mut self, env: &Env, elem: &mut Stmt_) -> ControlFlow<()> {
match check_call(env, elem) {
Check::Ignore => Continue(()),
Check::Invalidate => {
if let Stmt_::Expr(box expr) = elem {
let inner_expr = std::mem::replace(expr, elab_utils::expr::null());
*expr = elab_utils::expr::invalid(inner_expr);
}
Break(())
}
Check::Elaborate => {
let old_stmt_ = std::mem::replace(elem, Stmt_::Noop);
if let Stmt_::Expr(box Expr(
annot,
expr_pos,
Expr_::Call(box CallExpr {
func: Expr(fn_expr_annot, fn_expr_pos, Expr_::Id(box Id(fn_name_pos, _))),
targs,
mut args,
unpacked_arg,
}),
)) = old_stmt_
{
let (pk, arg) = args.remove(0);
// Raise error if this is an inout param
if let ParamKind::Pinout(ref pk_pos) = pk {
env.emit_error(NamingPhaseError::NastCheck(
NastCheckError::InoutInTransformedPseudofunction {
pos: Pos::merge(pk_pos, &fn_expr_pos).unwrap(),
fn_name: "invariant".to_string(),
},
))
}
// Construct a call to `invariant_violation` for the
// false case
let id_expr = Expr_::Id(Box::new(Id(
fn_name_pos,
sn::autoimported_functions::INVARIANT_VIOLATION.into(),
)));
let fn_expr = Expr(fn_expr_annot, fn_expr_pos, id_expr);
let violation_expr = Expr(
annot,
expr_pos.clone(),
Expr_::Call(Box::new(CallExpr {
func: fn_expr,
targs,
args,
unpacked_arg,
})),
);
// See if we have a bool constant as our condition; use the
// call to `invariant_violation` directly if we do and put
// into an `If` statement otherwise. Note that we put it
// on the true branch so the condition is negated.
match arg {
Expr(_, _, Expr_::False) => *elem = Stmt_::Expr(Box::new(violation_expr)),
Expr(cond_annot, cond_pos, cond_expr) => {
let true_block =
Block(vec![Stmt(expr_pos, Stmt_::Expr(Box::new(violation_expr)))]);
let false_block =
Block(vec![Stmt(elab_utils::pos::null(), Stmt_::Noop)]);
let cond_expr = Expr(
(),
cond_pos.clone(),
Expr_::Unop(Box::new((
Uop::Unot,
Expr(cond_annot, cond_pos, cond_expr),
))),
);
*elem = Stmt_::If(Box::new((cond_expr, true_block, false_block)))
}
}
}
Continue(())
}
}
}
}
enum Check {
Ignore,
Invalidate,
Elaborate,
}
fn check_call(env: &Env, stmt: &Stmt_) -> Check {
match stmt {
Stmt_::Expr(box Expr(
_,
_,
Expr_::Call(box CallExpr {
func: Expr(_, fn_expr_pos, Expr_::Id(box Id(_, fn_name))),
args,
..
}),
)) if fn_name == sn::autoimported_functions::INVARIANT => match args.get(0..1) {
None | Some(&[]) => {
env.emit_error(NamingPhaseError::Naming(NamingError::TooFewArguments(
fn_expr_pos.clone(),
)));
Check::Invalidate
}
Some(&[(ParamKind::Pnormal, _), ..]) => Check::Elaborate,
Some(&[(ParamKind::Pinout(ref pk_pos), _), ..]) => {
env.emit_error(NamingPhaseError::NastCheck(
NastCheckError::InoutInTransformedPseudofunction {
pos: Pos::merge(fn_expr_pos, pk_pos).unwrap(),
fn_name: "invariant".to_string(),
},
));
Check::Elaborate
}
},
_ => Check::Ignore,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_valid() {
let env = Env::default();
let mut pass = ElabExprCallHhInvariantPass;
let mut elem = Stmt_::Expr(Box::new(Expr(
(),
elab_utils::pos::null(),
Expr_::Call(Box::new(CallExpr {
func: Expr(
(),
elab_utils::pos::null(),
Expr_::Id(Box::new(Id(
elab_utils::pos::null(),
sn::autoimported_functions::INVARIANT.to_string(),
))),
),
targs: vec![],
args: vec![(ParamKind::Pnormal, elab_utils::expr::null())],
unpacked_arg: None,
})),
)));
elem.transform(&env, &mut pass);
assert!(env.into_errors().is_empty());
assert!(match elem {
Stmt_::If(box (
Expr(_, _, Expr_::Unop(box (Uop::Unot, Expr(_, _, Expr_::Null)))),
Block(mut ts),
Block(mut fs),
)) => {
match ts.pop().zip(fs.pop()) {
Some((
Stmt(
_,
Stmt_::Expr(box Expr(
_,
_,
Expr_::Call(box CallExpr {
func: Expr(_, _, Expr_::Id(box Id(_, fn_name))),
args,
..
}),
)),
),
Stmt(_, Stmt_::Noop),
)) => {
fn_name == sn::autoimported_functions::INVARIANT_VIOLATION
&& args.is_empty()
}
_ => false,
}
}
_ => false,
})
}
#[test]
fn test_valid_false() {
let env = Env::default();
let mut pass = ElabExprCallHhInvariantPass;
let mut elem = Stmt_::Expr(Box::new(Expr(
(),
elab_utils::pos::null(),
Expr_::Call(Box::new(CallExpr {
func: Expr(
(),
elab_utils::pos::null(),
Expr_::Id(Box::new(Id(
elab_utils::pos::null(),
sn::autoimported_functions::INVARIANT.to_string(),
))),
),
targs: vec![],
args: vec![(
ParamKind::Pnormal,
Expr((), elab_utils::pos::null(), Expr_::False),
)],
unpacked_arg: None,
})),
)));
elem.transform(&env, &mut pass);
assert!(env.into_errors().is_empty());
assert!(match elem {
Stmt_::Expr(box Expr(
_,
_,
Expr_::Call(box CallExpr {
func: Expr(_, _, Expr_::Id(box Id(_, fn_name))),
args,
..
}),
)) => fn_name == sn::autoimported_functions::INVARIANT_VIOLATION && args.is_empty(),
_ => false,
})
}
#[test]
fn test_too_few_args() {
let env = Env::default();
let mut pass = ElabExprCallHhInvariantPass;
let mut elem = Stmt_::Expr(Box::new(Expr(
(),
elab_utils::pos::null(),
Expr_::Call(Box::new(CallExpr {
func: Expr(
(),
elab_utils::pos::null(),
Expr_::Id(Box::new(Id(
elab_utils::pos::null(),
sn::autoimported_functions::INVARIANT.to_string(),
))),
),
targs: vec![],
args: vec![],
unpacked_arg: None,
})),
)));
elem.transform(&env, &mut pass);
let too_few_args_err_opt = env.into_errors().pop();
assert!(matches!(
too_few_args_err_opt,
Some(NamingPhaseError::Naming(NamingError::TooFewArguments(_)))
));
// Expect our original expression to be wrapped in `Invalid`
assert!(matches!(
elem,
Stmt_::Expr(box Expr(_, _, Expr_::Invalid(_)))
))
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/elab_expr_call_hh_meth_caller.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.
// 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::mem::take;
use nast::CallExpr;
use nast::ClassId;
use nast::ClassId_;
use nast::Expr;
use nast::Expr_;
use nast::Id;
use nast::ParamKind;
use crate::prelude::*;
#[derive(Clone, Copy, Default)]
pub struct ElabExprCallHhMethCallerPass;
impl Pass for ElabExprCallHhMethCallerPass {
fn on_ty_expr__bottom_up(&mut self, env: &Env, elem: &mut Expr_) -> ControlFlow<()> {
let invalid = |expr_: &mut Expr_| {
let inner_expr_ = std::mem::replace(expr_, Expr_::Null);
let inner_expr = elab_utils::expr::from_expr_(inner_expr_);
*expr_ = Expr_::Invalid(Box::new(Some(inner_expr)));
Break(())
};
match elem {
Expr_::Call(box CallExpr {
func: Expr(_, fn_expr_pos, Expr_::Id(box id)),
args: fn_param_exprs,
unpacked_arg: fn_variadic_param_opt,
..
}) if id.name() == sn::autoimported_functions::METH_CALLER => {
// Raise an error if we have a variadic arg
if let Some(Expr(_, pos, _)) = fn_variadic_param_opt {
env.emit_error(NamingError::TooFewArguments(pos.clone()))
}
match fn_param_exprs.as_mut_slice() {
[_, _, _, ..] => {
env.emit_error(NamingError::TooManyArguments(fn_expr_pos.clone()));
invalid(elem)
}
[
(ParamKind::Pnormal, Expr(_, rcvr_pos, rcvr)),
(ParamKind::Pnormal, Expr(_, meth_pos, Expr_::String(meth))),
] => match rcvr {
Expr_::String(rcvr) => {
*elem = Expr_::MethodCaller(Box::new((
Id(take(rcvr_pos), rcvr.to_string()),
(take(meth_pos), meth.to_string()),
)));
Continue(())
}
Expr_::ClassConst(box (ClassId(_, _, ClassId_::CI(id)), (_, mem)))
if mem == sn::members::M_CLASS =>
{
*elem = Expr_::MethodCaller(Box::new((
take(id),
(take(meth_pos), meth.to_string()),
)));
Continue(())
}
_ => {
env.emit_error(NamingError::IllegalMethCaller(fn_expr_pos.clone()));
invalid(elem)
}
},
// We expect a string literal as the second argument and neither param
// can be inout; raise an error and invalidate
[_, _] => {
env.emit_error(NamingError::IllegalMethCaller(fn_expr_pos.clone()));
invalid(elem)
}
// We are expecting exactly two args
[] | [_] => {
env.emit_error(NamingError::TooFewArguments(fn_expr_pos.clone()));
invalid(elem)
}
}
}
_ => Continue(()),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
// -- Valid cases resulting in elaboration to `MethodCaller` ---------------
#[test]
fn test_valid_two_string_args() {
let env = Env::default();
let mut pass = ElabExprCallHhMethCallerPass;
let rcvr_name = "wut";
let meth_name = "foo";
let mut elem = Expr_::Call(Box::new(CallExpr {
func: Expr(
(),
elab_utils::pos::null(),
Expr_::Id(Box::new(Id(
elab_utils::pos::null(),
sn::autoimported_functions::METH_CALLER.to_string(),
))),
),
targs: vec![],
args: vec![
(
ParamKind::Pnormal,
Expr((), elab_utils::pos::null(), Expr_::String(rcvr_name.into())),
),
(
ParamKind::Pnormal,
Expr((), elab_utils::pos::null(), Expr_::String(meth_name.into())),
),
],
unpacked_arg: None,
}));
elem.transform(&env, &mut pass);
// Expect no errors
assert!(env.into_errors().is_empty());
// Expect our `Expr_` to elaborate to a `MethodCaller`
assert!(match elem {
Expr_::MethodCaller(meth_caller) => {
let (Id(_, x), (_, y)) = *meth_caller;
x == rcvr_name && y == meth_name
}
_ => false,
})
}
#[test]
fn test_valid_class_const_string_args() {
let env = Env::default();
let mut pass = ElabExprCallHhMethCallerPass;
let rcvr_name = "wut";
let meth_name = "foo";
let mut elem = Expr_::Call(Box::new(CallExpr {
func: Expr(
(),
elab_utils::pos::null(),
Expr_::Id(Box::new(Id(
elab_utils::pos::null(),
sn::autoimported_functions::METH_CALLER.to_string(),
))),
),
targs: vec![],
args: vec![
(
ParamKind::Pnormal,
Expr(
(),
elab_utils::pos::null(),
Expr_::ClassConst(Box::new((
ClassId(
(),
elab_utils::pos::null(),
ClassId_::CI(Id(elab_utils::pos::null(), rcvr_name.into())),
),
(elab_utils::pos::null(), sn::members::M_CLASS.to_string()),
))),
),
),
(
ParamKind::Pnormal,
Expr((), elab_utils::pos::null(), Expr_::String(meth_name.into())),
),
],
unpacked_arg: None,
}));
elem.transform(&env, &mut pass);
// Expect no errors
assert!(env.into_errors().is_empty());
// Expect our `Expr_` to elaborate to a `MethodCaller`
assert!(match elem {
Expr_::MethodCaller(meth_caller) => {
let (Id(_, x), (_, y)) = *meth_caller;
x == rcvr_name && y == meth_name
}
_ => false,
})
}
#[test]
fn test_valid_with_variadic_arg() {
let env = Env::default();
let mut pass = ElabExprCallHhMethCallerPass;
let rcvr_name = "wut";
let meth_name = "foo";
let mut elem = Expr_::Call(Box::new(CallExpr {
func: Expr(
(),
elab_utils::pos::null(),
Expr_::Id(Box::new(Id(
elab_utils::pos::null(),
sn::autoimported_functions::METH_CALLER.to_string(),
))),
),
targs: vec![],
args: vec![
(
ParamKind::Pnormal,
Expr((), elab_utils::pos::null(), Expr_::String(rcvr_name.into())),
),
(
ParamKind::Pnormal,
Expr((), elab_utils::pos::null(), Expr_::String(meth_name.into())),
),
],
unpacked_arg: Some(elab_utils::expr::null()),
}));
elem.transform(&env, &mut pass);
// Expect `TooFewArgs` error from variadic param
let too_few_args_err_opt = env.into_errors().pop();
assert!(matches!(
too_few_args_err_opt,
Some(NamingPhaseError::Naming(NamingError::TooFewArguments(_)))
));
// Expect our `Expr_` to elaborate to a `MethodCaller`
assert!(match elem {
Expr_::MethodCaller(meth_caller) => {
let (Id(_, x), (_, y)) = *meth_caller;
x == rcvr_name && y == meth_name
}
_ => false,
})
}
// -- Invalid cases resulting in elaboration to `Invalid(Some(Call(..))` ---
#[test]
fn test_invalid_arg_type() {
let env = Env::default();
let mut pass = ElabExprCallHhMethCallerPass;
let meth_name = "foo";
let mut elem = Expr_::Call(Box::new(CallExpr {
func: Expr(
(),
elab_utils::pos::null(),
Expr_::Id(Box::new(Id(
elab_utils::pos::null(),
sn::autoimported_functions::METH_CALLER.to_string(),
))),
),
targs: vec![],
args: vec![
(
ParamKind::Pnormal,
Expr((), elab_utils::pos::null(), Expr_::Null),
),
(
ParamKind::Pnormal,
Expr((), elab_utils::pos::null(), Expr_::String(meth_name.into())),
),
],
unpacked_arg: None,
}));
elem.transform(&env, &mut pass);
let illegal_err_opt = env.into_errors().pop();
assert!(matches!(
illegal_err_opt,
Some(NamingPhaseError::Naming(NamingError::IllegalMethCaller(..)))
));
// Expect our original expression to be wrapped in `Invalid`
assert!(match elem {
Expr_::Invalid(expr) => {
if let Some(Expr(_, _, Expr_::Call(cc))) = *expr {
if let CallExpr {
func: Expr(_, _, Expr_::Id(id)),
..
} = *cc
{
let Id(_, nm) = *id;
nm == sn::autoimported_functions::METH_CALLER
} else {
false
}
} else {
false
}
}
_ => false,
})
}
#[test]
fn test_invalid_param_kind() {
let env = Env::default();
let mut pass = ElabExprCallHhMethCallerPass;
let rcvr_name = "wut";
let meth_name = "foo";
let mut elem = Expr_::Call(Box::new(CallExpr {
func: Expr(
(),
elab_utils::pos::null(),
Expr_::Id(Box::new(Id(
elab_utils::pos::null(),
sn::autoimported_functions::METH_CALLER.to_string(),
))),
),
targs: vec![],
args: vec![
(
ParamKind::Pnormal,
Expr((), elab_utils::pos::null(), Expr_::String(rcvr_name.into())),
),
(
ParamKind::Pinout(elab_utils::pos::null()),
Expr((), elab_utils::pos::null(), Expr_::String(meth_name.into())),
),
],
unpacked_arg: None,
}));
elem.transform(&env, &mut pass);
let illegal_err_opt = env.into_errors().pop();
assert!(matches!(
illegal_err_opt,
Some(NamingPhaseError::Naming(NamingError::IllegalMethCaller(..)))
));
// Expect our original expression to be wrapped in `Invalid`
assert!(match elem {
Expr_::Invalid(expr) => {
if let Some(Expr(_, _, Expr_::Call(cc))) = *expr {
if let CallExpr {
func: Expr(_, _, Expr_::Id(id)),
..
} = *cc
{
let Id(_, nm) = *id;
nm == sn::autoimported_functions::METH_CALLER
} else {
false
}
} else {
false
}
}
_ => false,
})
}
#[test]
fn test_too_few_args() {
let env = Env::default();
let mut pass = ElabExprCallHhMethCallerPass;
let rcvr_name = "wut";
let mut elem = Expr_::Call(Box::new(CallExpr {
func: Expr(
(),
elab_utils::pos::null(),
Expr_::Id(Box::new(Id(
elab_utils::pos::null(),
sn::autoimported_functions::METH_CALLER.to_string(),
))),
),
targs: vec![],
args: vec![(
ParamKind::Pnormal,
Expr((), elab_utils::pos::null(), Expr_::String(rcvr_name.into())),
)],
unpacked_arg: None,
}));
elem.transform(&env, &mut pass);
let too_few_args_err_opt = env.into_errors().pop();
assert!(matches!(
too_few_args_err_opt,
Some(NamingPhaseError::Naming(NamingError::TooFewArguments(_)))
));
// Expect our original expression to be wrapped in `Invalid`
assert!(match elem {
Expr_::Invalid(expr) => {
if let Some(Expr(_, _, Expr_::Call(cc))) = *expr {
if let CallExpr {
func: Expr(_, _, Expr_::Id(id)),
..
} = *cc
{
let Id(_, nm) = *id;
nm == sn::autoimported_functions::METH_CALLER
} else {
false
}
} else {
false
}
}
_ => false,
})
}
#[test]
fn test_too_many_args() {
let env = Env::default();
let mut pass = ElabExprCallHhMethCallerPass;
let rcvr_name = "wut";
let meth_name = "foo";
let mut elem = Expr_::Call(Box::new(CallExpr {
func: Expr(
(),
elab_utils::pos::null(),
Expr_::Id(Box::new(Id(
elab_utils::pos::null(),
sn::autoimported_functions::METH_CALLER.to_string(),
))),
),
targs: vec![],
args: vec![
(
ParamKind::Pnormal,
Expr((), elab_utils::pos::null(), Expr_::String(rcvr_name.into())),
),
(
ParamKind::Pnormal,
Expr((), elab_utils::pos::null(), Expr_::String(meth_name.into())),
),
(ParamKind::Pnormal, elab_utils::expr::null()),
],
unpacked_arg: None,
}));
elem.transform(&env, &mut pass);
let too_many_args_err_opt = env.into_errors().pop();
assert!(matches!(
too_many_args_err_opt,
Some(NamingPhaseError::Naming(NamingError::TooManyArguments(_)))
));
// Expect our original expression to be wrapped in `Invalid`
assert!(match elem {
Expr_::Invalid(expr) => {
if let Some(Expr(_, _, Expr_::Call(cc))) = *expr {
if let CallExpr {
func: Expr(_, _, Expr_::Id(id)),
..
} = *cc
{
let Id(_, nm) = *id;
nm == sn::autoimported_functions::METH_CALLER
} else {
false
}
} else {
false
}
}
_ => false,
})
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/elab_expr_collection.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 nast::Afield;
use nast::CollectionTarg;
use nast::Expr;
use nast::Expr_;
use nast::Field;
use nast::Hint;
use nast::Hint_;
use nast::Id;
use nast::KvcKind;
use nast::Lid;
use nast::Pos;
use nast::Targ;
use nast::VcKind;
use oxidized::local_id;
use crate::prelude::*;
#[derive(Clone, Copy, Default)]
pub struct ElabExprCollectionPass;
impl Pass for ElabExprCollectionPass {
/// Translate `Collection1 expressions received from lowering into
/// the canonical representation of either:
/// - `ValCollection` for `Keyset`, `Vec`, (`Imm`)`Vector`, (`Imm`)`Set`
/// - `KeyValCollection` for `Dict` and (`Imm`)`Map`
/// - `Pair` for `Pair`
///
/// If we have a collection with some other class name, we wrap in
/// the `Invalid` expression marker.
///
/// Elaboration into canonical representation may also reveal
/// errors in the explicit type arguments and the expressions
/// within the collection literal.
fn on_ty_expr_top_down(&mut self, env: &Env, elem: &mut Expr) -> ControlFlow<()> {
let Expr(_annot, _pos, expr_) = elem;
if let Expr_::Collection(c) = expr_ {
let (Id(pos, cname), ctarg_opt, afields) = c as &mut (_, _, Vec<Afield>);
match collection_kind(cname) {
CollectionKind::VcKind(vc_kind) => {
let targ_opt = targ_from_collection_targs(env, ctarg_opt, pos);
let exprs: Vec<Expr> = afields
.iter_mut()
.map(|afield| expr_from_afield(env, afield, cname))
.collect();
*expr_ = Expr_::ValCollection(Box::new((
(std::mem::replace(pos, Pos::NONE), vc_kind),
targ_opt,
exprs,
)));
Continue(())
}
CollectionKind::KvcKind(kvc_kind) => {
let targs_opt = targs_from_collection_targs(env, ctarg_opt, pos);
let fields: Vec<Field> = afields
.iter_mut()
.map(|afield| field_from_afield(env, afield, cname))
.collect();
*expr_ = Expr_::KeyValCollection(Box::new((
(std::mem::replace(pos, Pos::NONE), kvc_kind),
targs_opt,
fields,
)));
Continue(())
}
CollectionKind::Pair => {
match &mut (afields.pop(), afields.pop(), afields.pop()) {
// We have exactly two args so this _may_ be a valid pair
(Some(afield2), Some(afield1), None) => {
let targs_opt = targs_from_collection_targs(env, ctarg_opt, pos);
let expr1 = expr_from_afield(env, afield1, cname);
let expr2 = expr_from_afield(env, afield2, cname);
*expr_ = Expr_::Pair(Box::new((targs_opt, expr1, expr2)));
Continue(())
}
// We have fewer than two args, this cannot be a valid [Pair] so replace
// with [Invalid]
(_, None, _) => {
env.emit_error(NamingError::TooFewArguments(pos.clone()));
let inner_expr =
std::mem::replace(elem, Expr((), Pos::NONE, Expr_::Null));
*elem = Expr(
(),
inner_expr.1.clone(),
Expr_::Invalid(Box::new(Some(inner_expr))),
);
Break(())
}
// We have more than two args, this cannot be a valid `Pair` so replace
// with `Invalid`.
_ => {
env.emit_error(NamingError::TooManyArguments(pos.clone()));
let inner_expr =
std::mem::replace(elem, Expr((), Pos::NONE, Expr_::Null));
*elem = Expr(
(),
inner_expr.1.clone(),
Expr_::Invalid(Box::new(Some(inner_expr))),
);
Break(())
}
}
}
CollectionKind::NotACollection => {
env.emit_error(NamingError::ExpectedCollection {
pos: pos.clone(),
cname: cname.clone(),
});
let inner_expr = std::mem::replace(elem, Expr((), Pos::NONE, Expr_::Null));
let Expr(_, expr_pos, _) = &inner_expr;
*elem = Expr(
(),
expr_pos.clone(),
Expr_::Invalid(Box::new(Some(inner_expr))),
);
Break(())
}
}
} else {
Continue(())
}
}
}
/// Extract the expression from [AFvalue]s; if we encounter an [AFkvalue] we
/// raise an error and drop the value expression
fn expr_from_afield(env: &Env, afield: &mut Afield, cname: &str) -> Expr {
match afield {
Afield::AFvalue(e) => std::mem::replace(e, Expr((), Pos::NONE, Expr_::Null)),
Afield::AFkvalue(e, _) => {
let Expr(_, expr_pos, _) = &e;
env.emit_error(NamingError::UnexpectedArrow {
pos: expr_pos.clone(),
cname: cname.to_string(),
});
std::mem::replace(e, Expr((), Pos::NONE, Expr_::Null))
}
}
}
/// Extract the expressions from [AFkvalue]s into a `Field`; if we encounter an
/// `AFvalue` we raise an error and generate a synthetic lvar as the second
/// expression in the `Field`
fn field_from_afield(env: &Env, afield: &mut Afield, cname: &str) -> Field {
match afield {
Afield::AFkvalue(ek, ev) => {
let ek = std::mem::replace(ek, Expr((), Pos::NONE, Expr_::Null));
let ev = std::mem::replace(ev, Expr((), Pos::NONE, Expr_::Null));
Field(ek, ev)
}
Afield::AFvalue(e) => {
env.emit_error(NamingError::MissingArrow {
pos: e.1.clone(),
cname: cname.to_string(),
});
let ek = std::mem::replace(e, Expr((), Pos::NONE, Expr_::Null));
// TODO[mjt]: replace with `Invalid` expression?
let ev = Expr(
(),
Pos::NONE,
Expr_::Lvar(Box::new(Lid(
ek.1.clone(),
local_id::make_unscoped("__internal_placeholder"),
))),
);
Field(ek, ev)
}
}
}
// Get val collection hint if present; if we a keyval hint, raise an error and return `None`
fn targ_from_collection_targs(
env: &Env,
ctarg_opt: &mut Option<CollectionTarg>,
pos: &Pos,
) -> Option<Targ> {
if let Some(ctarg) = ctarg_opt {
match ctarg {
CollectionTarg::CollectionTV(tv) => {
let tv = std::mem::replace(tv, Targ((), Hint(Pos::NONE, Box::new(Hint_::Herr))));
Some(tv)
}
CollectionTarg::CollectionTKV(..) => {
env.emit_error(NamingError::TooManyArguments(pos.clone()));
None
}
}
} else {
None
}
}
// Get keyval collection hint if present; if we a val hint, raise an error and return `None`
fn targs_from_collection_targs(
env: &Env,
ctarg_opt: &mut Option<CollectionTarg>,
pos: &Pos,
) -> Option<(Targ, Targ)> {
if let Some(ctarg) = ctarg_opt {
match ctarg {
CollectionTarg::CollectionTKV(tk, tv) => {
let tk = std::mem::replace(tk, Targ((), Hint(Pos::NONE, Box::new(Hint_::Herr))));
let tv = std::mem::replace(tv, Targ((), Hint(Pos::NONE, Box::new(Hint_::Herr))));
Some((tk, tv))
}
CollectionTarg::CollectionTV(..) => {
env.emit_error(NamingError::TooFewArguments(pos.clone()));
None
}
}
} else {
None
}
}
enum CollectionKind {
VcKind(VcKind),
KvcKind(KvcKind),
Pair,
NotACollection,
}
// Determine the `CollectionKind` based on class name
fn collection_kind(name: &str) -> CollectionKind {
if let Some(kind) = vc_kind_opt(name) {
CollectionKind::VcKind(kind)
} else if let Some(kind) = kvc_kind_opt(name) {
CollectionKind::KvcKind(kind)
} else if name == sn::collections::PAIR {
CollectionKind::Pair
} else {
CollectionKind::NotACollection
}
}
fn kvc_kind_opt(name: &str) -> Option<KvcKind> {
match name {
sn::collections::MAP => Some(KvcKind::Map),
sn::collections::IMM_MAP => Some(KvcKind::ImmMap),
sn::collections::DICT => Some(KvcKind::Dict),
_ => None,
}
}
fn vc_kind_opt(name: &str) -> Option<VcKind> {
match name {
sn::collections::VECTOR => Some(VcKind::Vector),
sn::collections::IMM_VECTOR => Some(VcKind::ImmVector),
sn::collections::SET => Some(VcKind::Set),
sn::collections::IMM_SET => Some(VcKind::ImmSet),
sn::collections::KEYSET => Some(VcKind::Keyset),
sn::collections::VEC => Some(VcKind::Vec),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
// -- ValCollection --------------------------------------------------------
#[test]
fn test_val_collection_empty() {
let env = Env::default();
let mut pass = ElabExprCollectionPass;
let mut elem = Expr(
(),
Pos::NONE,
Expr_::Collection(Box::new((
Id(Pos::NONE, sn::collections::VEC.to_string()),
None,
vec![],
))),
);
elem.transform(&env, &mut pass);
let Expr(_, _, expr_) = elem;
assert_eq!(env.into_errors().len(), 0);
assert!(matches!(expr_, Expr_::ValCollection(_)));
}
#[test]
fn test_val_collection_afvalue() {
let env = Env::default();
let mut pass = ElabExprCollectionPass;
let mut elem = Expr(
(),
Pos::NONE,
Expr_::Collection(Box::new((
Id(Pos::NONE, sn::collections::VEC.to_string()),
None,
vec![Afield::AFvalue(Expr(
(),
Pos::NONE,
Expr_::Int("42".to_string()),
))],
))),
);
elem.transform(&env, &mut pass);
let Expr(_, _, expr_) = elem;
assert_eq!(env.into_errors().len(), 0);
assert!(matches!(expr_, Expr_::ValCollection(_)));
}
#[test]
fn test_val_collection_afkvalue() {
let env = Env::default();
let mut pass = ElabExprCollectionPass;
let mut elem = Expr(
(),
Pos::NONE,
Expr_::Collection(Box::new((
Id(Pos::NONE, sn::collections::VEC.to_string()),
None,
vec![Afield::AFkvalue(
Expr((), Pos::NONE, Expr_::Int("42".to_string())),
Expr((), Pos::NONE, Expr_::True),
)],
))),
);
elem.transform(&env, &mut pass);
let Expr(_, _, expr_) = elem;
assert!(matches!(
env.into_errors().pop(),
Some(NamingPhaseError::Naming(
NamingError::UnexpectedArrow { .. }
))
));
assert!(matches!(expr_, Expr_::ValCollection(_)));
}
#[test]
fn test_val_collection_val_arg() {
let env = Env::default();
let mut pass = ElabExprCollectionPass;
let mut elem = Expr(
(),
Pos::NONE,
Expr_::Collection(Box::new((
Id(Pos::NONE, sn::collections::VEC.to_string()),
Some(CollectionTarg::CollectionTV(Targ(
(),
Hint(Pos::NONE, Box::new(Hint_::Hnothing)),
))),
vec![],
))),
);
elem.transform(&env, &mut pass);
let Expr(_, _, expr_) = elem;
assert_eq!(env.into_errors().len(), 0);
assert!(matches!(expr_, Expr_::ValCollection(_)));
}
#[test]
fn test_val_collection_key_val_arg() {
let env = Env::default();
let mut pass = ElabExprCollectionPass;
let mut elem = Expr(
(),
Pos::NONE,
Expr_::Collection(Box::new((
Id(Pos::NONE, sn::collections::VEC.to_string()),
Some(CollectionTarg::CollectionTKV(
Targ((), Hint(Pos::NONE, Box::new(Hint_::Hnothing))),
Targ((), Hint(Pos::NONE, Box::new(Hint_::Hnothing))),
)),
vec![],
))),
);
elem.transform(&env, &mut pass);
let Expr(_, _, expr_) = elem;
assert!(matches!(
env.into_errors().pop(),
Some(NamingPhaseError::Naming(NamingError::TooManyArguments(_)))
));
assert!(match expr_ {
Expr_::ValCollection(b) => {
let (_, targ_opt, _) = *b;
targ_opt.is_none()
}
_ => false,
});
}
// -- KeyValCollection -----------------------------------------------------
#[test]
fn test_key_val_collection_empty() {
let env = Env::default();
let mut pass = ElabExprCollectionPass;
let mut elem = Expr(
(),
Pos::NONE,
Expr_::Collection(Box::new((
Id(Pos::NONE, sn::collections::DICT.to_string()),
None,
vec![],
))),
);
elem.transform(&env, &mut pass);
let Expr(_, _, expr_) = elem;
assert_eq!(env.into_errors().len(), 0);
assert!(matches!(expr_, Expr_::KeyValCollection(_)));
}
#[test]
fn test_key_val_collection_afvalue() {
let env = Env::default();
let mut pass = ElabExprCollectionPass;
let mut elem = Expr(
(),
Pos::NONE,
Expr_::Collection(Box::new((
Id(Pos::NONE, sn::collections::MAP.to_string()),
None,
vec![Afield::AFvalue(Expr(
(),
Pos::NONE,
Expr_::Int("42".to_string()),
))],
))),
);
elem.transform(&env, &mut pass);
let Expr(_, _, expr_) = elem;
assert!(matches!(
env.into_errors().pop(),
Some(NamingPhaseError::Naming(NamingError::MissingArrow { .. }))
));
assert!(matches!(expr_, Expr_::KeyValCollection(_)));
}
#[test]
fn test_key_val_collection_afkvalue() {
let env = Env::default();
let mut pass = ElabExprCollectionPass;
let mut elem = Expr(
(),
Pos::NONE,
Expr_::Collection(Box::new((
Id(Pos::NONE, sn::collections::MAP.to_string()),
None,
vec![Afield::AFkvalue(
Expr((), Pos::NONE, Expr_::Int("42".to_string())),
Expr((), Pos::NONE, Expr_::True),
)],
))),
);
elem.transform(&env, &mut pass);
let Expr(_, _, expr_) = elem;
assert_eq!(env.into_errors().len(), 0);
assert!(matches!(expr_, Expr_::KeyValCollection(_)));
}
#[test]
fn test_key_val_collection_val_arg() {
let env = Env::default();
let mut pass = ElabExprCollectionPass;
let mut elem = Expr(
(),
Pos::NONE,
Expr_::Collection(Box::new((
Id(Pos::NONE, sn::collections::MAP.to_string()),
Some(CollectionTarg::CollectionTV(Targ(
(),
Hint(Pos::NONE, Box::new(Hint_::Hnothing)),
))),
vec![],
))),
);
elem.transform(&env, &mut pass);
let Expr(_, _, expr_) = elem;
assert!(matches!(
env.into_errors().pop(),
Some(NamingPhaseError::Naming(NamingError::TooFewArguments(_)))
));
assert!(match expr_ {
Expr_::KeyValCollection(b) => {
let (_, targ_opt, _) = *b;
targ_opt.is_none()
}
_ => false,
});
}
#[test]
fn test_key_val_collection_key_val_arg() {
let env = Env::default();
let mut pass = ElabExprCollectionPass;
let mut elem = Expr(
(),
Pos::NONE,
Expr_::Collection(Box::new((
Id(Pos::NONE, sn::collections::MAP.to_string()),
Some(CollectionTarg::CollectionTKV(
Targ((), Hint(Pos::NONE, Box::new(Hint_::Hnothing))),
Targ((), Hint(Pos::NONE, Box::new(Hint_::Hnothing))),
)),
vec![],
))),
);
elem.transform(&env, &mut pass);
let Expr(_, _, expr_) = elem;
assert_eq!(env.into_errors().len(), 0);
assert!(matches!(expr_, Expr_::KeyValCollection(_)));
}
// -- Pair -----------------------------------------------------------------
#[test]
fn test_pair() {
let env = Env::default();
let mut pass = ElabExprCollectionPass;
let mut elem = Expr(
(),
Pos::NONE,
Expr_::Collection(Box::new((
Id(Pos::NONE, sn::collections::PAIR.to_string()),
None,
vec![
Afield::AFvalue(Expr((), Pos::NONE, Expr_::Int("42".to_string()))),
Afield::AFvalue(Expr((), Pos::NONE, Expr_::True)),
],
))),
);
elem.transform(&env, &mut pass);
let Expr(_, _, expr_) = elem;
assert_eq!(env.into_errors().len(), 0);
assert!(matches!(expr_, Expr_::Pair(_)));
}
#[test]
fn test_pair_too_few_exprs() {
let env = Env::default();
let mut pass = ElabExprCollectionPass;
let mut elem = Expr(
(),
Pos::NONE,
Expr_::Collection(Box::new((
Id(Pos::NONE, sn::collections::PAIR.to_string()),
None,
vec![Afield::AFvalue(Expr(
(),
Pos::NONE,
Expr_::Int("42".to_string()),
))],
))),
);
elem.transform(&env, &mut pass);
let Expr(_, _, expr_) = elem;
assert!(matches!(
env.into_errors().pop(),
Some(NamingPhaseError::Naming(NamingError::TooFewArguments(_)))
));
assert!(matches!(expr_, Expr_::Invalid(_)));
}
#[test]
fn test_pair_too_many_exprs() {
let env = Env::default();
let mut pass = ElabExprCollectionPass;
let mut elem = Expr(
(),
Pos::NONE,
Expr_::Collection(Box::new((
Id(Pos::NONE, sn::collections::PAIR.to_string()),
None,
vec![
Afield::AFvalue(Expr((), Pos::NONE, Expr_::Int("42".to_string()))),
Afield::AFvalue(Expr((), Pos::NONE, Expr_::True)),
Afield::AFvalue(Expr((), Pos::NONE, Expr_::Null)),
],
))),
);
elem.transform(&env, &mut pass);
let Expr(_, _, expr_) = elem;
assert!(matches!(
env.into_errors().pop(),
Some(NamingPhaseError::Naming(NamingError::TooManyArguments(_)))
));
assert!(matches!(expr_, Expr_::Invalid(_)));
}
#[test]
fn test_pair_val_arg() {
let env = Env::default();
let mut pass = ElabExprCollectionPass;
let mut elem = Expr(
(),
Pos::NONE,
Expr_::Collection(Box::new((
Id(Pos::NONE, sn::collections::PAIR.to_string()),
Some(CollectionTarg::CollectionTV(Targ(
(),
Hint(Pos::NONE, Box::new(Hint_::Hnothing)),
))),
vec![
Afield::AFvalue(Expr((), Pos::NONE, Expr_::Int("42".to_string()))),
Afield::AFvalue(Expr((), Pos::NONE, Expr_::True)),
],
))),
);
elem.transform(&env, &mut pass);
let Expr(_, _, expr_) = elem;
assert!(matches!(
env.into_errors().pop(),
Some(NamingPhaseError::Naming(NamingError::TooFewArguments(_)))
));
assert!(match expr_ {
Expr_::Pair(b) => {
let (targ_opt, _, _) = *b;
targ_opt.is_none()
}
_ => false,
});
}
#[test]
fn test_pair_key_val_arg() {
let env = Env::default();
let mut pass = ElabExprCollectionPass;
let mut elem = Expr(
(),
Pos::NONE,
Expr_::Collection(Box::new((
Id(Pos::NONE, sn::collections::PAIR.to_string()),
Some(CollectionTarg::CollectionTKV(
Targ((), Hint(Pos::NONE, Box::new(Hint_::Hnothing))),
Targ((), Hint(Pos::NONE, Box::new(Hint_::Hnothing))),
)),
vec![
Afield::AFvalue(Expr((), Pos::NONE, Expr_::Int("42".to_string()))),
Afield::AFvalue(Expr((), Pos::NONE, Expr_::True)),
],
))),
);
elem.transform(&env, &mut pass);
let Expr(_, _, expr_) = elem;
assert_eq!(env.into_errors().len(), 0);
assert!(matches!(expr_, Expr_::Pair(_)));
}
// -- Not a collection -----------------------------------------------------
#[test]
fn test_not_a_collection() {
let env = Env::default();
let mut pass = ElabExprCollectionPass;
let mut elem = Expr(
(),
Pos::NONE,
Expr_::Collection(Box::new((
Id(Pos::NONE, sn::classes::DATE_TIME.to_string()),
None,
vec![],
))),
);
elem.transform(&env, &mut pass);
let Expr(_, _, expr_) = elem;
assert!(matches!(
env.into_errors().pop(),
Some(NamingPhaseError::Naming(
NamingError::ExpectedCollection { .. }
))
));
assert!(matches!(expr_, Expr_::Invalid(_)));
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/elab_expr_import.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 nast::Expr;
use nast::Expr_;
use nast::Pos;
use crate::prelude::*;
#[derive(Clone, Copy, Default)]
pub struct ElabExprImportPass;
impl Pass for ElabExprImportPass {
// Wrap all occurrence of `Import` in an `Invalid` marker
// TODO[mjt] Oddly there is no error reporting about the occurrence of these
// expressions and no invariant is assumed. I would expect one of these
fn on_ty_expr_top_down(&mut self, _: &Env, elem: &mut Expr) -> ControlFlow<()> {
let Expr(_, _, expr_) = elem;
match expr_ {
Expr_::Import(_) => {
let inner_expr = std::mem::replace(elem, Expr((), Pos::NONE, Expr_::Null));
*elem = Expr(
(),
inner_expr.1.clone(),
Expr_::Invalid(Box::new(Some(inner_expr))),
);
Break(())
}
_ => Continue(()),
}
}
}
#[cfg(test)]
mod tests {
use nast::ImportFlavor;
use super::*;
// -- ValCollection --------------------------------------------------------
#[test]
fn test_val_collection_empty() {
let env = Env::default();
let mut pass = ElabExprImportPass;
let mut elem: Expr = Expr(
(),
Pos::NONE,
Expr_::Import(Box::new((
ImportFlavor::Include,
Expr((), Pos::NONE, Expr_::Null),
))),
);
elem.transform(&env, &mut pass);
let Expr(_, _, expr_) = elem;
assert!(matches!(expr_, Expr_::Invalid(_)));
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/elab_expr_lvar.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 nast::Expr_;
use nast::Lid;
use nast::Pos;
use oxidized::local_id;
use crate::prelude::*;
#[derive(Clone, Copy, Default)]
pub struct ElabExprLvarPass;
impl Pass for ElabExprLvarPass {
fn on_ty_expr__top_down(&mut self, _: &Env, elem: &mut Expr_) -> ControlFlow<()> {
match elem {
Expr_::Lvar(lid) => {
let Lid(pos, lcl_id) = lid as &mut Lid;
let lcl_id_str = local_id::get_name(lcl_id);
if lcl_id_str == sn::special_idents::THIS {
*elem = Expr_::This;
} else if lcl_id_str == sn::special_idents::DOLLAR_DOLLAR {
let pos = std::mem::replace(pos, Pos::NONE);
*elem = Expr_::Dollardollar(Box::new(Lid(
pos,
local_id::make_unscoped(sn::special_idents::DOLLAR_DOLLAR),
)));
} else if lcl_id_str == sn::special_idents::PLACEHOLDER {
let pos = std::mem::replace(pos, Pos::NONE);
*elem = Expr_::Lplaceholder(Box::new(pos));
}
Continue(())
}
Expr_::Pipe(pipe) => {
let (Lid(_, lcl_id), _, _) = pipe as &mut (Lid, _, _);
*lcl_id = local_id::make_unscoped(sn::special_idents::DOLLAR_DOLLAR);
Continue(())
}
_ => Continue(()),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_lvar_this() {
let env = Env::default();
let mut pass = ElabExprLvarPass;
let mut elem = Expr_::Lvar(Box::new(Lid(
Pos::NONE,
local_id::make_unscoped(sn::special_idents::THIS),
)));
elem.transform(&env, &mut pass);
assert!(matches!(elem, Expr_::This))
}
#[test]
fn test_lvar_placeholder() {
let env = Env::default();
let mut pass = ElabExprLvarPass;
let mut elem = Expr_::Lvar(Box::new(Lid(
Pos::NONE,
local_id::make_unscoped(sn::special_idents::PLACEHOLDER),
)));
elem.transform(&env, &mut pass);
assert!(matches!(elem, Expr_::Lplaceholder(_)))
}
#[test]
fn test_lvar_dollar_dollar() {
let env = Env::default();
let mut pass = ElabExprLvarPass;
let mut elem = Expr_::Lvar(Box::new(Lid(
Pos::NONE,
local_id::make_unscoped(sn::special_idents::DOLLAR_DOLLAR),
)));
elem.transform(&env, &mut pass);
assert!(matches!(elem, Expr_::Dollardollar(_)))
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/elab_expr_package.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 naming_special_names_rust::pseudo_functions;
use nast::CallExpr;
use nast::Expr;
use nast::Expr_;
use nast::Id;
use nast::ParamKind;
use crate::prelude::*;
#[derive(Clone, Copy, Default)]
pub struct ElabExprPackagePass;
impl Pass for ElabExprPackagePass {
fn on_ty_expr_top_down(&mut self, _: &Env, elem: &mut Expr) -> ControlFlow<()> {
let Expr(_, pos, expr) = elem;
match expr {
Expr_::Package(box pkg) => {
*expr = Expr_::Call(Box::new(CallExpr {
func: Expr::new(
(),
pos.clone(),
Expr_::mk_id(Id(pos.clone(), pseudo_functions::PACKAGE_EXISTS.into())),
),
targs: vec![],
args: vec![(
ParamKind::Pnormal,
Expr::new((), pkg.pos().clone(), Expr_::mk_string(pkg.name().into())),
)],
unpacked_arg: None,
}));
Break(())
}
_ => Continue(()),
}
}
}
#[cfg(test)]
mod tests {
use nast::Id;
use nast::Pos;
use super::*;
#[test]
fn test() {
let env = Env::default();
let mut pass = ElabExprPackagePass;
let mut elem: Expr = Expr(
(),
Pos::NONE,
Expr_::Package(Box::new(Id(Pos::NONE, "foo".into()))),
);
elem.transform(&env, &mut pass);
let Expr(_, _, expr) = elem;
assert!(match expr {
Expr_::Call(box CallExpr {
func: Expr(_, _, Expr_::Id(box Id(_, fn_name))),
args,
..
}) if fn_name == pseudo_functions::PACKAGE_EXISTS => {
if let [(ParamKind::Pnormal, Expr(_, _, Expr_::String(fn_param_name)))] = &args[..]
{
fn_param_name == "foo"
} else {
false
}
}
_ => false,
});
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/elab_expr_tuple.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 nast::Expr;
use nast::Expr_;
use crate::prelude::*;
/// Replace empty tuples with invalid expressions and record errors.
#[derive(Clone, Copy, Default)]
pub struct ElabExprTuplePass;
impl Pass for ElabExprTuplePass {
fn on_ty_expr_top_down(&mut self, env: &Env, elem: &mut Expr) -> ControlFlow<()> {
if let Expr(_annot, pos, Expr_::Tuple(es)) = elem {
if es.is_empty() {
// Loc. of the empty tuple.
let pos = pos.clone();
// Steal the contents of `elem`.
let expr = std::mem::replace(elem, elab_utils::expr::null());
// Wrap them in `Invalid` and install the result back into
// `elem`.
*elem = elab_utils::expr::invalid(expr);
// Record the error and break.
env.emit_error(NamingError::TooFewArguments(pos));
return Break(());
}
}
Continue(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_empty_tuple() {
let env = Env::default();
let mut pass = ElabExprTuplePass;
let mut elem = elab_utils::expr::from_expr_(Expr_::Tuple(vec![]));
elem.transform(&env, &mut pass);
assert!(matches!(elem, Expr(_, _, Expr_::Invalid(_))));
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/elab_func_body.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 nast::Class_;
use nast::FunDef;
use nast::FuncBody;
use nast::Gconst;
use nast::ModuleDef;
use nast::Typedef;
use crate::prelude::*;
#[derive(Clone, Copy)]
pub struct ElabFuncBodyPass {
mode: file_info::Mode,
}
impl Default for ElabFuncBodyPass {
fn default() -> Self {
ElabFuncBodyPass {
mode: file_info::Mode::Mstrict,
}
}
}
impl Pass for ElabFuncBodyPass {
fn on_ty_func_body_top_down(&mut self, _: &Env, elem: &mut FuncBody) -> ControlFlow<()> {
if matches!(self.mode, file_info::Mode::Mhhi) {
elem.fb_ast.clear()
}
Continue(())
}
fn on_ty_class__top_down(&mut self, _: &Env, elem: &mut Class_) -> ControlFlow<()> {
self.mode = elem.mode;
Continue(())
}
fn on_ty_typedef_top_down(&mut self, _: &Env, elem: &mut Typedef) -> ControlFlow<()> {
self.mode = elem.mode;
Continue(())
}
fn on_ty_gconst_top_down(&mut self, _: &Env, elem: &mut Gconst) -> ControlFlow<()> {
self.mode = elem.mode;
Continue(())
}
fn on_ty_fun_def_top_down(&mut self, _: &Env, elem: &mut FunDef) -> ControlFlow<()> {
self.mode = elem.mode;
Continue(())
}
fn on_ty_module_def_top_down(&mut self, _: &Env, elem: &mut ModuleDef) -> ControlFlow<()> {
self.mode = elem.mode;
Continue(())
}
}
#[cfg(test)]
mod tests {
use nast::FuncBody;
use nast::Pos;
use nast::Stmt;
use nast::Stmt_;
use super::*;
#[test]
fn test_add() {
let env = Env::default();
let mut elem = FuncBody {
fb_ast: nast::Block(vec![Stmt(Pos::NONE, Stmt_::Noop)]),
};
let mut pass = ElabFuncBodyPass::default();
// Transform when not in Mode::Mhhi should be unchanged
elem.transform(&env, &mut pass);
assert!(!elem.fb_ast.is_empty());
// Transform when in Mode::Mhhi should result in [fb_ast] being cleared
pass.mode = file_info::Mode::Mhhi;
elem.transform(&env, &mut pass);
assert!(elem.fb_ast.is_empty());
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/elab_hint_haccess.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 bitflags::bitflags;
use nast::Class_;
use nast::Contexts;
use nast::Hint;
use nast::Hint_;
use nast::Id;
use nast::WhereConstraintHint;
use crate::prelude::*;
#[derive(Clone, Default)]
pub struct ElabHintHaccessPass {
current_class: Option<Rc<Id>>,
flags: Flags,
}
bitflags! {
#[derive(Default)]
struct Flags: u8 {
const IN_CONTEXT = 1 << 0;
const IN_HACCESS = 1 << 1;
const IN_WHERE_CLAUSE = 1 << 2;
}
}
impl ElabHintHaccessPass {
fn set_in_class(&mut self, cls: &Class_) {
self.current_class = Some(Rc::new(cls.name.clone()))
}
fn in_context(&self) -> bool {
self.flags.contains(Flags::IN_CONTEXT)
}
fn set_in_context(&mut self, value: bool) {
self.flags.set(Flags::IN_CONTEXT, value)
}
fn in_haccess(&self) -> bool {
self.flags.contains(Flags::IN_HACCESS)
}
fn set_in_haccess(&mut self, value: bool) {
self.flags.set(Flags::IN_HACCESS, value)
}
fn in_where_clause(&self) -> bool {
self.flags.contains(Flags::IN_WHERE_CLAUSE)
}
fn set_in_where_clause(&mut self, value: bool) {
self.flags.set(Flags::IN_WHERE_CLAUSE, value)
}
}
impl Pass for ElabHintHaccessPass {
fn on_ty_hint_top_down(&mut self, env: &Env, elem: &mut Hint) -> ControlFlow<()> {
if !self.in_haccess() {
return Continue(());
}
match &mut *elem.1 {
Hint_::Happly(id, hints) if id.name() == sn::classes::SELF => {
if let Some(class_id) = self.current_class.as_deref() {
*id = class_id.clone();
// TODO[mjt] we appear to be discarding type arguments on `Happly` here?
hints.clear();
Continue(())
} else {
env.emit_error(NamingError::SelfOutsideClass(id.0.clone()));
*elem.1 = Hint_::Herr;
Break(())
}
}
Hint_::Happly(id, _)
if id.name() == sn::classes::STATIC || id.name() == sn::classes::PARENT =>
{
env.emit_error(NamingError::InvalidTypeAccessRoot {
pos: id.pos().clone(),
id: Some(id.name().to_string()),
});
*elem.1 = Hint_::Herr;
Break(())
}
Hint_::Hthis | Hint_::Happly(..) => Continue(()),
Hint_::Habstr(..) if self.in_where_clause() || self.in_context() => Continue(()),
// TODO[mjt] I don't understand what this case corresponds to
Hint_::Hvar(..) => Continue(()),
_ => {
env.emit_error(NamingError::InvalidTypeAccessRoot {
pos: elem.0.clone(),
id: None,
});
*elem.1 = Hint_::Herr;
Break(())
}
}
}
fn on_ty_hint__top_down(&mut self, _: &Env, elem: &mut Hint_) -> ControlFlow<()> {
self.set_in_haccess(matches!(elem, Hint_::Haccess(..)));
Continue(())
}
fn on_ty_class__top_down(&mut self, _: &Env, elem: &mut Class_) -> ControlFlow<()> {
self.set_in_class(elem);
Continue(())
}
fn on_ty_where_constraint_hint_top_down(
&mut self,
_: &Env,
_: &mut WhereConstraintHint,
) -> ControlFlow<()> {
self.set_in_where_clause(true);
Continue(())
}
fn on_ty_contexts_top_down(&mut self, _: &Env, _: &mut Contexts) -> ControlFlow<()> {
self.set_in_context(true);
Continue(())
}
}
#[cfg(test)]
mod tests {
use nast::ConstraintKind;
use nast::Id;
use nast::Pos;
use super::*;
// -- type access through `self` -------------------------------------------
#[test]
// type access through `self` is valid inside a class
fn test_haccess_self_in_class_valid() {
let env = Env::default();
let class_name = "Classy";
let mut pass = ElabHintHaccessPass {
current_class: Some(Rc::new(Id(Default::default(), "Classy".to_string()))),
..Default::default()
};
let mut elem = Hint(
Pos::default(),
Box::new(Hint_::Haccess(
Hint(
Pos::default(),
Box::new(Hint_::Happly(
Id(Pos::default(), sn::classes::SELF.to_string()),
vec![],
)),
),
vec![Id(Pos::default(), "T".to_string())],
)),
);
elem.transform(&env, &mut pass);
assert!(env.into_errors().is_empty());
assert!(match elem {
Hint(_, box Hint_::Haccess(Hint(_, box Hint_::Happly(id, hints)), _)) =>
id.name() == class_name && hints.is_empty(),
_ => false,
})
}
#[test]
// currently we erase any type params to which `self` is applied; adding
// test for tracking
fn test_haccess_self_in_class_erased_tparams_valid() {
let env = Env::default();
let class_name = "Classy";
let mut pass = ElabHintHaccessPass {
current_class: Some(Rc::new(Id(Default::default(), "Classy".to_string()))),
..Default::default()
};
let mut elem = Hint(
Pos::default(),
Box::new(Hint_::Haccess(
Hint(
Pos::default(),
Box::new(Hint_::Happly(
Id(Pos::default(), sn::classes::SELF.to_string()),
vec![Hint(Pos::default(), Box::new(Hint_::Herr))],
)),
),
vec![Id(Pos::default(), "T".to_string())],
)),
);
elem.transform(&env, &mut pass);
assert!(env.into_errors().is_empty());
assert!(match elem {
Hint(_, box Hint_::Haccess(Hint(_, box Hint_::Happly(id, hints)), _)) =>
id.name() == class_name && hints.is_empty(),
_ => false,
})
}
#[test]
// type access through `self` is invalid outside a class
fn test_haccess_self_outside_class_invalid() {
let env = Env::default();
let mut pass = ElabHintHaccessPass::default();
let mut elem = Hint(
Pos::default(),
Box::new(Hint_::Haccess(
Hint(
Pos::default(),
Box::new(Hint_::Happly(
Id(Pos::default(), sn::classes::SELF.to_string()),
vec![],
)),
),
vec![Id(Pos::default(), "T".to_string())],
)),
);
elem.transform(&env, &mut pass);
let err_opt = env.into_errors().pop();
assert!(matches!(
err_opt,
Some(NamingPhaseError::Naming(NamingError::SelfOutsideClass(..)))
));
assert!(matches!(
elem,
Hint(_, box Hint_::Haccess(Hint(_, box Hint_::Herr), _))
))
}
// -- type access through `this` -------------------------------------------
#[test]
// type access through `this` is always valid
fn test_haccess_this_valid() {
let env = Env::default();
let mut pass = ElabHintHaccessPass::default();
let mut elem = Hint(
Pos::default(),
Box::new(Hint_::Haccess(
Hint(Pos::default(), Box::new(Hint_::Hthis)),
vec![Id(Pos::default(), "T".to_string())],
)),
);
elem.transform(&env, &mut pass);
assert!(env.into_errors().is_empty());
assert!(matches!(
elem,
Hint(_, box Hint_::Haccess(Hint(_, box Hint_::Hthis), _))
))
}
// -- type access through `static` / `parent` ------------------------------
#[test]
// type access through `static` is invalid
fn test_haccess_static_in_class_invalid() {
let env = Env::default();
let mut pass = ElabHintHaccessPass {
current_class: Some(Rc::new(Id(Default::default(), "Classy".to_string()))),
..Default::default()
};
let mut elem = Hint(
Pos::default(),
Box::new(Hint_::Haccess(
Hint(
Pos::default(),
Box::new(Hint_::Happly(
Id(Pos::default(), sn::classes::STATIC.to_string()),
vec![],
)),
),
vec![Id(Pos::default(), "T".to_string())],
)),
);
elem.transform(&env, &mut pass);
let err_opt = env.into_errors().pop();
assert!(matches!(
err_opt,
Some(NamingPhaseError::Naming(
NamingError::InvalidTypeAccessRoot { .. }
))
));
assert!(matches!(
elem,
Hint(_, box Hint_::Haccess(Hint(_, box Hint_::Herr), _))
))
}
// -- type access through type param ---------------------------------------
#[test]
// type access through type parameter is valid inside a context
fn test_haccess_tparam_in_context_valid() {
let env = Env::default();
let mut pass = ElabHintHaccessPass::default();
let mut elem = Contexts(
Pos::default(),
vec![Hint(
Pos::default(),
Box::new(Hint_::Haccess(
Hint(
Pos::default(),
Box::new(Hint_::Habstr("T".to_string(), vec![])),
),
vec![Id(Pos::default(), "C".to_string())],
)),
)],
);
elem.transform(&env, &mut pass);
assert!(env.into_errors().is_empty());
let Contexts(_, mut hints) = elem;
assert!(matches!(
hints.pop(),
Some(Hint(_, box Hint_::Haccess(Hint(_, box Hint_::Habstr(..)), _)))
))
}
#[test]
// type access through type parameter is valid inside a where clause
fn test_haccess_tparam_in_where_clause_valid() {
let env = Env::default();
let mut pass = ElabHintHaccessPass::default();
let mut elem = WhereConstraintHint(
Hint(
Pos::default(),
Box::new(Hint_::Haccess(
Hint(
Pos::default(),
Box::new(Hint_::Habstr("T".to_string(), vec![])),
),
vec![Id(Pos::default(), "C".to_string())],
)),
),
ConstraintKind::ConstraintSuper,
Hint(Pos::default(), Box::new(Hint_::Herr)),
);
elem.transform(&env, &mut pass);
assert!(env.into_errors().is_empty());
let WhereConstraintHint(hint, _, _) = elem;
assert!(matches!(
hint,
Hint(_, box Hint_::Haccess(Hint(_, box Hint_::Habstr(..)), _))
))
}
#[test]
// type access through type parameter in any other context is invalid
fn test_haccess_tparam_invalid() {
let env = Env::default();
let mut pass = ElabHintHaccessPass::default();
let mut elem = Hint(
Pos::default(),
Box::new(Hint_::Haccess(
Hint(
Pos::default(),
Box::new(Hint_::Habstr("T".to_string(), vec![])),
),
vec![Id(Pos::default(), "C".to_string())],
)),
);
elem.transform(&env, &mut pass);
let err_opt = env.into_errors().pop();
assert!(matches!(
err_opt,
Some(NamingPhaseError::Naming(
NamingError::InvalidTypeAccessRoot { .. }
))
));
assert!(matches!(
elem,
Hint(_, box Hint_::Haccess(Hint(_, box Hint_::Herr), _))
))
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/elab_hint_happly.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 hash::HashSet;
use nast::Class_;
use nast::FunDef;
use nast::Gconst;
use nast::Hint;
use nast::Hint_;
use nast::Id;
use nast::Method_;
use nast::ModuleDef;
use nast::Pos;
use nast::Tparam;
use nast::Tprim;
use nast::Typedef;
use crate::prelude::*;
#[derive(Clone, Default)]
pub struct ElabHintHapplyPass {
tparams: Rc<HashSet<String>>,
}
impl ElabHintHapplyPass {
pub fn extend_tparams(&mut self, tps: &[Tparam]) {
let tparams = Rc::make_mut(&mut self.tparams);
tps.iter().for_each(|tparam| {
tparams.insert(tparam.name.1.clone());
})
}
pub fn reset_tparams(&mut self) {
Rc::make_mut(&mut self.tparams).clear()
}
pub fn set_tparams(&mut self, tps: &[Tparam]) {
self.reset_tparams();
self.extend_tparams(tps);
}
pub fn tparams(&self) -> &HashSet<String> {
&self.tparams
}
}
impl Pass for ElabHintHapplyPass {
// We can't write this - how can we make the contexts modular?
// type Ctx = impl CanonicalHapplyCtx;
fn on_ty_typedef_top_down(&mut self, _: &Env, elem: &mut Typedef) -> ControlFlow<()> {
self.set_tparams(&elem.tparams);
Continue(())
}
fn on_ty_gconst_top_down(&mut self, _: &Env, _: &mut Gconst) -> ControlFlow<()> {
self.reset_tparams();
Continue(())
}
fn on_ty_fun_def_top_down(&mut self, _: &Env, elem: &mut FunDef) -> ControlFlow<()> {
self.set_tparams(&elem.tparams);
Continue(())
}
fn on_ty_module_def_top_down(&mut self, _: &Env, _: &mut ModuleDef) -> ControlFlow<()> {
self.reset_tparams();
Continue(())
}
fn on_ty_class__top_down(&mut self, _: &Env, elem: &mut Class_) -> ControlFlow<()> {
self.set_tparams(&elem.tparams);
Continue(())
}
fn on_ty_method__top_down(&mut self, _: &Env, elem: &mut Method_) -> ControlFlow<()> {
self.extend_tparams(&elem.tparams);
Continue(())
}
fn on_ty_tparam_top_down(&mut self, _: &Env, elem: &mut Tparam) -> ControlFlow<()> {
self.extend_tparams(&elem.parameters);
Continue(())
}
fn on_ty_hint_top_down(&mut self, env: &Env, elem: &mut Hint) -> ControlFlow<()> {
match &mut *elem.1 {
Hint_::Happly(id, hints) => {
match canonical_happly(&elem.0, id, hints, self.tparams()) {
Continue((hint_opt, err_opt)) => {
if let Some(hint_) = hint_opt {
*elem.1 = hint_
}
if let Some(err) = err_opt {
env.emit_error(err)
}
Continue(())
}
Break((hint_opt, err)) => {
if let Some(hint_) = hint_opt {
*elem.1 = hint_
}
env.emit_error(err);
Break(())
}
}
}
_ => Continue(()),
}
}
}
enum CanonResult {
Concrete(Hint_),
This,
Classname,
Wildcard,
Tycon,
Typaram,
Varray,
Darray,
VecOrDict,
ErrPrimTopLevel,
}
// Find the canonical representation of an `Happly` hint; if only some _part_
// of the hint needs modifying, we mutate here. If the whole hint should be
// replaced, we return a `Hint_` and replace in the calling function
fn canonical_happly(
hint_pos: &Pos,
id: &mut Id,
hints: &mut Vec<Hint>,
tparams: &HashSet<String>,
) -> ControlFlow<(Option<Hint_>, NamingError), (Option<Hint_>, Option<NamingError>)> {
match canonical_tycon(id, tparams) {
// The type constructors canonical representation _is_ `Happly`
CanonResult::Tycon => Continue((None, None)),
// The type constructors canonical representation is a concrete type
CanonResult::Concrete(hint_canon) => {
// We can't represent a concrete type applied to other types
let err_opt = if hints.is_empty() {
None
} else {
Some(NamingError::UnexpectedTypeArguments(id.0.clone()))
};
Continue((Some(hint_canon), err_opt))
}
// The type constructors corresponds to an in-scope type parameter
CanonResult::Typaram => {
// TODO: is this clone necessary? We are replacing the hint which
// contains them
let mut nm_canon = String::default();
let mut hints_canon = vec![];
std::mem::swap(&mut id.1, &mut nm_canon);
std::mem::swap(hints, &mut hints_canon);
let hint_canon = Hint_::Habstr(nm_canon.to_string(), hints_canon);
Continue((Some(hint_canon), None))
}
// The type constructors canonical representation is `Happly` but
// additional elaboration / validation is required
CanonResult::This => {
let hint_ = Hint_::Hthis;
let err_opt = if hints.is_empty() {
None
} else {
Some(NamingError::ThisNoArgument(hint_pos.clone()))
};
Continue((Some(hint_), err_opt))
}
CanonResult::Wildcard => {
if hints.is_empty() {
Continue((None, None))
} else {
let err = NamingError::ThisNoArgument(hint_pos.clone());
let hint_ = Hint_::Herr;
Break((Some(hint_), err))
}
}
CanonResult::Classname => {
// TODO[mjt] currently if `classname` is not applied to exactly
// one type parameter, it canonicalizes to `Hprim Tstring`.
// Investigate why this happens and if we can delay treatment to
// typing
if hints.len() == 1 {
Continue((None, None))
} else {
let err = NamingError::ClassnameParam(id.0.clone());
let hint_ = Hint_::Hprim(Tprim::Tstring);
Break((Some(hint_), err))
}
}
CanonResult::ErrPrimTopLevel => {
let hint_ = Hint_::Herr;
let err = NamingError::PrimitiveTopLevel(id.0.clone());
Break((Some(hint_), err))
}
// TODO[mjt] we should not be assuming knowledge about the arity of
// type constructors during elaboration
CanonResult::Darray if hints.len() == 2 => {
id.1 = sn::collections::DICT.to_string();
Continue((None, None))
}
CanonResult::Darray if hints.len() < 2 => {
id.1 = sn::collections::DICT.to_string();
hints.clear();
hints.push(Hint(id.0.clone(), Box::new(Hint_::Hany)));
hints.push(Hint(id.0.clone(), Box::new(Hint_::Hany)));
let err = NamingError::TooFewTypeArguments(hint_pos.clone());
Continue((None, Some(err)))
}
CanonResult::Darray => {
let hint_ = Hint_::Hany;
let err = NamingError::TooManyTypeArguments(hint_pos.clone());
Break((Some(hint_), err))
}
CanonResult::Varray if hints.len() == 1 => {
id.1 = sn::collections::VEC.to_string();
Continue((None, None))
}
CanonResult::Varray if hints.is_empty() => {
id.1 = sn::collections::VEC.to_string();
hints.clear();
hints.push(Hint(id.0.clone(), Box::new(Hint_::Hany)));
let err = NamingError::TooFewTypeArguments(hint_pos.clone());
Continue((None, Some(err)))
}
CanonResult::Varray => {
let hint_ = Hint_::Hany;
let err = NamingError::TooManyTypeArguments(hint_pos.clone());
Break((Some(hint_), err))
}
CanonResult::VecOrDict if hints.len() > 2 => {
let hint_ = Hint_::Hany;
let err = NamingError::TooManyTypeArguments(hint_pos.clone());
Break((Some(hint_), err))
}
CanonResult::VecOrDict => match hints.pop() {
None => {
let mut pos_canon = Pos::NONE;
std::mem::swap(&mut id.0, &mut pos_canon);
let hint_ = Hint_::HvecOrDict(None, Hint(pos_canon.clone(), Box::new(Hint_::Hany)));
let err = NamingError::TooFewTypeArguments(pos_canon);
Continue((Some(hint_), Some(err)))
}
Some(hint2) => {
if let Some(hint1) = hints.pop() {
let hint_ = Hint_::HvecOrDict(Some(hint1), hint2);
Continue((Some(hint_), None))
} else {
let hint_ = Hint_::HvecOrDict(None, hint2);
Continue((Some(hint_), None))
}
}
},
}
}
fn canonical_tycon(id: &Id, tparams: &HashSet<String>) -> CanonResult {
if id.1 == sn::typehints::INT {
CanonResult::Concrete(Hint_::Hprim(Tprim::Tint))
} else if id.1 == sn::typehints::BOOL {
CanonResult::Concrete(Hint_::Hprim(Tprim::Tbool))
} else if id.1 == sn::typehints::FLOAT {
CanonResult::Concrete(Hint_::Hprim(Tprim::Tfloat))
} else if id.1 == sn::typehints::STRING {
CanonResult::Concrete(Hint_::Hprim(Tprim::Tstring))
} else if id.1 == sn::typehints::VOID {
CanonResult::Concrete(Hint_::Hprim(Tprim::Tvoid))
} else if id.1 == sn::typehints::NORETURN {
CanonResult::Concrete(Hint_::Hprim(Tprim::Tnoreturn))
} else if id.1 == sn::typehints::NULL {
CanonResult::Concrete(Hint_::Hprim(Tprim::Tnull))
} else if id.1 == sn::typehints::RESOURCE {
CanonResult::Concrete(Hint_::Hprim(Tprim::Tresource))
} else if id.1 == sn::typehints::ARRAYKEY {
CanonResult::Concrete(Hint_::Hprim(Tprim::Tarraykey))
} else if id.1 == sn::typehints::NUM {
CanonResult::Concrete(Hint_::Hprim(Tprim::Tnum))
} else if id.1 == sn::typehints::DARRAY {
CanonResult::Darray
} else if id.1 == sn::typehints::VARRAY {
CanonResult::Varray
} else if id.1 == sn::typehints::VARRAY_OR_DARRAY || id.1 == sn::typehints::VEC_OR_DICT {
// TODO[mjt] `vec_or_dict` is currently special cased since the canonical representation
// requires us to have no arity mismatches or throw away info. We do not use that repr here
// to avoid having to do so. Ultimately, we should remove that special case
CanonResult::VecOrDict
} else if id.1 == sn::typehints::MIXED {
CanonResult::Concrete(Hint_::Hmixed)
} else if id.1 == sn::typehints::NONNULL {
CanonResult::Concrete(Hint_::Hnonnull)
} else if id.1 == sn::typehints::NOTHING {
CanonResult::Concrete(Hint_::Hnothing)
} else if id.1 == sn::typehints::DYNAMIC {
CanonResult::Concrete(Hint_::Hdynamic)
} else if id.1 == sn::typehints::THIS {
CanonResult::This
} else if id.1 == sn::typehints::WILDCARD {
CanonResult::Wildcard
} else if id.1 == sn::classes::CLASS_NAME {
CanonResult::Classname
} else if tparams.contains(&id.1) {
CanonResult::Typaram
} else if is_toplevel_prim(&id.1) {
// TODO: this should be a separate validation pass
CanonResult::ErrPrimTopLevel
} else {
CanonResult::Tycon
}
}
fn is_toplevel_prim(str: &str) -> bool {
if let Some(substr) = str.strip_prefix('\\') {
return is_prim(substr);
}
false
}
fn is_prim(str: &str) -> bool {
str == sn::typehints::VOID
|| str == sn::typehints::NULL
|| str == sn::typehints::NORETURN
|| str == sn::typehints::INT
|| str == sn::typehints::BOOL
|| str == sn::typehints::FLOAT
|| str == sn::typehints::NUM
|| str == sn::typehints::STRING
|| str == sn::typehints::RESOURCE
|| str == sn::typehints::MIXED
|| str == sn::typehints::NONNULL
|| str == sn::typehints::ARRAYKEY
|| str == sn::typehints::NOTHING
}
#[cfg(test)]
mod tests {
use nast::ClassConcreteTypeconst;
use nast::ClassTypeconst;
use super::*;
#[test]
fn test_int() {
let env = Env::default();
let mut pass = ElabHintHapplyPass::default();
let mut elem = Hint(
Pos::NONE,
Box::new(Hint_::Happly(
Id(Pos::NONE, sn::typehints::INT.to_string()),
vec![],
)),
);
elem.transform(&env, &mut pass);
let Hint(_, hint_) = elem;
assert!(matches!(&*hint_, Hint_::Hprim(Tprim::Tint)))
}
#[test]
fn test_typconst_int() {
let env = Env::default();
let mut pass = ElabHintHapplyPass::default();
let mut elem = ClassTypeconst::TCConcrete(ClassConcreteTypeconst {
c_tc_type: Hint(
Pos::NONE,
Box::new(Hint_::Happly(
Id(Pos::NONE, sn::typehints::INT.to_string()),
vec![],
)),
),
});
elem.transform(&env, &mut pass);
assert!(matches!(
elem,
ClassTypeconst::TCConcrete(ClassConcreteTypeconst {
c_tc_type: Hint(_, box Hint_::Hprim(Tprim::Tint)),
})
))
}
#[test]
fn test_vec_or_dict_two_tyargs() {
let env = Env::default();
let mut pass = ElabHintHapplyPass::default();
let mut elem = Hint(
Pos::NONE,
Box::new(Hint_::Happly(
Id(Pos::NONE, sn::typehints::VEC_OR_DICT.to_string()),
vec![
Hint(Pos::NONE, Box::new(Hint_::Hmixed)),
Hint(Pos::NONE, Box::new(Hint_::Hnothing)),
],
)),
);
elem.transform(&env, &mut pass);
let Hint(_, hint_) = elem;
assert!(match &*hint_ {
Hint_::HvecOrDict(Some(h1), h2) => {
let Hint(_, h1_) = h1 as &Hint;
let Hint(_, h2_) = h2 as &Hint;
matches!(**h1_, Hint_::Hmixed) && matches!(**h2_, Hint_::Hnothing)
}
_ => false,
})
}
#[test]
fn test_vec_or_dict_one_tyargs() {
let env = Env::default();
let mut pass = ElabHintHapplyPass::default();
let mut elem = Hint(
Pos::NONE,
Box::new(Hint_::Happly(
Id(Pos::NONE, sn::typehints::VEC_OR_DICT.to_string()),
vec![Hint(Pos::NONE, Box::new(Hint_::Hnothing))],
)),
);
elem.transform(&env, &mut pass);
let Hint(_, hint_) = elem;
assert!(match &*hint_ {
Hint_::HvecOrDict(None, h) => {
let Hint(_, h_) = h as &Hint;
matches!(**h_, Hint_::Hnothing)
}
_ => false,
})
}
#[test]
fn test_vec_or_dict_zero_tyargs() {
let env = Env::default();
let mut pass = ElabHintHapplyPass::default();
let mut elem = Hint(
Pos::NONE,
Box::new(Hint_::Happly(
Id(Pos::NONE, sn::typehints::VEC_OR_DICT.to_string()),
vec![],
)),
);
elem.transform(&env, &mut pass);
let Hint(_, hint_) = elem;
assert!(match &*hint_ {
Hint_::HvecOrDict(None, h) => {
let Hint(_, h_) = h as &Hint;
matches!(**h_, Hint_::Hany)
}
_ => false,
})
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/elab_hint_hsoft.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 nast::Hint;
use nast::Hint_;
use nast::Pos;
use crate::prelude::*;
#[derive(Clone, Copy, Default)]
pub struct ElabHintHsoftPass;
impl Pass for ElabHintHsoftPass {
fn on_ty_hint_top_down(&mut self, env: &Env, elem: &mut Hint) -> std::ops::ControlFlow<()> {
let Hint(_, hint_) = elem;
if let Hint_::Hsoft(inner) = hint_ as &mut Hint_ {
if env.soft_as_like() {
// Replace `Hsoft` with `Hlike` retaining the original position
// (pos, Hsoft(hint)) ==> (pos, Hlike(hint))
let herr = Hint(Pos::NONE, Box::new(Hint_::Herr));
let inner_hint = std::mem::replace(inner, herr);
**hint_ = Hint_::Hlike(inner_hint)
} else {
// Drop the surrounding `Hsoft` and use the inner Hint_
// whilst maintaining positions
// (pos, Hsoft(_, hint_)) ==> (pos, hint_)
let Hint(_, inner_hint_) = inner;
let herr_ = Hint_::Herr;
let inner_hint_ = std::mem::replace(inner_hint_ as &mut Hint_, herr_);
**hint_ = inner_hint_
}
}
Continue(())
}
}
#[cfg(test)]
mod tests {
use nast::Hint;
use nast::Hint_;
use nast::Pos;
use oxidized::typechecker_options::TypecheckerOptions;
use super::*;
use crate::env::ProgramSpecificOptions;
#[test]
fn test() {
let mut pass = ElabHintHsoftPass;
let mut elem1: Hint = Hint(
Pos::NONE,
Box::new(Hint_::Hsoft(Hint(Pos::NONE, Box::new(Hint_::Hdynamic)))),
);
let mut elem2 = elem1.clone();
// Transform `elem1` without flag `SOFT_AS_LIKE` set and expect
// `Hdynamic`.
let tco = TypecheckerOptions {
..Default::default()
};
let pso = ProgramSpecificOptions {
..Default::default()
};
let env = Env::new(&tco, &pso);
elem1.transform(&env, &mut pass);
assert!(matches!(*elem1.1, Hint_::Hdynamic));
// Transform `elem2` with flag `SOFT_AS_LIKE` set & expect `Hlike(_,
// Hdynamic)`.
let tco = TypecheckerOptions {
po_interpret_soft_types_as_like_types: true,
..Default::default()
};
let pso = ProgramSpecificOptions {
..Default::default()
};
let env = Env::new(&tco, &pso);
elem2.transform(&env, &mut pass);
assert!(matches!(&*elem2.1, Hint_::Hlike(_)));
assert!(match &*elem2.1 {
Hint_::Hlike(inner) => matches!(*inner.1, Hint_::Hdynamic),
_ => false,
})
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/elab_hint_retonly.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 nast::Hint;
use nast::Hint_;
use nast::Tprim;
use oxidized::naming_error::ReturnOnlyHint;
use crate::prelude::*;
#[derive(Clone, Copy, Default)]
pub struct ElabHintRetonlyPass {
allow_retonly: bool,
}
impl Pass for ElabHintRetonlyPass {
fn on_ty_hint_top_down(&mut self, env: &Env, elem: &mut Hint) -> ControlFlow<()> {
match elem {
Hint(pos, box hint_ @ Hint_::Hprim(Tprim::Tvoid)) if !self.allow_retonly => {
env.emit_error(NamingError::ReturnOnlyTypehint {
pos: pos.clone(),
kind: ReturnOnlyHint::Hvoid,
});
*hint_ = Hint_::Herr;
Break(())
}
Hint(pos, box hint_ @ Hint_::Hprim(Tprim::Tnoreturn)) if !self.allow_retonly => {
env.emit_error(NamingError::ReturnOnlyTypehint {
pos: pos.clone(),
kind: ReturnOnlyHint::Hnoreturn,
});
*hint_ = Hint_::Herr;
Break(())
}
_ => Continue(()),
}
}
fn on_ty_hint__top_down(&mut self, _: &Env, elem: &mut Hint_) -> ControlFlow<()> {
match elem {
Hint_::Happly(..) | Hint_::Habstr(..) => self.allow_retonly = true,
_ => (),
}
Continue(())
}
fn on_ty_targ_top_down(&mut self, _: &Env, _: &mut nast::Targ) -> ControlFlow<()> {
self.allow_retonly = true;
Continue(())
}
fn on_fld_hint_fun_return_ty_top_down(&mut self, _: &Env, _: &mut Hint) -> ControlFlow<()> {
self.allow_retonly = true;
Continue(())
}
fn on_fld_fun__ret_top_down(&mut self, _: &Env, _: &mut nast::TypeHint) -> ControlFlow<()> {
self.allow_retonly = true;
Continue(())
}
fn on_fld_method__ret_top_down(&mut self, _: &Env, _: &mut nast::TypeHint) -> ControlFlow<()> {
self.allow_retonly = true;
Continue(())
}
}
#[cfg(test)]
mod tests {
use nast::Block;
use nast::FunParam;
use nast::Fun_;
use nast::FuncBody;
use nast::HintFun;
use nast::Id;
use nast::ParamKind;
use nast::Pos;
use nast::Targ;
use nast::TypeHint;
use super::*;
#[test]
fn test_fun_ret_valid() {
let env = Env::default();
let mut pass = ElabHintRetonlyPass::default();
let mut elem = Fun_ {
span: Default::default(),
readonly_this: Default::default(),
annotation: Default::default(),
readonly_ret: Default::default(),
ret: TypeHint(
(),
Some(Hint(Pos::default(), Box::new(Hint_::Hprim(Tprim::Tvoid)))),
),
params: Default::default(),
ctxs: Default::default(),
unsafe_ctxs: Default::default(),
body: FuncBody {
fb_ast: Block(vec![]),
},
fun_kind: nast::FunKind::FSync,
user_attributes: Default::default(),
external: Default::default(),
doc_comment: Default::default(),
};
elem.transform(&env, &mut pass);
assert!(env.into_errors().is_empty());
assert!(matches!(
elem.ret.1,
Some(Hint(_, box Hint_::Hprim(Tprim::Tvoid)))
))
}
#[test]
fn test_hint_fun_return_ty_valid() {
let env = Env::default();
let mut pass = ElabHintRetonlyPass::default();
let mut elem = HintFun {
is_readonly: Default::default(),
param_tys: Default::default(),
param_info: Default::default(),
variadic_ty: Default::default(),
ctxs: Default::default(),
return_ty: Hint(Pos::default(), Box::new(Hint_::Hprim(Tprim::Tvoid))),
is_readonly_return: Default::default(),
};
elem.transform(&env, &mut pass);
assert!(env.into_errors().is_empty());
assert!(matches!(
elem.return_ty,
Hint(_, box Hint_::Hprim(Tprim::Tvoid))
))
}
#[test]
fn test_hint_in_happly_valid() {
let env = Env::default();
let mut pass = ElabHintRetonlyPass::default();
// Whatever<void>
let mut elem = Hint(
Pos::default(),
Box::new(Hint_::Happly(
Id::default(),
vec![Hint(Pos::default(), Box::new(Hint_::Hprim(Tprim::Tvoid)))],
)),
);
elem.transform(&env, &mut pass);
assert!(env.into_errors().is_empty());
assert!(match elem {
Hint(_, box Hint_::Happly(_, hints)) =>
matches!(hints.as_slice(), [Hint(_, box Hint_::Hprim(Tprim::Tvoid))]),
_ => false,
})
}
#[test]
fn test_hint_in_targ_valid() {
let env = Env::default();
let mut pass = ElabHintRetonlyPass::default();
let mut elem = Targ(
(),
Hint(Pos::default(), Box::new(Hint_::Hprim(Tprim::Tvoid))),
);
elem.transform(&env, &mut pass);
assert!(env.into_errors().is_empty());
assert!(matches!(elem.1, Hint(_, box Hint_::Hprim(Tprim::Tvoid))))
}
#[test]
fn test_hint_top_level_invalid() {
let env = Env::default();
let mut pass = ElabHintRetonlyPass::default();
let mut elem = Hint(Pos::default(), Box::new(Hint_::Hprim(Tprim::Tvoid)));
elem.transform(&env, &mut pass);
let retonly_hint_err_opt = env.into_errors().pop();
assert!(matches!(
retonly_hint_err_opt,
Some(NamingPhaseError::Naming(
NamingError::ReturnOnlyTypehint { .. }
))
));
assert!(matches!(elem, Hint(_, box Hint_::Herr)))
}
#[test]
fn test_fun_param_invalid() {
let env = Env::default();
let mut pass = ElabHintRetonlyPass::default();
let mut elem = Fun_ {
span: Default::default(),
readonly_this: Default::default(),
annotation: Default::default(),
readonly_ret: Default::default(),
ret: TypeHint((), None),
params: vec![FunParam {
annotation: (),
type_hint: TypeHint(
(),
Some(Hint(Pos::default(), Box::new(Hint_::Hprim(Tprim::Tvoid)))),
),
is_variadic: Default::default(),
pos: Default::default(),
name: Default::default(),
expr: Default::default(),
readonly: Default::default(),
callconv: ParamKind::Pnormal,
user_attributes: Default::default(),
visibility: Default::default(),
}],
ctxs: Default::default(),
unsafe_ctxs: Default::default(),
body: FuncBody {
fb_ast: Block(vec![]),
},
fun_kind: nast::FunKind::FSync,
user_attributes: Default::default(),
external: Default::default(),
doc_comment: Default::default(),
};
elem.transform(&env, &mut pass);
let retonly_hint_err_opt = env.into_errors().pop();
assert!(matches!(
retonly_hint_err_opt,
Some(NamingPhaseError::Naming(
NamingError::ReturnOnlyTypehint { .. }
))
));
assert!(match elem.params.pop() {
Some(fp) => matches!(fp.type_hint, TypeHint(_, Some(Hint(_, box Hint_::Herr)))),
_ => false,
})
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/elab_hint_this.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 bitflags::bitflags;
use nast::ClassHint;
use nast::ClassReq;
use nast::ClassVar;
use nast::Class_;
use nast::ClassishKind;
use nast::Expr_;
use nast::Hint;
use nast::Hint_;
use nast::RequireKind;
use nast::ShapeFieldInfo;
use nast::Targ;
use nast::Tparam;
use nast::TraitHint;
use nast::TypeHint;
use nast::Variance;
use nast::XhpAttr;
use nast::XhpAttrHint;
use crate::prelude::*;
#[derive(Copy, Clone, Default)]
pub struct ElabHintThisPass {
context: Option<Context>,
flags: Flags,
}
#[derive(Copy, Clone)]
enum Context {
ReqExtends,
Extends,
StaticClassVar(bool),
}
bitflags! {
#[derive(Default)]
struct Flags: u8 {
const FORBID_THIS= 1 << 0;
const IS_TOP_LEVEL_HACCESS_ROOT= 1 << 1;
const IN_INTERFACE = 1 << 2;
const IN_INVARIANT_FINAL = 1 << 3;
}
}
impl ElabHintThisPass {
fn forbid_this(&self) -> bool {
self.flags.contains(Flags::FORBID_THIS)
}
fn set_forbid_this(&mut self, value: bool) {
self.flags.set(Flags::FORBID_THIS, value)
}
fn set_static_class_var(&mut self, value: bool) {
self.context = Some(Context::StaticClassVar(value))
}
fn in_req_extends(&self) -> bool {
matches!(self.context, Some(Context::ReqExtends))
}
fn set_in_req_extends(&mut self) {
self.context = Some(Context::ReqExtends)
}
fn in_extends(&self) -> bool {
matches!(self.context, Some(Context::Extends))
}
fn set_in_extends(&mut self) {
self.context = Some(Context::Extends)
}
fn is_top_level_haccess_root(&self) -> bool {
self.flags.contains(Flags::IS_TOP_LEVEL_HACCESS_ROOT)
}
fn set_is_top_level_haccess_root(&mut self, value: bool) {
self.flags.set(Flags::IS_TOP_LEVEL_HACCESS_ROOT, value)
}
fn in_interface(&self) -> bool {
self.flags.contains(Flags::IN_INTERFACE)
}
fn set_in_interface(&mut self, value: bool) {
self.flags.set(Flags::IN_INTERFACE, value)
}
fn in_invariant_final(&self) -> bool {
self.flags.contains(Flags::IN_INVARIANT_FINAL)
}
fn set_in_invariant_final(&mut self, value: bool) {
self.flags.set(Flags::IN_INVARIANT_FINAL, value)
}
// We want to disallow `this` hints in:
// - _class_ and _abstract class_ type parameters
// - non-late static bound class_var
// - `extends` and `require extends` clauses _unless_ it appears as the
// top-level root of a type access
fn forbid_in_extends(&self) -> bool {
(self.in_req_extends() || self.in_extends())
&& (!self.in_interface())
&& (!self.is_top_level_haccess_root())
&& (!self.in_invariant_final())
}
}
impl Pass for ElabHintThisPass {
fn on_ty_hint_top_down(&mut self, env: &Env, elem: &mut Hint) -> ControlFlow<()> {
let Hint(pos, box hint_) = elem;
match &hint_ {
Hint_::Hthis if self.forbid_this() || self.forbid_in_extends() => {
// We have a `this` hint in a forbidden position; raise and error,
// leave the `Herr` and break
*hint_ = Hint_::Herr;
env.emit_error(NamingError::ThisTypeForbidden {
pos: pos.clone(),
in_extends: self.in_extends(),
in_req_extends: self.in_req_extends(),
});
return Continue(());
}
// Otherwise, just update our state to reflect whether we are
// at the top-level `Hint` inside an `Haccess`
Hint_::Haccess(..) => self.set_is_top_level_haccess_root(true),
_ => self.set_is_top_level_haccess_root(false),
}
Continue(())
}
fn on_ty_class__top_down(&mut self, _: &Env, elem: &mut Class_) -> ControlFlow<()> {
let in_interface = matches!(elem.kind, ClassishKind::Cinterface);
let in_invariant_final = elem.final_
&& elem
.tparams
.iter()
.all(|tp| matches!(tp.variance, Variance::Invariant));
self.set_in_interface(in_interface);
self.set_in_invariant_final(in_invariant_final);
Continue(())
}
fn on_fld_class__tparams_top_down(&mut self, _: &Env, _: &mut Vec<Tparam>) -> ControlFlow<()> {
self.set_forbid_this(true);
Continue(())
}
fn on_fld_class__extends_top_down(
&mut self,
_: &Env,
_: &mut Vec<ClassHint>,
) -> ControlFlow<()> {
self.set_in_extends();
Continue(())
}
fn on_fld_class__uses_top_down(&mut self, _: &Env, _: &mut Vec<TraitHint>) -> ControlFlow<()> {
self.set_forbid_this(false);
Continue(())
}
fn on_fld_class__xhp_attrs_top_down(
&mut self,
_: &Env,
_: &mut Vec<XhpAttr>,
) -> ControlFlow<()> {
self.set_forbid_this(false);
Continue(())
}
fn on_fld_class__xhp_attr_uses_top_down(
&mut self,
_: &Env,
_: &mut Vec<XhpAttrHint>,
) -> ControlFlow<()> {
self.set_forbid_this(false);
Continue(())
}
fn on_fld_class__reqs_top_down(&mut self, _: &Env, _: &mut Vec<ClassReq>) -> ControlFlow<()> {
self.set_forbid_this(false);
Continue(())
}
fn on_ty_class_req_top_down(&mut self, _: &Env, elem: &mut ClassReq) -> ControlFlow<()> {
if elem.1 == RequireKind::RequireExtends {
self.set_in_req_extends()
}
Continue(())
}
fn on_fld_class__implements_top_down(
&mut self,
_: &Env,
_: &mut Vec<ClassHint>,
) -> ControlFlow<()> {
self.set_forbid_this(false);
Continue(())
}
fn on_ty_class_var_top_down(&mut self, _: &Env, elem: &mut ClassVar) -> ControlFlow<()> {
self.set_static_class_var(
elem.is_static
&& !elem
.user_attributes
.iter()
.any(|ua| ua.name.name() == sn::user_attributes::LSB),
);
Continue(())
}
fn on_fld_class_var_type__top_down(&mut self, _: &Env, _: &mut TypeHint) -> ControlFlow<()> {
let forbid_this = match self.context {
Some(Context::StaticClassVar(lsb)) => lsb,
_ => panic!("impossible"),
};
self.context = None;
self.set_forbid_this(forbid_this);
Continue(())
}
fn on_fld_fun__ret_top_down(&mut self, _: &Env, _: &mut TypeHint) -> ControlFlow<()> {
self.context = None;
self.set_forbid_this(false);
Continue(())
}
fn on_ty_expr__top_down(&mut self, _: &Env, elem: &mut Expr_) -> ControlFlow<()> {
match elem {
Expr_::Cast(..) | Expr_::Is(..) | Expr_::As(..) | Expr_::Upcast(..) => {
self.context = None;
self.set_forbid_this(false);
}
_ => (),
}
Continue(())
}
fn on_ty_shape_field_info_top_down(
&mut self,
_: &Env,
_: &mut ShapeFieldInfo,
) -> ControlFlow<()> {
self.context = None;
self.set_forbid_this(false);
Continue(())
}
fn on_fld_hint_fun_return_ty_top_down(&mut self, _: &Env, _: &mut Hint) -> ControlFlow<()> {
self.context = None;
self.set_forbid_this(false);
Continue(())
}
fn on_ty_targ_top_down(&mut self, _: &Env, _: &mut Targ) -> ControlFlow<()> {
self.context = None;
self.set_forbid_this(false);
Continue(())
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use file_info::Mode;
use nast::Id;
use nast::Pos;
use nast::UserAttribute;
use nast::UserAttributes;
use oxidized::namespace_env;
use oxidized::s_map::SMap;
use super::*;
fn make_class(
kind: ClassishKind,
name: &str,
final_: bool,
tparams: Vec<Tparam>,
extends: Vec<ClassHint>,
reqs: Vec<ClassReq>,
) -> Class_ {
Class_ {
span: Default::default(),
annotation: (),
mode: Mode::Mstrict,
final_,
is_xhp: Default::default(),
has_xhp_keyword: Default::default(),
kind,
name: Id(Pos::default(), name.to_string()),
tparams,
extends,
uses: Default::default(),
xhp_attr_uses: Default::default(),
xhp_category: Default::default(),
reqs,
implements: Default::default(),
where_constraints: Default::default(),
consts: Default::default(),
typeconsts: Default::default(),
vars: Default::default(),
methods: Default::default(),
xhp_children: Default::default(),
xhp_attrs: Default::default(),
namespace: Arc::new(namespace_env::Env {
ns_uses: SMap::default(),
class_uses: SMap::default(),
fun_uses: SMap::default(),
const_uses: SMap::default(),
name: None,
is_codegen: false,
disable_xhp_element_mangling: false,
}),
user_attributes: Default::default(),
file_attributes: Default::default(),
docs_url: Default::default(),
enum_: Default::default(),
doc_comment: Default::default(),
emit_id: Default::default(),
internal: Default::default(),
module: Default::default(),
}
}
fn make_static_class_var(name: &str, type_: TypeHint, lsb: bool) -> ClassVar {
let user_attributes = if lsb {
UserAttributes(vec![UserAttribute {
name: Id(Default::default(), sn::user_attributes::LSB.to_string()),
params: vec![],
}])
} else {
UserAttributes(vec![])
};
ClassVar {
final_: Default::default(),
xhp_attr: Default::default(),
abstract_: Default::default(),
readonly: Default::default(),
visibility: nast::Visibility::Public,
type_,
id: Id(Default::default(), name.to_string()),
expr: Default::default(),
user_attributes,
doc_comment: Default::default(),
is_promoted_variadic: Default::default(),
is_static: true,
span: Default::default(),
}
}
// -- `this` in extends clause ---------------------------------------------
#[test]
// We allow `this` as a generic on a super type when the class is final
// and not generic
fn test_final_extends_non_generic_valid() {
let env = Env::default();
let mut pass = ElabHintThisPass::default();
// final class C extends B<this> {}
let mut elem: Class_ = make_class(
ClassishKind::Cclass(nast::Abstraction::Concrete),
"C",
true,
vec![],
vec![Hint(
Pos::default(),
Box::new(Hint_::Happly(
Id(Pos::default(), "B".to_string()),
vec![Hint(Pos::default(), Box::new(Hint_::Hthis))],
)),
)],
vec![],
);
elem.transform(&env, &mut pass);
// Expect no errors
assert!(env.into_errors().is_empty());
assert!(match elem.extends.pop() {
Some(Hint(_, box Hint_::Happly(_, hints))) => match hints.as_slice() {
[Hint(_, box Hint_::Hthis)] => true,
_ => false,
},
_ => false,
})
}
#[test]
// We allow `this` as a generic on a super type when the class is final
// and invariant in all type parameters
fn test_final_extends_invariant_valid() {
let env = Env::default();
let mut pass = ElabHintThisPass::default();
// final class C<T> extends B<this> {}
let mut elem: Class_ = make_class(
ClassishKind::Cclass(nast::Abstraction::Concrete),
"C",
true,
vec![Tparam {
variance: Variance::Invariant,
name: Id(Pos::default(), "T".to_string()),
parameters: Default::default(),
constraints: Default::default(),
reified: nast::ReifyKind::Erased,
user_attributes: Default::default(),
}],
vec![Hint(
Pos::default(),
Box::new(Hint_::Happly(
Id(Pos::default(), "B".to_string()),
vec![Hint(Pos::default(), Box::new(Hint_::Hthis))],
)),
)],
vec![],
);
elem.transform(&env, &mut pass);
// Expect no errors
assert!(env.into_errors().is_empty());
assert!(match elem.extends.pop() {
Some(Hint(_, box Hint_::Happly(_, hints))) => match hints.as_slice() {
[Hint(_, box Hint_::Hthis)] => true,
_ => false,
},
_ => false,
})
}
#[test]
// We disallow `this` as a generic on a super type when the class is final
// and but invariant in some type parameter
fn test_final_extends_covariant_invalid() {
let env = Env::default();
let mut pass = ElabHintThisPass::default();
// final class C<+T> extends B<this> {}
let mut elem: Class_ = make_class(
ClassishKind::Cclass(nast::Abstraction::Concrete),
"C",
true,
vec![Tparam {
variance: Variance::Covariant,
name: Id(Pos::default(), "T".to_string()),
parameters: Default::default(),
constraints: Default::default(),
reified: nast::ReifyKind::Erased,
user_attributes: Default::default(),
}],
vec![Hint(
Pos::default(),
Box::new(Hint_::Happly(
Id(Pos::default(), "B".to_string()),
vec![Hint(Pos::default(), Box::new(Hint_::Hthis))],
)),
)],
vec![],
);
elem.transform(&env, &mut pass);
let this_type_forbidden_err_opt = env.into_errors().pop();
assert!(match this_type_forbidden_err_opt {
Some(NamingPhaseError::Naming(NamingError::ThisTypeForbidden {
in_extends,
in_req_extends,
..
})) => in_extends && !in_req_extends,
_ => false,
});
assert!(match elem.extends.pop() {
Some(Hint(_, box Hint_::Happly(_, hints))) => match hints.as_slice() {
[Hint(_, box Hint_::Herr)] => true,
_ => false,
},
_ => false,
})
}
// -- `this` hint in require extends ---------------------------------------
#[test]
// We disallow `this` as a generic in require extends clauses
fn test_req_extends_generic_invalid() {
let env = Env::default();
let mut pass = ElabHintThisPass::default();
// trait C<T> { require extends B<this>; }
let mut elem: Class_ = make_class(
ClassishKind::Ctrait,
"C",
false,
vec![Tparam {
variance: Variance::Invariant,
name: Id(Pos::default(), "T".to_string()),
parameters: Default::default(),
constraints: Default::default(),
reified: nast::ReifyKind::Erased,
user_attributes: Default::default(),
}],
vec![],
vec![ClassReq(
Hint(
Pos::default(),
Box::new(Hint_::Happly(
Id(Pos::default(), "B".to_string()),
vec![Hint(Pos::default(), Box::new(Hint_::Hthis))],
)),
),
RequireKind::RequireExtends,
)],
);
elem.transform(&env, &mut pass);
let this_type_forbidden_err_opt = env.into_errors().pop();
assert!(match this_type_forbidden_err_opt {
Some(NamingPhaseError::Naming(NamingError::ThisTypeForbidden {
in_extends,
in_req_extends,
..
})) => !in_extends && in_req_extends,
_ => false,
});
assert!(match elem.reqs.pop() {
Some(ClassReq(Hint(_, box Hint_::Happly(_, hints)), _)) => match hints.as_slice() {
[Hint(_, box Hint_::Herr)] => true,
_ => false,
},
_ => false,
})
}
#[test]
// We disallow `this` as a top-level hint in require extends clauses
fn test_req_extends_top_level_invalid() {
let env = Env::default();
let mut pass = ElabHintThisPass::default();
// trait C<T> { require extends this; }
let mut elem: Class_ = make_class(
ClassishKind::Ctrait,
"C",
false,
vec![Tparam {
variance: Variance::Invariant,
name: Id(Pos::default(), "T".to_string()),
parameters: Default::default(),
constraints: Default::default(),
reified: nast::ReifyKind::Erased,
user_attributes: Default::default(),
}],
vec![],
vec![ClassReq(
Hint(Pos::default(), Box::new(Hint_::Hthis)),
RequireKind::RequireExtends,
)],
);
elem.transform(&env, &mut pass);
let this_type_forbidden_err_opt = env.into_errors().pop();
assert!(match this_type_forbidden_err_opt {
Some(NamingPhaseError::Naming(NamingError::ThisTypeForbidden {
in_extends,
in_req_extends,
..
})) => !in_extends && in_req_extends,
_ => false,
});
assert!(matches!(
elem.reqs.pop(),
Some(ClassReq(Hint(_, box Hint_::Herr), _))
));
}
// -- `this` in static class var -------------------------------------------
#[test]
fn test_lsb_static_class_var_valid() {
let env = Env::default();
let mut pass = ElabHintThisPass::default();
let mut elem: ClassVar = make_static_class_var(
"x",
TypeHint(
(),
Some(Hint(
Default::default(),
Box::new(Hint_::Hoption(Hint(
Default::default(),
Box::new(Hint_::Hthis),
))),
)),
),
true,
);
elem.transform(&env, &mut pass);
assert!(env.into_errors().is_empty());
let TypeHint(_, hint_opt) = elem.type_;
assert!(matches!(
hint_opt,
Some(Hint(_, box Hint_::Hoption(Hint(_, box Hint_::Hthis))))
));
}
#[test]
fn test_non_lsb_static_class_var_invalid() {
let env = Env::default();
let mut pass = ElabHintThisPass::default();
let mut elem: ClassVar = make_static_class_var(
"x",
TypeHint(
(),
Some(Hint(
Default::default(),
Box::new(Hint_::Hoption(Hint(
Default::default(),
Box::new(Hint_::Hthis),
))),
)),
),
false,
);
elem.transform(&env, &mut pass);
let this_type_forbidden_err_opt = env.into_errors().pop();
assert!(match this_type_forbidden_err_opt {
Some(NamingPhaseError::Naming(NamingError::ThisTypeForbidden {
in_extends,
in_req_extends,
..
})) => !in_extends && !in_req_extends,
_ => false,
});
let TypeHint(_, hint_opt) = elem.type_;
assert!(matches!(
hint_opt,
Some(Hint(_, box Hint_::Hoption(Hint(_, box Hint_::Herr))))
));
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/elab_hint_wildcard.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 nast::Contexts;
use nast::Expr_;
use nast::Hint;
use nast::Hint_;
use crate::prelude::*;
#[derive(Clone, Copy, Default)]
pub struct ElabHintWildcardPass {
depth: usize,
allow_wildcard: bool,
}
impl ElabHintWildcardPass {
pub fn reset_depth(&mut self) {
self.depth = 0
}
pub fn incr_depth(&mut self) {
self.depth += 1
}
}
impl Pass for ElabHintWildcardPass {
fn on_ty_hint_top_down(&mut self, env: &Env, elem: &mut Hint) -> ControlFlow<()> {
let Hint(pos, box hint_) = elem;
// Swap for `Herr`
let in_hint_ = std::mem::replace(hint_, Hint_::Herr);
match &in_hint_ {
Hint_::Hwildcard => {
if self.allow_wildcard && self.depth >= 1 {
// This is valid; restore the hint and continue
*hint_ = in_hint_;
Continue(())
} else {
// Wildcard hints are disallowed here; add an error
env.emit_error(NamingError::WildcardHintDisallowed(pos.clone()));
// We've already set the hint to `Herr` so just break
Break(())
}
}
_ => {
// This isn't a wildcard hint; restore the original hint and continue
*hint_ = in_hint_;
Continue(())
}
}
}
// Wildcard hints are _always_ disallowed in contexts
// TODO: we define this on `context` in OCaml - we need a newtype
// to do the same here
fn on_ty_contexts_top_down(&mut self, env: &Env, elem: &mut Contexts) -> ControlFlow<()> {
let Contexts(_, hints) = elem;
hints
.iter_mut()
.filter(|hint| is_wildcard(hint))
.for_each(|hint| {
let Hint(pos, box hint_) = hint;
env.emit_error(NamingError::InvalidWildcardContext(pos.clone()));
*hint_ = Hint_::Herr
});
Continue(())
}
fn on_ty_expr__top_down(&mut self, _: &Env, elem: &mut nast::Expr_) -> ControlFlow<()> {
match elem {
Expr_::Cast(..) => self.incr_depth(),
Expr_::Is(..) | Expr_::As(..) => self.allow_wildcard = true,
Expr_::Upcast(..) => self.allow_wildcard = false,
_ => (),
}
Continue(())
}
fn on_ty_targ_top_down(&mut self, _: &Env, _: &mut nast::Targ) -> ControlFlow<()> {
self.allow_wildcard = true;
self.incr_depth();
Continue(())
}
fn on_ty_hint__top_down(&mut self, _: &Env, elem: &mut Hint_) -> ControlFlow<()> {
match elem {
Hint_::Hunion(_)
| Hint_::Hintersection(_)
| Hint_::Hoption(_)
| Hint_::Hlike(_)
| Hint_::Hsoft(_)
| Hint_::Hrefinement(..) => self.reset_depth(),
Hint_::Htuple(_) | Hint_::Happly(..) | Hint_::Habstr(..) | Hint_::HvecOrDict(..) => {
self.incr_depth()
}
_ => (),
}
Continue(())
}
fn on_ty_shape_field_info_top_down(
&mut self,
_: &Env,
_: &mut nast::ShapeFieldInfo,
) -> ControlFlow<()> {
self.incr_depth();
Continue(())
}
}
fn is_wildcard(hint: &Hint) -> bool {
match hint {
Hint(_, box Hint_::Hwildcard) => true,
_ => false,
}
}
#[cfg(test)]
mod tests {
use nast::Pos;
use nast::Targ;
use super::*;
fn make_wildcard() -> Hint {
Hint(Pos::default(), Box::new(Hint_::Hwildcard))
}
// -- Wildcard hints in expressions ----------------------------------------
// -- Wilcard hints in `Is` (equivalently `As`) expressions ----------------
#[test]
// Wildcard hint at the top-level of a `Is` expression. `allow_wildcard`
// will be true because of the `Is` expression but depth will be 0 since
// we reach the `on_ty_hint_top_down` handler _before_ `on_ty_hint__top_down`
// As a result, we will mark the hint as invalid and raise an error
fn test_expr_is_top_level_invalid() {
let env = Env::default();
let mut pass = ElabHintWildcardPass::default();
let mut elem = Expr_::Is(Box::new((elab_utils::expr::null(), make_wildcard())));
elem.transform(&env, &mut pass);
let wildcard_hint_disallowed_err_opt = env.into_errors().pop();
assert!(matches!(
wildcard_hint_disallowed_err_opt,
Some(NamingPhaseError::Naming(
NamingError::WildcardHintDisallowed(_)
))
));
assert!(matches!(elem, Expr_::Is(box (_, Hint(_, box Hint_::Herr)))))
}
#[test]
// Wildcard hint inside a tuple hint, in a `Is` expression. This means
// we have (i) wildcards are allowed, (ii) depth is 1, (iii) the
// wildcard isn't applied to other types so we expect it to be valid
fn test_expr_is_nested_valid() {
let env = Env::default();
let mut pass = ElabHintWildcardPass::default();
let mut elem = Expr_::Is(Box::new((
elab_utils::expr::null(),
Hint(
Pos::default(),
Box::new(Hint_::Htuple(vec![make_wildcard()])),
),
)));
elem.transform(&env, &mut pass);
assert!(env.into_errors().is_empty());
assert!(match elem {
Expr_::Is(box (_, Hint(_, box Hint_::Htuple(mut hints)))) =>
hints.pop().map_or(false, |hint| is_wildcard(&hint)),
_ => false,
})
}
// -- Wildcard hint in `Upcast` expressions --------------------------------
#[test]
// Since `Upcast` sets `allow_wildcard` to false and the flag is only
// set to true in `targ`s or `Is`/`As` expressions we expect all wildcard
// hints appearing here to be invalid
fn test_expr_upcast_top_level_invalid() {
let env = Env::default();
let mut pass = ElabHintWildcardPass::default();
let mut elem = Expr_::Upcast(Box::new((elab_utils::expr::null(), make_wildcard())));
elem.transform(&env, &mut pass);
let wildcard_hint_disallowed_err_opt = env.into_errors().pop();
assert!(matches!(
wildcard_hint_disallowed_err_opt,
Some(NamingPhaseError::Naming(
NamingError::WildcardHintDisallowed(_)
))
));
assert!(matches!(
elem,
Expr_::Upcast(box (_, Hint(_, box Hint_::Herr)))
))
}
// -- Wildcard hint in `Cast` expressions ----------------------------------
#[test]
// Since `Cast` does not modify `allow_wildcard` we never expect it to be
// valid
fn test_expr_cast_top_level_invalid() {
let env = Env::default();
let mut pass = ElabHintWildcardPass::default();
let mut elem = Expr_::Cast(Box::new((make_wildcard(), elab_utils::expr::null())));
elem.transform(&env, &mut pass);
let wildcard_hint_disallowed_err_opt = env.into_errors().pop();
assert!(matches!(
wildcard_hint_disallowed_err_opt,
Some(NamingPhaseError::Naming(
NamingError::WildcardHintDisallowed(_)
))
));
assert!(matches!(
elem,
Expr_::Cast(box (Hint(_, box Hint_::Herr), _))
))
}
// -- Wildcard hints in `Contexts` -----------------------------------------
#[test]
// Wildcard hints are always invalid inside `Contexts`
fn test_contexts_top_level_invalid() {
let env = Env::default();
let mut pass = ElabHintWildcardPass::default();
let mut elem = Contexts(Pos::default(), vec![make_wildcard()]);
elem.transform(&env, &mut pass);
let invalid_wildcard_context_err_opt = env.into_errors().pop();
assert!(matches!(
invalid_wildcard_context_err_opt,
Some(NamingPhaseError::Naming(
NamingError::InvalidWildcardContext(_)
))
));
let Contexts(_, mut hints) = elem;
let hint_opt = hints.pop();
assert!(matches!(hint_opt, Some(Hint(_, box Hint_::Herr))))
}
// -- Wildcard hints in `Targ`s --------------------------------------------
#[test]
// Wildcard hints are valid inside `Targ`s
fn test_contexts_top_level_valid() {
let env = Env::default();
let mut pass = ElabHintWildcardPass::default();
let mut elem = Targ((), make_wildcard());
elem.transform(&env, &mut pass);
assert!(env.into_errors().is_empty());
let Targ(_, ref hint) = elem;
assert!(is_wildcard(hint))
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/elab_hkt.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 nast::Class_;
use nast::FunDef;
use nast::Hint;
use nast::Hint_;
use nast::Id;
use nast::Method_;
use nast::Tparam;
use nast::Typedef;
use crate::prelude::*;
#[derive(Clone, Copy, Default)]
pub struct ElabHktPass;
impl Pass for ElabHktPass {
fn on_ty_hint_top_down(&mut self, env: &Env, elem: &mut Hint) -> ControlFlow<()> {
if !env.hkt_enabled() {
let Hint(pos, hint_) = elem;
if let Hint_::Habstr(tp_name, tp_params) = &mut **hint_ {
if !tp_params.is_empty() {
env.emit_error(NamingError::TparamAppliedToType {
pos: pos.clone(),
tparam_name: tp_name.clone(),
});
tp_params.clear()
}
}
}
Continue(())
}
fn on_ty_class__top_down(&mut self, env: &Env, elem: &mut Class_) -> ControlFlow<()> {
if !env.hkt_enabled() {
elem.tparams
.iter_mut()
.for_each(|tparam| elab_tparam(env, tparam));
}
Continue(())
}
fn on_ty_typedef_top_down(&mut self, env: &Env, elem: &mut Typedef) -> ControlFlow<()> {
if !env.hkt_enabled() {
elem.tparams
.iter_mut()
.for_each(|tparam| elab_tparam(env, tparam));
}
Continue(())
}
fn on_ty_fun_def_top_down(&mut self, env: &Env, elem: &mut FunDef) -> ControlFlow<()> {
if !env.hkt_enabled() {
elem.tparams
.iter_mut()
.for_each(|tparam| elab_tparam(env, tparam));
}
Continue(())
}
fn on_ty_method__top_down(&mut self, env: &Env, elem: &mut Method_) -> ControlFlow<()> {
if !env.hkt_enabled() {
elem.tparams
.iter_mut()
.for_each(|tparam| elab_tparam(env, tparam));
}
Continue(())
}
fn on_ty_tparam_top_down(&mut self, env: &Env, elem: &mut Tparam) -> ControlFlow<()> {
if !env.hkt_enabled() {
elab_tparam(env, elem);
}
Continue(())
}
}
fn elab_tparam(env: &Env, tparam: &mut Tparam) {
if !tparam.parameters.is_empty() {
let Id(pos, tp_name) = &tparam.name;
env.emit_error(NamingError::TparamWithTparam {
pos: pos.clone(),
tparam_name: tp_name.clone(),
});
tparam.parameters.clear()
}
}
#[cfg(test)]
mod tests {
use nast::Pos;
use nast::ReifyKind;
use nast::UserAttributes;
use nast::Variance;
use oxidized::typechecker_options::TypecheckerOptions;
use super::*;
use crate::env::ProgramSpecificOptions;
#[test]
fn test_hint() {
let env_hkt_disabled = Env::new(
&TypecheckerOptions::default(),
&ProgramSpecificOptions::default(),
);
let env_hkt_enabled = Env::new(
&TypecheckerOptions {
tco_higher_kinded_types: true,
..Default::default()
},
&ProgramSpecificOptions::default(),
);
let mut pass = ElabHktPass;
let mut elem = Hint(
Pos::NONE,
Box::new(Hint_::Habstr(
"T".to_string(),
vec![Hint(Pos::NONE, Box::new(Hint_::Hmixed))],
)),
);
elem.transform(&env_hkt_enabled, &mut pass);
let Hint(_, hint_) = &elem;
assert!(match &**hint_ {
Hint_::Habstr(_, hints) => !hints.is_empty(),
_ => false,
});
assert_eq!(env_hkt_enabled.into_errors().len(), 0);
elem.transform(&env_hkt_disabled, &mut pass);
let Hint(_, hint_) = &elem;
assert!(match &**hint_ {
Hint_::Habstr(_, hints) => hints.is_empty(),
_ => false,
});
assert_eq!(env_hkt_disabled.into_errors().len(), 1);
}
#[test]
fn test_tparam() {
let env_hkt_disabled = Env::new(
&TypecheckerOptions::default(),
&ProgramSpecificOptions::default(),
);
let env_hkt_enabled = Env::new(
&TypecheckerOptions {
tco_higher_kinded_types: true,
..Default::default()
},
&ProgramSpecificOptions::default(),
);
let mut pass = ElabHktPass;
let mut elem = Tparam {
variance: Variance::Invariant,
name: Id(Pos::NONE, "T".to_string()),
parameters: vec![Tparam {
variance: Variance::Invariant,
name: Id(Pos::NONE, "TInner".to_string()),
parameters: vec![],
constraints: vec![],
reified: ReifyKind::Erased,
user_attributes: UserAttributes::default(),
}],
constraints: vec![],
reified: ReifyKind::Erased,
user_attributes: UserAttributes::default(),
};
elem.transform(&env_hkt_enabled, &mut pass);
assert!(!elem.parameters.is_empty());
assert_eq!(env_hkt_enabled.into_errors().len(), 0);
elem.transform(&env_hkt_disabled, &mut pass);
assert!(elem.parameters.is_empty());
assert_eq!(env_hkt_disabled.into_errors().len(), 1);
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/elab_shape_field_name.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 nast::Class_;
use nast::Expr_;
use nast::ShapeFieldInfo;
use nast::ShapeFieldName;
use crate::prelude::*;
#[derive(Clone, Default)]
pub struct ElabShapeFieldNamePass {
current_class: Option<Rc<String>>,
}
impl ElabShapeFieldNamePass {
pub fn in_class(&mut self, cls: &Class_) {
self.current_class = Some(Rc::new(cls.name.name().to_string()));
}
}
impl Pass for ElabShapeFieldNamePass {
fn on_ty_class__top_down(&mut self, _: &Env, elem: &mut Class_) -> ControlFlow<()> {
self.in_class(elem);
Continue(())
}
fn on_ty_expr__bottom_up(&mut self, env: &Env, elem: &mut Expr_) -> ControlFlow<()> {
match elem {
Expr_::Shape(fields) => fields
.iter_mut()
.for_each(|(nm, _)| canonical_shape_name(env, nm, self.current_class.as_deref())),
_ => (),
}
Continue(())
}
fn on_ty_shape_field_info_bottom_up(
&mut self,
env: &Env,
elem: &mut ShapeFieldInfo,
) -> ControlFlow<()> {
canonical_shape_name(env, &mut elem.name, self.current_class.as_deref());
Continue(())
}
}
fn canonical_shape_name(env: &Env, nm: &mut ShapeFieldName, current_class: Option<&String>) {
match (nm, current_class) {
(ShapeFieldName::SFclassConst(id, _), Some(cls_nm)) if id.name() == sn::classes::SELF => {
id.1 = cls_nm.to_string();
}
(ShapeFieldName::SFclassConst(id, _), _) if id.name() == sn::classes::SELF => {
env.emit_error(NamingError::SelfOutsideClass(id.0.clone()));
id.1 = sn::classes::UNKNOWN.to_string();
}
_ => (),
}
}
#[cfg(test)]
mod tests {
use nast::Hint;
use nast::Hint_;
use nast::Id;
use nast::Pos;
use super::*;
// -- Valid cases ----------------------------------------------------------
#[test]
fn test_shape_in_class() {
let env = Env::default();
let class_name = "Classy";
let mut pass = ElabShapeFieldNamePass {
current_class: Some(Rc::new(class_name.to_string())),
};
let mut elem = Expr_::Shape(vec![(
ShapeFieldName::SFclassConst(
Id(Pos::default(), sn::classes::SELF.to_string()),
(Pos::default(), String::default()),
),
elab_utils::expr::null(),
)]);
elem.transform(&env, &mut pass);
// Expect no errors
assert!(env.into_errors().is_empty());
assert!(if let Expr_::Shape(mut fields) = elem {
let field_opt = fields.pop();
match field_opt {
Some((ShapeFieldName::SFclassConst(id, _), _)) => id.name() == class_name,
_ => false,
}
} else {
false
})
}
#[test]
fn test_shape_field_info_in_class() {
let env = Env::default();
let class_name = "Classy";
let mut pass = ElabShapeFieldNamePass {
current_class: Some(Rc::new(class_name.to_string())),
};
let mut elem = ShapeFieldInfo {
optional: Default::default(),
hint: Hint(Pos::default(), Box::new(Hint_::Herr)),
name: ShapeFieldName::SFclassConst(
Id(Pos::default(), sn::classes::SELF.to_string()),
(Pos::default(), String::default()),
),
};
elem.transform(&env, &mut pass);
// Expect no errors
assert!(env.into_errors().is_empty());
assert!(match elem.name {
ShapeFieldName::SFclassConst(id, _) => id.name() == class_name,
_ => false,
})
}
// -- Invalid cases --------------------------------------------------------
#[test]
fn test_shape_not_in_class() {
let env = Env::default();
let mut pass = ElabShapeFieldNamePass::default();
let mut elem = Expr_::Shape(vec![(
ShapeFieldName::SFclassConst(
Id(Pos::default(), sn::classes::SELF.to_string()),
(Pos::default(), String::default()),
),
elab_utils::expr::null(),
)]);
elem.transform(&env, &mut pass);
let self_outside_class_err_opt = env.into_errors().pop();
assert!(matches!(
self_outside_class_err_opt,
Some(NamingPhaseError::Naming(NamingError::SelfOutsideClass(..)))
));
assert!(if let Expr_::Shape(mut fields) = elem {
let field_opt = fields.pop();
match field_opt {
Some((ShapeFieldName::SFclassConst(id, _), _)) => id.name() == sn::classes::UNKNOWN,
_ => false,
}
} else {
false
})
}
#[test]
fn test_shape_field_info_not_in_class() {
let env = Env::default();
let mut pass = ElabShapeFieldNamePass::default();
let mut elem = ShapeFieldInfo {
optional: Default::default(),
hint: Hint(Pos::default(), Box::new(Hint_::Herr)),
name: ShapeFieldName::SFclassConst(
Id(Pos::default(), sn::classes::SELF.to_string()),
(Pos::default(), String::default()),
),
};
elem.transform(&env, &mut pass);
let self_outside_class_err_opt = env.into_errors().pop();
assert!(matches!(
self_outside_class_err_opt,
Some(NamingPhaseError::Naming(NamingError::SelfOutsideClass(..)))
));
assert!(match elem.name {
ShapeFieldName::SFclassConst(id, _) => id.name() == sn::classes::UNKNOWN,
_ => false,
})
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/elab_user_attributes.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 hash::HashMap;
use nast::Id;
use nast::Pos;
use nast::UserAttributes;
use crate::prelude::*;
#[derive(Clone, Copy, Default)]
pub struct ElabUserAttributesPass;
impl Pass for ElabUserAttributesPass {
fn on_ty_user_attributes_top_down(
&mut self,
env: &Env,
elem: &mut UserAttributes,
) -> ControlFlow<()> {
let mut seen: HashMap<String, Pos> = HashMap::default();
let UserAttributes(uas) = elem;
uas.retain(|ua| {
let Id(pos, attr_name) = &ua.name;
if let Some(prev_pos) = seen.get(attr_name) {
env.emit_error(NamingError::DuplicateUserAttribute {
pos: pos.clone(),
attr_name: attr_name.clone(),
prev_pos: prev_pos.clone(),
});
false
} else {
seen.insert(attr_name.clone(), pos.clone());
true
}
});
Continue(())
}
}
#[cfg(test)]
mod tests {
use nast::UserAttribute;
use super::*;
// Elaboration of CIexpr(..,..,Id(..,..)) when the id refers to a class
#[test]
fn test_ciexpr_id_class_ref() {
let env = Env::default();
let mut pass = ElabUserAttributesPass;
let mut elem = UserAttributes(vec![
UserAttribute {
name: Id(Pos::NONE, "One".to_string()),
params: vec![],
},
UserAttribute {
name: Id(Pos::NONE, "Two".to_string()),
params: vec![],
},
UserAttribute {
name: Id(Pos::NONE, "One".to_string()),
params: vec![],
},
UserAttribute {
name: Id(Pos::NONE, "Two".to_string()),
params: vec![],
},
UserAttribute {
name: Id(Pos::NONE, "One".to_string()),
params: vec![],
},
UserAttribute {
name: Id(Pos::NONE, "Two".to_string()),
params: vec![],
},
]);
elem.transform(&env, &mut pass);
assert_eq!(elem.len(), 2);
assert_eq!(env.into_errors().len(), 4);
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/guard_invalid.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 nast::Expr_;
use crate::prelude::*;
#[derive(Clone, Copy, Default)]
pub struct GuardInvalidPass;
impl Pass for GuardInvalidPass {
fn on_ty_expr__top_down(&mut self, _: &Env, elem: &mut Expr_) -> ControlFlow<()> {
if matches!(elem, Expr_::Invalid(..)) {
Break(())
} else {
Continue(())
}
}
}
#[cfg(test)]
mod tests {
use nast::Binop;
use nast::Bop;
use nast::Expr;
use nast::Expr_;
use nast::Pos;
use super::*;
#[derive(Clone)]
pub struct RewriteZero;
impl Pass for RewriteZero {
fn on_ty_expr__bottom_up(&mut self, _: &Env, elem: &mut Expr_) -> ControlFlow<()> {
match elem {
Expr_::Int(..) => *elem = Expr_::Int("0".to_string()),
_ => (),
}
Continue(())
}
}
#[test]
fn test() {
let env = Env::default();
let mut pass = passes![GuardInvalidPass, RewriteZero];
let mut elem = Expr_::Binop(Box::new(Binop {
bop: Bop::Lt,
lhs: Expr(
(),
Pos::NONE,
Expr_::Invalid(Box::new(Some(Expr(
(),
Pos::NONE,
Expr_::Int("42".to_string()),
)))),
),
rhs: Expr((), Pos::NONE, Expr_::Int("43".to_string())),
}));
elem.transform(&env, &mut pass);
assert!(matches!(
elem,
Expr_::Binop(box Binop{
lhs:Expr(_, _, Expr_::Invalid(box Some(Expr(_, _, Expr_::Int(n))))),
rhs:Expr(_, _, Expr_::Int(m)),
..
})
if n == "42" && m == "0"
));
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/remove_memo_attr.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 crate::prelude::*;
#[derive(Clone, Copy, Default)]
pub struct RemoveMemoAttr {}
impl Pass for RemoveMemoAttr {
fn on_ty_fun__top_down(&mut self, _: &Env, elem: &mut nast::Fun_) -> ControlFlow<()> {
remove_memo_attr(&mut elem.user_attributes);
Continue(())
}
fn on_ty_method__top_down(&mut self, _: &Env, elem: &mut nast::Method_) -> ControlFlow<()> {
remove_memo_attr(&mut elem.user_attributes);
Continue(())
}
}
/// Removes any memoization attributes
fn remove_memo_attr(input_attrs: &mut nast::UserAttributes) {
input_attrs
.0
.retain(|attr| !sn::user_attributes::is_memoized(attr.name.name()));
} |
Rust | hhvm/hphp/hack/src/elab/passes/validate_class_consistent_construct.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 nast::Class_;
use nast::ClassishKind;
use crate::prelude::*;
#[derive(Clone, Copy, Default)]
pub struct ValidateClassConsistentConstructPass;
impl Pass for ValidateClassConsistentConstructPass {
fn on_ty_class__top_down(&mut self, env: &Env, class: &mut Class_) -> ControlFlow<()> {
if env.consistent_ctor_level <= 0 {
return Continue(());
}
let attr_pos_opt = class
.user_attributes
.iter()
.find(|ua| ua.name.name() == sn::user_attributes::CONSISTENT_CONSTRUCT)
.map(|ua| ua.name.pos());
let has_ctor = class
.methods
.iter()
.any(|m| m.name.name() == sn::members::__CONSTRUCT);
match attr_pos_opt {
// If this classish is attributed `__ConsistentConstruct` & does not
// define a constructor then, if either it's a trait or
// `consistent_ctor_level` > 1, it's an error.
Some(pos)
if !has_ctor
&& (class.kind == ClassishKind::Ctrait || env.consistent_ctor_level > 1) =>
{
env.emit_error(NamingError::ExplicitConsistentConstructor {
classish_kind: class.kind,
pos: pos.clone(),
})
}
_ => (),
}
Continue(())
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/validate_class_member.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 nast::Class_;
use nast::Id;
use nast::Pos;
use nast::Sid;
use crate::prelude::*;
#[derive(Clone, Copy, Default)]
pub struct ValidateClassMemberPass;
impl Pass for ValidateClassMemberPass {
fn on_ty_class__bottom_up(&mut self, env: &Env, class: &mut Class_) -> ControlFlow<()> {
let typeconst_names = class.typeconsts.iter().map(|tc| &tc.name);
let const_names = class.consts.iter().map(|c| &c.id);
error_if_repeated_name(env, typeconst_names.chain(const_names));
Continue(())
}
}
// We use the same namespace as constants within the class so we cannot have
// a const and type const with the same name.
fn error_if_repeated_name<'a>(env: &Env, names: impl Iterator<Item = &'a Sid>) {
let mut seen = hash::HashMap::<&str, Pos>::default();
for Id(pos, name) in names {
if let Some(prev_pos) = seen.insert(name, pos.clone()) {
env.emit_error(NamingError::ErrorNameAlreadyBound {
pos: pos.clone(),
prev_pos: prev_pos.clone(),
name: name.clone(),
});
}
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use nast::Abstraction;
use nast::ClassConcreteTypeconst;
use nast::ClassConst;
use nast::ClassConstKind;
use nast::ClassTypeconst;
use nast::ClassTypeconstDef;
use nast::ClassishKind;
use nast::Id;
use nast::Pos;
use nast::UserAttributes;
use oxidized::namespace_env;
use oxidized::typechecker_options::TypecheckerOptions;
use super::*;
use crate::env::ProgramSpecificOptions;
fn mk_class_const(name: String) -> ClassConst {
ClassConst {
user_attributes: UserAttributes::default(),
type_: None,
id: Id(Pos::NONE, name),
kind: ClassConstKind::CCConcrete(elab_utils::expr::null()),
span: Pos::NONE,
doc_comment: None,
}
}
fn mk_class_typeconst(name: String) -> ClassTypeconstDef {
ClassTypeconstDef {
user_attributes: UserAttributes::default(),
name: Id(Pos::NONE, name),
kind: ClassTypeconst::TCConcrete(ClassConcreteTypeconst {
c_tc_type: elab_utils::hint::null(),
}),
span: Pos::NONE,
doc_comment: None,
is_ctx: false,
}
}
fn mk_class(
name: String,
consts: Vec<ClassConst>,
typeconsts: Vec<ClassTypeconstDef>,
) -> Class_ {
Class_ {
span: Pos::NONE,
annotation: (),
mode: file_info::Mode::Mstrict,
final_: false,
is_xhp: false,
has_xhp_keyword: false,
kind: ClassishKind::Cclass(Abstraction::Concrete),
name: Id(Pos::NONE, name),
tparams: vec![],
extends: vec![],
uses: vec![],
xhp_attr_uses: vec![],
xhp_category: None,
reqs: vec![],
implements: vec![],
where_constraints: vec![],
consts,
typeconsts,
vars: vec![],
methods: vec![],
xhp_children: vec![],
xhp_attrs: vec![],
namespace: Arc::new(namespace_env::Env::empty(vec![], false, false)),
user_attributes: Default::default(),
file_attributes: vec![],
docs_url: None,
enum_: None,
doc_comment: None,
emit_id: None,
internal: false,
module: None,
}
}
#[test]
fn test_class_constant_names_clash() {
let env = Env::new(
&TypecheckerOptions::default(),
&ProgramSpecificOptions::default(),
);
let mut class = mk_class(
"Foo".to_string(),
vec![mk_class_const("FOO".to_string())],
vec![mk_class_typeconst("FOO".to_string())],
);
class.transform(&env, &mut ValidateClassMemberPass);
assert!(matches!(
env.into_errors().as_slice(),
[NamingPhaseError::Naming(
NamingError::ErrorNameAlreadyBound { .. }
)]
));
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/validate_class_methods.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 hash::HashSet;
use nast::Class_;
use nast::Id;
use nast::Method_;
use crate::prelude::*;
#[derive(Clone, Copy, Default)]
pub struct ValidateClassMethodsPass;
impl Pass for ValidateClassMethodsPass {
fn on_ty_class__bottom_up(&mut self, env: &Env, class: &mut Class_) -> ControlFlow<()> {
let mut seen = HashSet::<&str>::default();
for method in class.methods.iter() {
let Id(pos, name) = &method.name;
if seen.contains(name as &str) {
env.emit_error(NamingError::MethodNameAlreadyBound {
pos: pos.clone(),
meth_name: name.clone(),
});
}
seen.insert(name);
}
Continue(())
}
fn on_ty_method__bottom_up(&mut self, env: &Env, method: &mut Method_) -> ControlFlow<()> {
if method.abstract_
&& method.user_attributes.iter().any(|attr| {
let Id(_, ua) = &attr.name;
ua == sn::user_attributes::MEMOIZE || ua == sn::user_attributes::MEMOIZE_LSB
})
{
env.emit_error(NastCheckError::AbstractMethodMemoize(
method.name.pos().clone(),
))
}
Continue(())
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use nast::Abstraction;
use nast::Block;
use nast::ClassishKind;
use nast::FunKind;
use nast::FuncBody;
use nast::Id;
use nast::Pos;
use nast::TypeHint;
use nast::UserAttribute;
use nast::UserAttributes;
use nast::Visibility;
use oxidized::namespace_env;
use oxidized::typechecker_options::TypecheckerOptions;
use super::*;
use crate::env::ProgramSpecificOptions;
fn mk_method(name: String, r#abstract: bool, attrs: Vec<UserAttribute>) -> Method_ {
Method_ {
span: Pos::NONE,
annotation: (),
final_: false,
abstract_: r#abstract,
static_: true,
readonly_this: false,
visibility: Visibility::Public,
name: Id(Pos::NONE, name),
tparams: vec![],
where_constraints: vec![],
params: vec![],
ctxs: None,
unsafe_ctxs: None,
body: FuncBody {
fb_ast: Block(vec![]),
},
fun_kind: FunKind::FSync,
user_attributes: UserAttributes(attrs),
readonly_ret: None,
ret: TypeHint((), None),
external: false,
doc_comment: None,
}
}
fn mk_class(name: String, methods: Vec<Method_>) -> Class_ {
Class_ {
span: Pos::NONE,
annotation: (),
mode: file_info::Mode::Mstrict,
final_: false,
is_xhp: false,
has_xhp_keyword: false,
kind: ClassishKind::Cclass(Abstraction::Concrete),
name: Id(Pos::NONE, name),
tparams: vec![],
extends: vec![],
uses: vec![],
xhp_attr_uses: vec![],
xhp_category: None,
reqs: vec![],
implements: vec![],
where_constraints: vec![],
consts: vec![],
typeconsts: vec![],
vars: vec![],
methods,
xhp_children: vec![],
xhp_attrs: vec![],
namespace: Arc::new(namespace_env::Env::empty(vec![], false, false)),
user_attributes: Default::default(),
file_attributes: vec![],
docs_url: None,
enum_: None,
doc_comment: None,
emit_id: None,
internal: false,
module: None,
}
}
#[test]
fn test_multiply_bound_method_name() {
let env = Env::new(
&TypecheckerOptions::default(),
&ProgramSpecificOptions::default(),
);
let m = mk_method("foo".to_string(), false, vec![]);
let n = mk_method("foo".to_string(), false, vec![]);
let mut class = mk_class("Foo".to_string(), vec![m, n]);
class.transform(&env, &mut ValidateClassMethodsPass);
assert!(matches!(
env.into_errors().as_slice(),
[NamingPhaseError::Naming(
NamingError::MethodNameAlreadyBound { .. }
)]
));
}
#[test]
fn test_abstract_memoized_method() {
let env = Env::new(
&TypecheckerOptions::default(),
&ProgramSpecificOptions::default(),
);
let memoized_attr = UserAttribute {
name: Id(Pos::NONE, sn::user_attributes::MEMOIZE.to_string()),
params: vec![],
};
let mut method = mk_method("foo".to_string(), true, vec![memoized_attr]);
method.transform(&env, &mut ValidateClassMethodsPass);
assert!(matches!(
env.into_errors().as_slice(),
[NamingPhaseError::NastCheck(
NastCheckError::AbstractMethodMemoize(_)
)]
));
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/validate_class_req.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 nast::ClassReq;
use nast::Class_;
use nast::ClassishKind;
use nast::Hint;
use nast::RequireKind;
use crate::prelude::*;
#[derive(Clone, Copy, Default)]
pub struct ValidateClassReqPass;
impl Pass for ValidateClassReqPass {
fn on_ty_class__top_down(&mut self, env: &Env, cls: &mut Class_) -> ControlFlow<()> {
let is_trait = cls.kind == ClassishKind::Ctrait;
let is_interface = cls.kind == ClassishKind::Cinterface;
let find_req = |kind| cls.reqs.iter().find(|&&ClassReq(_, k)| k == kind);
// `require implements` and `require class` are only allowed in traits.
if !is_trait {
if let Some(ClassReq(Hint(pos, _), _)) = find_req(RequireKind::RequireImplements) {
env.emit_error(NamingError::InvalidRequireImplements(pos.clone()));
}
if let Some(ClassReq(Hint(pos, _), _)) = find_req(RequireKind::RequireClass) {
env.emit_error(NamingError::InvalidRequireClass(pos.clone()));
}
}
// `require extends` is only allowed in traits and interfaces, so if
// this classish is neither that's an error.
if !(is_trait || is_interface) {
if let Some(ClassReq(Hint(pos, _), _)) = find_req(RequireKind::RequireExtends) {
env.emit_error(NamingError::InvalidRequireExtends(pos.clone()));
}
}
Continue(())
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/validate_class_tparams.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 nast::ClassTypeconstDef;
use nast::Class_;
use nast::Hint;
use nast::Hint_;
use nast::Id;
use crate::prelude::*;
#[derive(Clone, Default)]
pub struct ValidateClassTparamsPass {
class_tparams: Option<Rc<Vec<Id>>>,
in_typeconst_def: bool,
}
impl Pass for ValidateClassTparamsPass {
fn on_ty_class__top_down(&mut self, _: &Env, elem: &mut Class_) -> ControlFlow<()> {
self.class_tparams = Some(Rc::new(
elem.tparams.iter().map(|tp| tp.name.clone()).collect(),
));
Continue(())
}
fn on_ty_class_typeconst_def_top_down(
&mut self,
_: &Env,
_: &mut ClassTypeconstDef,
) -> ControlFlow<()> {
self.in_typeconst_def = true;
Continue(())
}
fn on_ty_hint_top_down(&mut self, env: &Env, elem: &mut Hint) -> ControlFlow<()> {
if self.in_typeconst_def {
match &*elem.1 {
Hint_::Habstr(tp_name, _) => {
if let Some(class_tparams) = &self.class_tparams {
class_tparams
.iter()
.filter(|tp| tp.name() == tp_name)
.for_each(|tp| {
env.emit_error(NastCheckError::TypeconstDependsOnExternalTparam {
pos: elem.0.clone(),
ext_pos: tp.pos().clone(),
ext_name: tp.name().to_string(),
})
})
}
}
_ => (),
}
}
Continue(())
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/validate_class_user_attribute_const.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 nast::Class_;
use nast::Pos;
use nast::UserAttributes;
use crate::prelude::*;
#[derive(Clone, Copy, Default)]
pub struct ValidateClassUserAttributeConstPass;
impl Pass for ValidateClassUserAttributeConstPass {
fn on_ty_class__bottom_up(&mut self, env: &Env, elem: &mut Class_) -> ControlFlow<()> {
if !env.const_attribute() {
// Disallow `__Const` attribute unless typechecker option is enabled
check_const(env, elem.name.pos(), &elem.user_attributes);
elem.vars
.iter()
.for_each(|cv| check_const(env, elem.name.pos(), &cv.user_attributes));
}
Continue(())
}
}
fn check_const(env: &Env, pos: &Pos, attrs: &UserAttributes) {
if attrs
.0
.iter()
.any(|ua| ua.name.name() == sn::user_attributes::CONST)
{
env.emit_error(ExperimentalFeature::ConstAttr(pos.clone()))
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/validate_class_var_user_attribute_const.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 nast::ClassVar;
use nast::Pos;
use nast::UserAttributes;
use crate::prelude::*;
#[derive(Clone, Copy, Default)]
pub struct ValidateClassVarUserAttributeConstPass;
impl Pass for ValidateClassVarUserAttributeConstPass {
fn on_ty_class_var_bottom_up(&mut self, env: &Env, elem: &mut ClassVar) -> ControlFlow<()> {
if !env.const_static_props() && elem.is_static {
check_const(env, elem.id.pos(), &elem.user_attributes)
}
Continue(())
}
}
fn check_const(env: &Env, pos: &Pos, attrs: &UserAttributes) {
if attrs
.0
.iter()
.any(|ua| ua.name.name() == sn::user_attributes::CONST)
{
env.emit_error(ExperimentalFeature::ConstStaticProp(pos.clone()))
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/validate_class_var_user_attribute_lsb.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 nast::ClassVar;
use nast::Id;
use crate::prelude::*;
#[derive(Clone, Default)]
pub struct ValidateClassVarUserAttributeLsbPass {
final_class: Option<Rc<Id>>,
}
impl Pass for ValidateClassVarUserAttributeLsbPass {
fn on_ty_class__top_down(&mut self, _: &Env, elem: &mut nast::Class_) -> ControlFlow<()> {
self.final_class = if elem.final_ {
Some(Rc::new(elem.name.clone()))
} else {
None
};
Continue(())
}
fn on_ty_class_var_bottom_up(&mut self, env: &Env, elem: &mut ClassVar) -> ControlFlow<()> {
if let Some(ua) = elem
.user_attributes
.0
.iter()
.find(|ua| ua.name.name() == sn::user_attributes::LSB)
{
// Non-static properties cannot have attribute `__LSB`
if !elem.is_static {
env.emit_error(NamingError::NonstaticPropertyWithLsb(ua.name.pos().clone()))
}
// `__LSB` attribute is unnecessary in final classes
if let Some(id) = &self.final_class {
env.emit_error(NamingError::UnnecessaryAttribute {
pos: ua.name.pos().clone(),
attr: sn::user_attributes::LSB.to_string(),
class_pos: id.pos().clone(),
class_name: id.name().to_string(),
suggestion: None,
});
}
}
Continue(())
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/validate_control_context.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 nast::Expr_;
use nast::FinallyBlock;
use nast::Stmt;
use nast::Stmt_;
use crate::prelude::*;
#[derive(Copy, Clone)]
enum ControlContext {
TopLevel,
Loop,
Switch,
}
impl Default for ControlContext {
fn default() -> Self {
Self::TopLevel
}
}
#[derive(Copy, Clone, Default)]
pub struct ValidateControlContextPass {
control_context: ControlContext,
in_finally_block: bool,
}
impl Pass for ValidateControlContextPass {
fn on_ty_stmt_bottom_up(&mut self, env: &Env, elem: &mut Stmt) -> ControlFlow<()> {
match (&elem.1, self.control_context) {
(Stmt_::Break, ControlContext::TopLevel) => {
env.emit_error(NastCheckError::ToplevelBreak(elem.0.clone()))
}
(Stmt_::Continue, ControlContext::TopLevel) => {
env.emit_error(NastCheckError::ToplevelContinue(elem.0.clone()))
}
(Stmt_::Continue, ControlContext::Switch) => {
env.emit_error(NastCheckError::ContinueInSwitch(elem.0.clone()))
}
(Stmt_::Return(..), _) if self.in_finally_block => {
env.emit_error(NastCheckError::ReturnInFinally(elem.0.clone()))
}
_ => (),
}
Continue(())
}
fn on_ty_stmt__top_down(&mut self, _: &Env, elem: &mut Stmt_) -> ControlFlow<()> {
match elem {
Stmt_::Do(..) | Stmt_::While(..) | Stmt_::For(..) | Stmt_::Foreach(..) => {
self.control_context = ControlContext::Loop
}
Stmt_::Switch(..) => self.control_context = ControlContext::Switch,
_ => (),
}
Continue(())
}
fn on_ty_finally_block_top_down(&mut self, _: &Env, _: &mut FinallyBlock) -> ControlFlow<()> {
self.in_finally_block = true;
Continue(())
}
fn on_ty_expr__top_down(&mut self, _: &Env, elem: &mut Expr_) -> ControlFlow<()> {
match elem {
Expr_::Efun(..) | Expr_::Lfun(..) => {
self.control_context = ControlContext::TopLevel;
self.in_finally_block = false
}
_ => (),
}
Continue(())
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/validate_coroutine.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 bitflags::bitflags;
use nast::AsExpr;
use nast::Expr;
use nast::Expr_;
use nast::FunDef;
use nast::FunKind;
use nast::Fun_;
use nast::Method_;
use nast::Pos;
use nast::Stmt;
use nast::Stmt_;
use nast::UsingStmt;
use crate::prelude::*;
#[derive(Clone, Default)]
pub struct ValidateCoroutinePass {
func_pos: Option<Pos>,
flags: Flags,
}
bitflags! {
#[derive(Default)]
struct Flags: u8 {
const IS_SYNC = 1 << 0;
const IS_GENERATOR = 1 << 1;
}
}
impl ValidateCoroutinePass {
fn set_fun_kind(&mut self, fun_kind: FunKind) {
self.flags.set(
Flags::IS_SYNC,
[FunKind::FGenerator, FunKind::FSync].contains(&fun_kind),
);
self.flags.set(
Flags::IS_GENERATOR,
[FunKind::FGenerator, FunKind::FAsyncGenerator].contains(&fun_kind),
);
}
fn is_sync(&self) -> bool {
self.flags.contains(Flags::IS_SYNC)
}
fn is_generator(&self) -> bool {
self.flags.contains(Flags::IS_GENERATOR)
}
}
impl Pass for ValidateCoroutinePass {
fn on_ty_stmt_bottom_up(&mut self, env: &Env, elem: &mut Stmt) -> ControlFlow<()> {
match &elem.1 {
Stmt_::Using(box UsingStmt {
has_await, exprs, ..
}) if *has_await && self.is_sync() => {
env.emit_error(NastCheckError::AwaitInSyncFunction {
pos: exprs.0.clone(),
func_pos: None,
})
}
Stmt_::Foreach(box (_, AsExpr::AwaitAsV(pos, _) | AsExpr::AwaitAsKv(pos, _, _), _))
if self.is_sync() =>
{
env.emit_error(NastCheckError::AwaitInSyncFunction {
pos: pos.clone(),
func_pos: None,
})
}
Stmt_::Awaitall(..) if self.is_sync() => {
env.emit_error(NastCheckError::AwaitInSyncFunction {
pos: elem.0.clone(),
func_pos: None,
})
}
Stmt_::Return(box Some(_)) if self.is_generator() => {
env.emit_error(NastCheckError::ReturnInGen(elem.0.clone()))
}
_ => (),
}
Continue(())
}
fn on_ty_expr_bottom_up(&mut self, env: &Env, elem: &mut Expr) -> ControlFlow<()> {
match elem.2 {
Expr_::Await(..) if self.is_sync() => {
env.emit_error(NastCheckError::AwaitInSyncFunction {
pos: elem.1.clone(),
func_pos: self.func_pos.clone(),
})
}
_ => (),
}
Continue(())
}
fn on_ty_method__top_down(&mut self, _: &Env, elem: &mut Method_) -> ControlFlow<()> {
self.set_fun_kind(elem.fun_kind);
self.func_pos = Some(elem.name.pos().clone());
Continue(())
}
fn on_ty_fun_def_top_down(&mut self, _: &Env, elem: &mut FunDef) -> ControlFlow<()> {
self.func_pos = Some(elem.name.pos().clone());
Continue(())
}
fn on_ty_fun__top_down(&mut self, _: &Env, elem: &mut Fun_) -> ControlFlow<()> {
self.set_fun_kind(elem.fun_kind);
Continue(())
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/validate_dynamic_hint.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 nast::Expr_;
use nast::Hint;
use nast::Hint_;
use crate::prelude::*;
#[derive(Clone, Copy, Default)]
pub struct ValidateDynamicHintPass;
impl Pass for ValidateDynamicHintPass {
fn on_ty_expr__bottom_up(&mut self, env: &Env, expr: &mut Expr_) -> ControlFlow<()> {
match &*expr {
Expr_::Is(box (_, Hint(p, box Hint_::Hdynamic))) => {
env.emit_error(NamingError::DynamicHintDisallowed(p.clone()));
Continue(())
}
_ => Continue(()),
}
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/validate_expr_array_get.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 nast::Binop;
use nast::Expr;
use nast::Expr_;
use oxidized::ast_defs::Bop;
use crate::prelude::*;
#[derive(Copy, Clone, Default)]
pub struct ValidateExprArrayGetPass {
array_append_allowed: bool,
is_assignment: bool,
}
impl Pass for ValidateExprArrayGetPass {
fn on_ty_expr_bottom_up(&mut self, env: &Env, expr: &mut Expr) -> ControlFlow<()> {
match &expr.2 {
Expr_::ArrayGet(box (array_get_expr, None)) if !self.array_append_allowed => {
env.emit_error(NastCheckError::ReadingFromAppend(array_get_expr.1.clone()))
}
_ => (),
}
Continue(())
}
fn on_ty_expr__top_down(&mut self, _env: &Env, expr_: &mut Expr_) -> ControlFlow<()> {
match expr_ {
Expr_::ObjGet(..) | Expr_::ArrayGet(..) => self.array_append_allowed = false,
_ => (),
}
Continue(())
}
fn on_ty_binop_top_down(&mut self, _env: &Env, binop: &mut Binop) -> ControlFlow<()> {
if binop.bop == Bop::Eq(None) {
self.is_assignment = true;
}
Continue(())
}
fn on_fld_binop_lhs_top_down(&mut self, _env: &Env, _elem: &mut Expr) -> ControlFlow<()> {
self.array_append_allowed = self.is_assignment;
Continue(())
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/validate_expr_call_echo.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 nast::CallExpr;
use nast::Expr;
use nast::Expr_;
use nast::Id;
use crate::prelude::*;
#[derive(Clone, Copy, Default)]
pub struct ValidateExprCallEchoPass;
impl Pass for ValidateExprCallEchoPass {
fn on_ty_expr__bottom_up(&mut self, env: &Env, elem: &mut Expr_) -> ControlFlow<()> {
match elem {
Expr_::Call(box CallExpr {
func: Expr(_, _, Expr_::Id(box Id(_, fn_name))),
unpacked_arg: Some(Expr(_, pos, _)),
..
}) if fn_name == sn::special_functions::ECHO => {
env.emit_error(NamingError::TooFewTypeArguments(pos.clone()))
}
_ => (),
}
Continue(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_valid() {
let env = Env::default();
let mut pass = ValidateExprCallEchoPass;
let mut elem = Expr_::Call(Box::new(CallExpr {
func: Expr(
(),
elab_utils::pos::null(),
Expr_::Id(Box::new(Id(
elab_utils::pos::null(),
sn::special_functions::ECHO.to_string(),
))),
),
targs: vec![],
args: vec![],
unpacked_arg: None,
}));
elem.transform(&env, &mut pass);
assert!(env.into_errors().is_empty());
assert!(match elem {
Expr_::Call(cc) => {
let CallExpr {
func: Expr(_, _, expr_),
..
} = *cc;
match expr_ {
Expr_::Id(id) => {
let Id(_, nm) = *id;
nm == sn::special_functions::ECHO
}
_ => false,
}
}
_ => false,
})
}
#[test]
fn test_invalid() {
let env = Env::default();
let mut pass = ValidateExprCallEchoPass;
let mut elem = Expr_::Call(Box::new(CallExpr {
func: Expr(
(),
elab_utils::pos::null(),
Expr_::Id(Box::new(Id(
elab_utils::pos::null(),
sn::special_functions::ECHO.to_string(),
))),
),
targs: vec![],
args: vec![],
unpacked_arg: Some(elab_utils::expr::null()),
}));
elem.transform(&env, &mut pass);
assert_eq!(env.into_errors().len(), 1);
assert!(match elem {
Expr_::Call(cc) => {
let CallExpr {
func: Expr(_, _, expr_),
..
} = *cc;
match expr_ {
Expr_::Id(id) => {
let Id(_, nm) = *id;
nm == sn::special_functions::ECHO
}
_ => false,
}
}
_ => false,
})
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/validate_expr_cast.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 nast::Expr_;
use nast::Hint;
use nast::Hint_;
use nast::Id;
use nast::Tprim::*;
use crate::prelude::*;
#[derive(Clone, Copy, Default)]
pub struct ValidateExprCastPass;
impl Pass for ValidateExprCastPass {
fn on_ty_expr__bottom_up(&mut self, env: &Env, expr: &mut Expr_) -> ControlFlow<()> {
match &*expr {
Expr_::Cast(box (Hint(_, box Hint_::Hprim(Tint | Tbool | Tfloat | Tstring)), _)) => {
Continue(())
}
Expr_::Cast(box (Hint(_, box Hint_::Happly(Id(_, tycon_nm), _)), _))
if tycon_nm == sn::collections::DICT || tycon_nm == sn::collections::VEC =>
{
Continue(())
}
Expr_::Cast(box (Hint(_, box Hint_::HvecOrDict(_, _)), _)) => Continue(()),
// We end up with a `Hany` when we have an arity error for
// `dict`/`vec`--we don't error on this case to preserve behaviour.
Expr_::Cast(box (Hint(_, box Hint_::Hany), _)) => Continue(()),
Expr_::Cast(box (Hint(p, _), _)) => {
env.emit_error(NamingError::ObjectCast(p.clone()));
Continue(())
}
_ => Continue(()),
}
}
}
#[cfg(test)]
mod tests {
use nast::Expr;
use nast::Pos;
use super::*;
#[test]
fn test_invalid_cast() {
let mut expr: Expr = elab_utils::expr::from_expr_(Expr_::Cast(Box::new((
Hint(Pos::NONE, Box::new(Hint_::Hthis)),
elab_utils::expr::null(),
))));
let env = Env::default();
expr.transform(&env, &mut ValidateExprCastPass);
assert_eq!(env.into_errors().len(), 1);
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/validate_expr_function_pointer.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 nast::ClassId;
use nast::ClassId_;
use nast::Class_;
use nast::Expr_;
use nast::Hint;
use nast::Hint_;
use oxidized::ast::FunctionPtrId;
use crate::prelude::*;
#[derive(Clone, Default)]
pub struct ValidateExprFunctionPointerPass {
in_final_class: bool,
class_name: Option<Rc<String>>,
parent_name: Option<Rc<String>>,
is_trait: bool,
}
impl Pass for ValidateExprFunctionPointerPass {
fn on_ty_class__top_down(&mut self, _env: &Env, class_: &mut Class_) -> ControlFlow<()> {
self.in_final_class = class_.final_;
self.is_trait = class_.kind.is_ctrait();
self.class_name = Some(Rc::new(class_.name.name().to_string()));
self.parent_name = match class_.extends.as_slice() {
[Hint(_, box Hint_::Happly(id, _)), ..] => Some(Rc::new(id.name().to_string())),
_ => None,
};
ControlFlow::Continue(())
}
fn on_ty_expr__bottom_up(&mut self, env: &Env, expr: &mut Expr_) -> ControlFlow<()> {
match &expr {
Expr_::FunctionPointer(box (
FunctionPtrId::FPClassConst(ClassId(_, pos, class_id_), (_, meth_name)),
_,
)) => match class_id_ {
ClassId_::CIself if !self.in_final_class => {
env.emit_error(NamingError::SelfInNonFinalFunctionPointer {
pos: pos.clone(),
meth_name: meth_name.clone(),
class_name: if self.is_trait {
None
} else {
self.class_name.as_deref().cloned()
},
})
}
ClassId_::CIparent => env.emit_error(NamingError::ParentInFunctionPointer {
pos: pos.clone(),
meth_name: meth_name.clone(),
parent_name: self.parent_name.as_deref().cloned(),
}),
_ => (),
},
_ => (),
}
ControlFlow::Continue(())
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/validate_expr_list.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 nast::AsExpr;
use nast::Binop;
use nast::Expr;
use nast::Expr_;
use nast::Fun_;
use nast::Method_;
use oxidized::ast_defs::Bop;
use crate::prelude::*;
#[derive(Copy, Clone, Default)]
pub struct ValidateExprListPass {
in_fun_or_method: bool,
in_lvalue: bool,
is_assignment: bool,
}
impl Pass for ValidateExprListPass {
fn on_ty_binop_top_down(&mut self, _env: &Env, binop: &mut Binop) -> ControlFlow<()> {
if matches!(binop.bop, Bop::Eq(None)) {
self.is_assignment = true;
}
Continue(())
}
fn on_fld_binop_lhs_top_down(&mut self, _env: &Env, _elem: &mut Expr) -> ControlFlow<()> {
self.in_lvalue = true;
Continue(())
}
fn on_ty_as_expr_top_down(&mut self, _env: &Env, _elem: &mut AsExpr) -> ControlFlow<()> {
self.in_lvalue = true;
Continue(())
}
fn on_ty_expr_bottom_up(&mut self, env: &Env, expr: &mut Expr) -> ControlFlow<()> {
if matches!(expr.2, Expr_::List(..)) && !self.in_lvalue && self.in_fun_or_method {
env.emit_error(NastCheckError::ListRvalue(expr.1.clone()))
}
Continue(())
}
fn on_ty_fun__top_down(&mut self, _env: &Env, _elem: &mut Fun_) -> ControlFlow<()> {
self.in_fun_or_method = true;
self.in_lvalue = false;
Continue(())
}
fn on_ty_method__top_down(&mut self, _env: &Env, _elem: &mut Method_) -> ControlFlow<()> {
self.in_fun_or_method = true;
self.in_lvalue = false;
Continue(())
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/validate_fun_params.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 nast::FunParam;
use nast::Fun_;
use nast::Method_;
use crate::prelude::*;
#[derive(Clone, Copy, Default)]
pub struct ValidateFunParamsPass;
impl Pass for ValidateFunParamsPass {
fn on_ty_fun__top_down(&mut self, env: &Env, elem: &mut Fun_) -> ControlFlow<()> {
self.validate_fun_params(env, &elem.params)
}
fn on_ty_method__top_down(&mut self, env: &Env, elem: &mut Method_) -> ControlFlow<()> {
self.validate_fun_params(env, &elem.params)
}
}
impl ValidateFunParamsPass {
fn validate_fun_params(&self, env: &Env, params: &Vec<FunParam>) -> ControlFlow<()> {
let mut seen = std::collections::BTreeSet::<&String>::new();
for FunParam { name, pos, .. } in params {
if name == sn::special_idents::PLACEHOLDER {
continue;
} else if seen.contains(name) {
env.emit_error(NamingError::AlreadyBound {
pos: pos.clone(),
name: name.clone(),
});
} else {
seen.insert(name);
}
}
Continue(())
}
}
#[cfg(test)]
mod tests {
use nast::Block;
use nast::FunKind;
use nast::FuncBody;
use nast::Id;
use nast::ParamKind;
use nast::Pos;
use nast::TypeHint;
use nast::UserAttributes;
use nast::Visibility;
use super::*;
fn mk_fun(params: Vec<FunParam>) -> Fun_ {
Fun_ {
span: Pos::NONE,
readonly_this: None,
annotation: (),
readonly_ret: None,
ret: TypeHint((), None),
params,
ctxs: None,
unsafe_ctxs: None,
body: FuncBody {
fb_ast: Block(vec![]),
},
fun_kind: FunKind::FSync,
user_attributes: UserAttributes(vec![]),
external: false,
doc_comment: None,
}
}
fn mk_method(name: String, params: Vec<FunParam>) -> Method_ {
Method_ {
span: Pos::NONE,
annotation: (),
final_: false,
abstract_: false,
static_: true,
readonly_this: false,
visibility: Visibility::Public,
name: Id(Pos::NONE, name),
tparams: vec![],
where_constraints: vec![],
params,
ctxs: None,
unsafe_ctxs: None,
body: FuncBody {
fb_ast: Block(vec![]),
},
fun_kind: FunKind::FSync,
user_attributes: UserAttributes(vec![]),
readonly_ret: None,
ret: TypeHint((), None),
external: false,
doc_comment: None,
}
}
fn mk_param(name: String) -> FunParam {
FunParam {
name,
annotation: (),
type_hint: TypeHint((), None),
is_variadic: false,
pos: Pos::NONE,
expr: None,
readonly: None,
callconv: ParamKind::Pnormal,
user_attributes: UserAttributes(Vec::default()),
visibility: Some(Visibility::Public),
}
}
#[test]
fn test_fn_no_args() {
let env = Env::default();
let mut pass = ValidateFunParamsPass;
let mut fun = mk_fun(vec![]);
fun.transform(&env, &mut pass);
assert!(env.into_errors().is_empty())
}
#[test]
fn test_meth_no_args() {
let env = Env::default();
let mut pass = ValidateFunParamsPass;
let mut meth = mk_method("foo".to_string(), vec![]);
meth.transform(&env, &mut pass);
assert!(env.into_errors().is_empty())
}
#[test]
fn test_fn_good_args() {
let env = Env::default();
let mut pass = ValidateFunParamsPass;
let x = mk_param("x".to_string());
let y = mk_param("y".to_string());
let mut fun = mk_fun(vec![x, y]);
fun.transform(&env, &mut pass);
assert!(env.into_errors().is_empty())
}
#[test]
fn test_meth_good_args() {
let env = Env::default();
let mut pass = ValidateFunParamsPass;
let x = mk_param("x".to_string());
let y = mk_param("y".to_string());
let mut meth = mk_method("foo".to_string(), vec![x, y]);
meth.transform(&env, &mut pass);
assert!(env.into_errors().is_empty())
}
#[test]
fn test_fn_args_multiply_bound() {
let env = Env::default();
let mut pass = ValidateFunParamsPass;
let x = mk_param("x".to_string());
let mut fun = mk_fun(vec![x.clone(), x]);
fun.transform(&env, &mut pass);
assert!(matches!(
env.into_errors().as_slice(),
&[NamingPhaseError::Naming(NamingError::AlreadyBound { .. })]
))
}
#[test]
fn test_meth_args_multiply_bound() {
let env = Env::default();
let mut pass = ValidateFunParamsPass;
let x = mk_param("x".to_string());
let mut meth = mk_method("foo".to_string(), vec![x.clone(), x]);
meth.transform(&env, &mut pass);
assert!(matches!(
env.into_errors().as_slice(),
&[NamingPhaseError::Naming(NamingError::AlreadyBound { .. })]
))
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/validate_fun_param_inout.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 nast::FunDef;
use nast::FunParam;
use nast::Id;
use nast::Method_;
use nast::ParamKind;
use nast::UserAttributes;
use crate::prelude::*;
#[derive(Copy, Clone, Default)]
pub struct ValidateFunParamInoutPass;
impl Pass for ValidateFunParamInoutPass {
fn on_ty_fun_def_bottom_up(&mut self, env: &Env, elem: &mut FunDef) -> ControlFlow<()> {
check_params(env, &elem.name, &elem.fun.user_attributes, &elem.fun.params);
Continue(())
}
fn on_ty_method__bottom_up(&mut self, env: &Env, elem: &mut Method_) -> ControlFlow<()> {
check_params(env, &elem.name, &elem.user_attributes, &elem.params);
Continue(())
}
}
fn check_params(env: &Env, id: &Id, attrs: &UserAttributes, params: &[FunParam]) {
let in_as_set_function = sn::members::AS_LOWERCASE_SET.contains(id.name());
let has_memoize_user_attr = has_memoize_user_attr(attrs);
// We can skip the check entirely if neither condition is true since we would never
// raise an error
if in_as_set_function || has_memoize_user_attr {
let mut has_inout_param = None;
// iterate through _all_ parameter; raise an error for `inout` params
// if we are in a `as_set` function and record the position of the
// first such parameter we encounter. If we are in a memoized function,
// we also raise an error for the first parameter, if it exists
params.iter().for_each(|fp| {
if matches!(fp.callconv, ParamKind::Pinout(_)) {
if has_inout_param.is_none() {
has_inout_param = Some(fp.pos.clone());
}
if in_as_set_function {
env.emit_error(NastCheckError::InoutParamsSpecial(fp.pos.clone()))
}
}
});
if let Some(param_pos) = has_inout_param {
if has_memoize_user_attr {
env.emit_error(NastCheckError::InoutParamsMemoize {
pos: id.pos().clone(),
param_pos,
})
}
}
}
}
fn has_memoize_user_attr(attrs: &UserAttributes) -> bool {
attrs.0.iter().any(|ua| {
ua.name.name() == sn::user_attributes::MEMOIZE
|| ua.name.name() == sn::user_attributes::MEMOIZE_LSB
})
} |
Rust | hhvm/hphp/hack/src/elab/passes/validate_global_const.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 file_info::Mode;
use nast::Expr;
use nast::Expr_;
use nast::Gconst;
use nast::Id;
use crate::prelude::*;
#[derive(Clone, Copy, Default)]
pub struct ValidateGlobalConstPass;
impl Pass for ValidateGlobalConstPass {
fn on_ty_gconst_bottom_up(&mut self, env: &Env, gconst: &mut Gconst) -> ControlFlow<()> {
error_if_no_typehint(env, gconst);
error_if_pseudo_constant(env, gconst);
Continue(())
}
}
fn error_if_no_typehint(env: &Env, gconst: &Gconst) {
if !matches!(gconst.mode, Mode::Mhhi) && matches!(gconst.type_, None) {
let Expr(_, _, expr_) = &gconst.value;
let Id(pos, const_name) = &gconst.name;
let ty_name = match expr_ {
Expr_::String(_) => "string",
Expr_::Int(_) => "int",
Expr_::Float(_) => "float",
_ => "mixed",
};
env.emit_error(NamingError::ConstWithoutTypehint {
pos: pos.clone(),
const_name: const_name.clone(),
ty_name: ty_name.to_string(),
});
}
}
fn error_if_pseudo_constant(env: &Env, gconst: &Gconst) {
if gconst.namespace.name.is_some() {
let Id(pos, n) = &gconst.name;
let name = core_utils_rust::add_ns(core_utils_rust::strip_all_ns(n));
if sn::pseudo_consts::is_pseudo_const(&name) {
env.emit_error(NamingError::NameIsReserved {
pos: pos.clone(),
name: name.to_string(),
});
}
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use nast::Hint;
use nast::Pos;
use oxidized::namespace_env;
use oxidized::typechecker_options::TypecheckerOptions;
use super::*;
use crate::env::ProgramSpecificOptions;
fn mk_gconst(
name: String,
value: Expr,
r#type: Option<Hint>,
namespace: Option<String>,
) -> Gconst {
Gconst {
annotation: (),
mode: file_info::Mode::Mstrict,
name: Id(Pos::NONE, name),
value,
type_: r#type,
namespace: Arc::new(namespace_env::Env {
name: namespace,
..namespace_env::Env::empty(vec![], false, false)
}),
span: Pos::NONE,
emit_id: None,
}
}
#[test]
fn test_no_type_hint() {
let env = Env::new(
&TypecheckerOptions::default(),
&ProgramSpecificOptions::default(),
);
let mut r#const = mk_gconst("FOO".to_string(), elab_utils::expr::null(), None, None);
r#const.transform(&env, &mut ValidateGlobalConstPass);
assert!(matches!(
env.into_errors().as_slice(),
[NamingPhaseError::Naming(
NamingError::ConstWithoutTypehint { .. }
)]
));
}
#[test]
fn test_pseudo_constant() {
let env = Env::new(
&TypecheckerOptions::default(),
&ProgramSpecificOptions::default(),
);
let mut r#const = mk_gconst(
"\\A\\B\\C\\__CLASS__".to_string(),
elab_utils::expr::null(),
Some(elab_utils::hint::null()),
Some("Foo".to_string()),
);
r#const.transform(&env, &mut ValidateGlobalConstPass);
assert!(matches!(
env.into_errors().as_slice(),
[NamingPhaseError::Naming(NamingError::NameIsReserved { .. })]
));
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/validate_hint_habstr.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 bitflags::bitflags;
use hash::HashMap;
use nast::Class_;
use nast::FunDef;
use nast::Hint;
use nast::Hint_;
use nast::Method_;
use nast::Pos;
use nast::ReifyKind;
use nast::Tparam;
use nast::Typedef;
use nast::WhereConstraintHint;
use crate::prelude::*;
#[derive(Copy, Clone)]
enum TparamKind {
Concrete,
Higher,
}
#[derive(Clone, Default)]
pub struct ValidateHintHabstrPass {
tparam_info: Rc<HashMap<String, (Pos, bool, TparamKind)>>,
flags: Flags,
}
bitflags! {
#[derive(Default)]
struct Flags: u8 {
const IN_METHOD_OR_FUN = 1 << 0;
const IN_WHERE_CONSTRAINT = 1 << 1;
}
}
impl ValidateHintHabstrPass {
fn in_method_or_fun(&self) -> bool {
self.flags.contains(Flags::IN_METHOD_OR_FUN)
}
fn set_in_method_or_fun(&mut self, value: bool) {
self.flags.set(Flags::IN_METHOD_OR_FUN, value)
}
fn in_where_constraint(&self) -> bool {
self.flags.contains(Flags::IN_WHERE_CONSTRAINT)
}
fn set_in_where_constraint(&mut self, value: bool) {
self.flags.set(Flags::IN_WHERE_CONSTRAINT, value)
}
fn clear_tparams(&mut self) {
Rc::make_mut(&mut self.tparam_info).clear();
}
fn check_tparams(&mut self, env: &Env, tparams: &[Tparam], nested: bool) {
// Put each tparam in scope and record its kind; raise errors for
// shadowed tparams in scope and non-shadowing reuse of previously seen
// params of higher-kinded params
let tparam_info = Rc::make_mut(&mut self.tparam_info);
tparams
.iter()
.filter(|tp| tp.name.name() != sn::typehints::WILDCARD)
.for_each(|tp| {
match tparam_info.get(tp.name.name()) {
// Shadows either a tparam either previously bound in the current scope or bound at some outer scope
Some((prev_pos, true, _)) => env.emit_error(NamingError::ShadowedTparam {
pos: tp.name.pos().clone(),
tparam_name: tp.name.name().to_string(),
prev_pos: prev_pos.clone(),
}),
// Shares a name with a higher kind tparam which is not in scope
Some((_, false, _)) => env.emit_error(NamingError::TparamNonShadowingReuse {
pos: tp.name.pos().clone(),
tparam_name: tp.name.name().to_string(),
}),
_ => (),
}
let kind = if tp.parameters.is_empty() {
TparamKind::Concrete
} else {
TparamKind::Higher
};
tparam_info.insert(
tp.name.name().to_string(),
(tp.name.pos().clone(), true, kind),
);
});
tparams
.iter()
.for_each(|tp| self.check_tparam(env, tp, nested));
// if we are checking tparams of a higher-kinded tparams, remove them from scope
// but remember we have seen them for non-shadow reuse warnings
if nested {
let tparam_info = Rc::make_mut(&mut self.tparam_info);
tparams
.iter()
.filter(|tp| tp.name.name() != sn::typehints::WILDCARD)
.for_each(|tp| {
tparam_info
.entry(tp.name.name().to_string())
.and_modify(|e| e.1 = false)
.or_insert((tp.name.pos().clone(), false, TparamKind::Concrete));
});
}
}
fn check_tparam(&mut self, env: &Env, tparam: &Tparam, nested: bool) {
let is_hk = !tparam.parameters.is_empty();
let name = tparam.name.name();
let pos = tparam.name.pos();
// -- Errors related to parameter name ---------------------------------
// Raise an error if the lowercase tparam name is `this`
if name.to_lowercase() == sn::typehints::THIS {
env.emit_error(NamingError::ThisReserved(pos.clone()))
}
// Raise an error for wildcard top-level tparams
if name == sn::typehints::WILDCARD {
if !nested || is_hk {
env.emit_error(NamingError::WildcardTparamDisallowed(pos.clone()))
}
} else if name.is_empty() || !name.starts_with('T') {
env.emit_error(NamingError::StartWithT(pos.clone()))
}
// -- Errors related to features that are not supported in combination
// with higher kinded types
if !tparam.constraints.is_empty() {
if nested {
env.emit_error(NamingError::HKTUnsupportedFeature {
pos: pos.clone(),
because_nested: true,
var_name: name.to_string(),
feature: UnsupportedFeature::FtConstraints,
})
}
if is_hk {
env.emit_error(NamingError::HKTUnsupportedFeature {
pos: pos.clone(),
because_nested: false,
var_name: name.to_string(),
feature: UnsupportedFeature::FtConstraints,
})
}
}
if tparam.reified != ReifyKind::Erased {
if nested {
env.emit_error(NamingError::HKTUnsupportedFeature {
pos: pos.clone(),
because_nested: true,
var_name: name.to_string(),
feature: UnsupportedFeature::FtReification,
})
}
if is_hk {
env.emit_error(NamingError::HKTUnsupportedFeature {
pos: pos.clone(),
because_nested: false,
var_name: name.to_string(),
feature: UnsupportedFeature::FtReification,
})
}
}
if !tparam.user_attributes.is_empty() {
if nested {
env.emit_error(NamingError::HKTUnsupportedFeature {
pos: pos.clone(),
because_nested: true,
var_name: name.to_string(),
feature: UnsupportedFeature::FtUserAttrs,
})
}
if is_hk {
env.emit_error(NamingError::HKTUnsupportedFeature {
pos: pos.clone(),
because_nested: false,
var_name: name.to_string(),
feature: UnsupportedFeature::FtUserAttrs,
})
}
}
if !tparam.variance.is_invariant() {
if nested {
env.emit_error(NamingError::HKTUnsupportedFeature {
pos: pos.clone(),
because_nested: true,
var_name: name.to_string(),
feature: UnsupportedFeature::FtVariance,
})
}
if is_hk {
env.emit_error(NamingError::HKTUnsupportedFeature {
pos: pos.clone(),
because_nested: false,
var_name: name.to_string(),
feature: UnsupportedFeature::FtVariance,
})
}
}
self.check_tparams(env, &tparam.parameters, true)
}
}
// TODO[mjt] we're doing quite a bit of work here to support higher-kinded
// types which are pretty bit-rotted. We should make a call on removing
impl Pass for ValidateHintHabstrPass {
fn on_ty_class__top_down(&mut self, env: &Env, elem: &mut Class_) -> ControlFlow<()> {
// [Class_]es exist at the top level so there shouldn't be anything
// in scope but we clear anyway
self.clear_tparams();
// Validate class level tparams and bring them into scope
self.check_tparams(env, &elem.tparams, false);
Continue(())
}
fn on_ty_typedef_top_down(&mut self, env: &Env, elem: &mut Typedef) -> ControlFlow<()> {
// [Typedef]s exist at the top level so there shouldn't be anything
// in scope but we clear anyway
self.clear_tparams();
self.check_tparams(env, &elem.tparams, false);
Continue(())
}
fn on_ty_fun_def_top_down(&mut self, env: &Env, elem: &mut FunDef) -> ControlFlow<()> {
// FunDefs exist at the top level so there shouldn't be anything
// in scope but we clear anyway
self.clear_tparams();
self.check_tparams(env, &elem.tparams, false);
// We want to check hints inside where constraints for functions
// and methods only (i.e. not class level constraints) so we record
// this in the context
self.set_in_method_or_fun(true);
Continue(())
}
fn on_ty_method__top_down(&mut self, env: &Env, elem: &mut Method_) -> ControlFlow<()> {
// Validate method level tparams given the already in-scope
// class level tparams
self.check_tparams(env, &elem.tparams, false);
// We want to check hints inside where constraints for functions
// and methods only (i.e. not class level constraints) so we record
// this in the context
self.set_in_method_or_fun(true);
Continue(())
}
fn on_ty_where_constraint_hint_top_down(
&mut self,
_: &Env,
_: &mut WhereConstraintHint,
) -> ControlFlow<()> {
// We want to check hints inside function / method where constraints
// so we need to record this in the context
self.set_in_where_constraint(true);
Continue(())
}
fn on_ty_hint_top_down(&mut self, env: &Env, elem: &mut Hint) -> ControlFlow<()> {
// NB this relies on [Happly] -> [Habstr] elaboration happening
// in a preceeding top-down pass
if self.in_method_or_fun() && self.in_where_constraint() {
if let Hint(pos, box Hint_::Habstr(t, _)) = &elem {
if let Some((_, true, TparamKind::Higher)) = self.tparam_info.get(t) {
env.emit_error(NamingError::HKTUnsupportedFeature {
pos: pos.clone(),
because_nested: false,
var_name: t.clone(),
feature: UnsupportedFeature::FtWhereConstraints,
})
}
}
}
Continue(())
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use nast::Abstraction;
use nast::Block;
use nast::ClassishKind;
use nast::FuncBody;
use nast::Id;
use nast::TypeHint;
use nast::Variance;
use oxidized::namespace_env;
use super::*;
fn mk_class(tparams: Vec<Tparam>, methods: Vec<Method_>) -> Class_ {
Class_ {
span: Default::default(),
annotation: Default::default(),
mode: file_info::Mode::Mstrict,
final_: Default::default(),
is_xhp: Default::default(),
has_xhp_keyword: Default::default(),
kind: ClassishKind::Cclass(Abstraction::Concrete),
name: Default::default(),
tparams,
extends: Default::default(),
uses: Default::default(),
xhp_attr_uses: Default::default(),
xhp_category: Default::default(),
reqs: Default::default(),
implements: Default::default(),
where_constraints: Default::default(),
consts: Default::default(),
typeconsts: Default::default(),
vars: Default::default(),
methods,
xhp_children: Default::default(),
xhp_attrs: Default::default(),
namespace: Arc::new(namespace_env::Env::empty(vec![], false, false)),
user_attributes: Default::default(),
file_attributes: Default::default(),
docs_url: Default::default(),
enum_: Default::default(),
doc_comment: Default::default(),
emit_id: Default::default(),
internal: Default::default(),
module: Default::default(),
}
}
fn mk_method(tparams: Vec<Tparam>, where_constraints: Vec<WhereConstraintHint>) -> Method_ {
Method_ {
span: Default::default(),
annotation: Default::default(),
final_: Default::default(),
abstract_: Default::default(),
static_: Default::default(),
readonly_this: Default::default(),
visibility: nast::Visibility::Public,
name: Default::default(),
tparams,
where_constraints,
params: Default::default(),
ctxs: Default::default(),
unsafe_ctxs: Default::default(),
body: FuncBody {
fb_ast: Block(Default::default()),
},
fun_kind: nast::FunKind::FSync,
user_attributes: Default::default(),
readonly_ret: Default::default(),
ret: TypeHint(Default::default(), None),
external: Default::default(),
doc_comment: Default::default(),
}
}
#[test]
fn test_shadowed_class_member() {
let env = Env::default();
let mut pass = ValidateHintHabstrPass::default();
let tparam_class = Tparam {
variance: Variance::Invariant,
name: Id(Default::default(), "T".to_string()),
parameters: Default::default(),
constraints: Default::default(),
reified: ReifyKind::Erased,
user_attributes: Default::default(),
};
let meth = mk_method(vec![tparam_class.clone()], vec![]);
let mut elem = mk_class(vec![tparam_class], vec![meth]);
elem.transform(&env, &mut pass);
assert!(matches!(
env.into_errors().as_slice(),
&[NamingPhaseError::Naming(NamingError::ShadowedTparam { .. })]
));
}
#[test]
fn test_shadowed_member() {
let env = Env::default();
let mut pass = ValidateHintHabstrPass::default();
let tparam = Tparam {
variance: Variance::Invariant,
name: Id(Default::default(), "T".to_string()),
parameters: Default::default(),
constraints: Default::default(),
reified: ReifyKind::Erased,
user_attributes: Default::default(),
};
let mut elem = mk_method(vec![tparam.clone(), tparam], vec![]);
elem.transform(&env, &mut pass);
assert!(matches!(
env.into_errors().as_slice(),
&[NamingPhaseError::Naming(NamingError::ShadowedTparam { .. })]
));
}
#[test]
fn test_shadowed_class() {
let env = Env::default();
let mut pass = ValidateHintHabstrPass::default();
let tparam = Tparam {
variance: Variance::Invariant,
name: Id(Default::default(), "T".to_string()),
parameters: Default::default(),
constraints: Default::default(),
reified: ReifyKind::Erased,
user_attributes: Default::default(),
};
let mut elem = mk_class(vec![tparam.clone(), tparam], vec![]);
elem.transform(&env, &mut pass);
assert!(matches!(
env.into_errors().as_slice(),
&[NamingPhaseError::Naming(NamingError::ShadowedTparam { .. })]
));
}
#[test]
fn test_non_shadowed_reuse_class_member() {
let env = Env::default();
let mut pass = ValidateHintHabstrPass::default();
let tparam_concrete = Tparam {
variance: Variance::Invariant,
name: Id(Default::default(), "T".to_string()),
parameters: Default::default(),
constraints: Default::default(),
reified: ReifyKind::Erased,
user_attributes: Default::default(),
};
let tparam_higher = Tparam {
variance: Variance::Invariant,
name: Id(Default::default(), "TH".to_string()),
parameters: vec![tparam_concrete.clone()],
constraints: Default::default(),
reified: ReifyKind::Erased,
user_attributes: Default::default(),
};
let meth = mk_method(vec![tparam_concrete], vec![]);
let mut elem = mk_class(vec![tparam_higher], vec![meth]);
elem.transform(&env, &mut pass);
assert!(matches!(
env.into_errors().as_slice(),
&[NamingPhaseError::Naming(
NamingError::TparamNonShadowingReuse { .. }
)]
));
}
#[test]
fn test_starts_with_t() {
let env = Env::default();
let mut pass = ValidateHintHabstrPass::default();
let tparam = Tparam {
variance: Variance::Invariant,
name: Id(Default::default(), "X".to_string()),
parameters: Default::default(),
constraints: Default::default(),
reified: ReifyKind::Erased,
user_attributes: Default::default(),
};
let mut elem = mk_method(vec![tparam], vec![]);
elem.transform(&env, &mut pass);
assert!(matches!(
env.into_errors().as_slice(),
&[NamingPhaseError::Naming(NamingError::StartWithT(..))]
));
}
#[test]
fn test_this_reserved() {
let env = Env::default();
let mut pass = ValidateHintHabstrPass::default();
let tparam = Tparam {
variance: Variance::Invariant,
name: Id(Default::default(), "This".to_string()),
parameters: Default::default(),
constraints: Default::default(),
reified: ReifyKind::Erased,
user_attributes: Default::default(),
};
let mut elem = mk_method(vec![tparam], vec![]);
elem.transform(&env, &mut pass);
assert!(matches!(
env.into_errors().as_slice(),
&[NamingPhaseError::Naming(NamingError::ThisReserved(..))]
));
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/validate_hint_hrefinement.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 nast::ClassConcreteTypeconst;
use nast::ClassTypeconstDef;
use nast::Expr_;
use nast::Hint;
use nast::Hint_;
use crate::prelude::*;
#[derive(Copy, Clone, Default)]
pub struct ValidateHintHrefinementPass {
context: Option<RfmtCtxt>,
tc_is_context: bool,
}
impl Pass for ValidateHintHrefinementPass {
fn on_ty_expr__top_down(&mut self, _env: &Env, elem: &mut Expr_) -> ControlFlow<()> {
match elem {
Expr_::Is(..) => self.context = Some(RfmtCtxt::IsExpr),
Expr_::As(..) => self.context = Some(RfmtCtxt::AsExpr),
_ => self.context = None,
}
Continue(())
}
fn on_ty_hint_bottom_up(&mut self, env: &Env, elem: &mut Hint) -> ControlFlow<()> {
if let Some(ctxt) = self.context &&
matches!(&*elem.1, Hint_::Hrefinement(..)) {
env.emit_error(NastCheckError::RefinementInTypestruct {
pos: elem.0.clone(),
kind: ctxt.to_string(),
})
}
Continue(())
}
fn on_ty_class_typeconst_def_top_down(
&mut self,
_: &Env,
elem: &mut ClassTypeconstDef,
) -> ControlFlow<()> {
self.tc_is_context = elem.is_ctx;
Continue(())
}
fn on_fld_class_abstract_typeconst_default_top_down(
&mut self,
_: &Env,
_: &mut Option<Hint>,
) -> ControlFlow<()> {
self.context = Some(if self.tc_is_context {
RfmtCtxt::CtxtConst
} else {
RfmtCtxt::TyConst
});
Continue(())
}
fn on_ty_class_concrete_typeconst_top_down(
&mut self,
_: &Env,
_: &mut ClassConcreteTypeconst,
) -> ControlFlow<()> {
self.context = Some(if self.tc_is_context {
RfmtCtxt::CtxtConst
} else {
RfmtCtxt::TyConst
});
Continue(())
}
fn on_fld_typedef_kind_top_down(&mut self, _: &Env, _: &mut Hint) -> ControlFlow<()> {
self.context = Some(RfmtCtxt::TyAlias);
Continue(())
}
}
#[derive(Copy, Clone)]
enum RfmtCtxt {
IsExpr,
AsExpr,
CtxtConst,
TyConst,
TyAlias,
}
impl ToString for RfmtCtxt {
fn to_string(&self) -> String {
match self {
RfmtCtxt::IsExpr => "an is-expression".to_string(),
RfmtCtxt::AsExpr => "an as-expression".to_string(),
RfmtCtxt::CtxtConst => "a context constant".to_string(),
RfmtCtxt::TyConst => "a type constant".to_string(),
RfmtCtxt::TyAlias => "a type alias".to_string(),
}
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/validate_illegal_name.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 nast::ClassId;
use nast::ClassId_;
use nast::Class_;
use nast::ClassishKind;
use nast::Expr;
use nast::Expr_;
use nast::FunDef;
use nast::Id;
use nast::Method_;
use crate::prelude::*;
#[derive(Clone, Default)]
pub struct ValidateIllegalNamePass {
func_name: Option<Rc<String>>,
classish_kind: Option<ClassishKind>,
}
impl ValidateIllegalNamePass {
fn is_current_func(&self, nm: &str) -> bool {
if let Some(cur_nm) = self.func_name.as_deref() {
return cur_nm == nm;
}
false
}
fn in_trait(&self) -> bool {
self.classish_kind
.map_or(false, |ck| ck == ClassishKind::Ctrait)
}
}
impl Pass for ValidateIllegalNamePass {
fn on_ty_class__top_down(&mut self, _: &Env, elem: &mut Class_) -> ControlFlow<()> {
self.classish_kind = Some(elem.kind);
Continue(())
}
fn on_ty_class__bottom_up(&mut self, env: &Env, elem: &mut Class_) -> ControlFlow<()> {
elem.typeconsts
.iter()
.for_each(|tc| check_illegal_member_variable_class(env, &tc.name));
elem.consts
.iter()
.for_each(|cc| check_illegal_member_variable_class(env, &cc.id));
Continue(())
}
fn on_ty_fun_def_top_down(&mut self, _: &Env, elem: &mut FunDef) -> ControlFlow<()> {
self.func_name = Some(Rc::new(elem.name.name().to_string()));
Continue(())
}
fn on_ty_fun_def_bottom_up(&mut self, env: &Env, elem: &mut FunDef) -> ControlFlow<()> {
let name = elem.name.name();
let lower_norm = name
.strip_prefix('\\')
.unwrap_or(name)
.to_ascii_lowercase()
.to_string();
if lower_norm == sn::members::__CONSTRUCT || lower_norm == "using" {
env.emit_error(NastCheckError::IllegalFunctionName {
pos: elem.name.pos().clone(),
name: elem.name.name().to_string(),
})
}
Continue(())
}
fn on_ty_method__top_down(&mut self, _: &Env, elem: &mut Method_) -> ControlFlow<()> {
self.func_name = Some(Rc::new(elem.name.name().to_string()));
Continue(())
}
fn on_ty_method__bottom_up(&mut self, env: &Env, elem: &mut Method_) -> ControlFlow<()> {
if elem.name.name() == sn::members::__DESTRUCT {
env.emit_error(NastCheckError::IllegalDestructor(elem.name.pos().clone()))
}
Continue(())
}
fn on_ty_expr__bottom_up(&mut self, env: &Env, elem: &mut Expr_) -> ControlFlow<()> {
match elem {
Expr_::Id(box id)
if id.name() == sn::pseudo_consts::G__CLASS__ && self.classish_kind.is_none() =>
{
env.emit_error(NamingError::IllegalCLASS(id.pos().clone()))
}
Expr_::Id(box id) if id.name() == sn::pseudo_consts::G__TRAIT__ && !self.in_trait() => {
env.emit_error(NamingError::IllegalTRAIT(id.pos().clone()))
}
// TODO[mjt] Check if this will have already been elaborated to `CIparent`
Expr_::ClassConst(box (
ClassId(_, _, ClassId_::CIexpr(Expr(_, _, Expr_::Id(box id)))),
(_, meth_name),
)) if id.name() == sn::classes::PARENT && self.is_current_func(meth_name) => (),
Expr_::ClassConst(box (_, (pos, meth_name)))
if is_magic(meth_name) && !self.is_current_func(meth_name) =>
{
env.emit_error(NastCheckError::Magic {
pos: pos.clone(),
meth_name: meth_name.clone(),
})
}
Expr_::ObjGet(box (_, Expr(_, _, Expr_::Id(box id)), _, _)) if is_magic(id.name()) => {
env.emit_error(NastCheckError::Magic {
pos: id.pos().clone(),
meth_name: id.name().to_string(),
})
}
Expr_::MethodCaller(box (_, (pos, meth_name))) if is_magic(meth_name) => env
.emit_error(NastCheckError::Magic {
pos: pos.clone(),
meth_name: meth_name.clone(),
}),
_ => (),
}
Continue(())
}
}
fn check_illegal_member_variable_class(env: &Env, id: &Id) {
if id.name().to_ascii_lowercase() == sn::members::M_CLASS {
env.emit_error(NamingError::IllegalMemberVariableClass(id.pos().clone()))
}
}
fn is_magic(nm: &str) -> bool {
nm != sn::members::__TO_STRING && sn::members::AS_LOWERCASE_SET.contains(nm)
} |
Rust | hhvm/hphp/hack/src/elab/passes/validate_interface.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 itertools::FoldWhile;
use itertools::Itertools;
use nast::Class_;
use nast::Hint;
use crate::prelude::*;
#[derive(Clone, Copy, Default)]
pub struct ValidateInterfacePass;
impl Pass for ValidateInterfacePass {
fn on_ty_class__bottom_up(&mut self, env: &Env, elem: &mut Class_) -> ControlFlow<()> {
if elem.kind.is_cinterface() {
// Raise an error for each `use` clause
elem.uses.iter().for_each(|Hint(pos, _)| {
env.emit_error(NastCheckError::InterfaceUsesTrait(pos.clone()))
});
// Raise an error for the first static and instance member variable
// declared, if any
let (instance_var_pos_opt, static_var_pos_opt) = elem
.vars
.iter()
.fold_while(
(None, None),
|(has_instance_var, has_static_var), var| match (
&has_instance_var,
&has_static_var,
) {
(Some(_), Some(_)) => FoldWhile::Done((has_instance_var, has_static_var)),
(_, None) if var.is_static => {
FoldWhile::Continue((has_instance_var, Some(var.id.pos().clone())))
}
(None, _) if !var.is_static => {
FoldWhile::Continue((Some(var.id.pos().clone()), has_static_var))
}
_ => FoldWhile::Continue((has_instance_var, has_static_var)),
},
)
.into_inner();
if let Some(pos) = instance_var_pos_opt {
env.emit_error(NastCheckError::InterfaceWithMemberVariable(pos))
}
if let Some(pos) = static_var_pos_opt {
env.emit_error(NastCheckError::InterfaceWithStaticMemberVariable(pos))
}
// Raise an error for each method with a non-empty body
elem.methods
.iter()
.filter(|m| !m.body.fb_ast.0.is_empty())
.for_each(|m| env.emit_error(NastCheckError::AbstractBody(m.name.pos().clone())));
}
Continue(())
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/validate_like_hint.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 nast::Hint;
use nast::Hint_;
use crate::prelude::*;
#[derive(Clone, Copy, Default)]
pub struct ValidateLikeHintPass {}
impl Pass for ValidateLikeHintPass {
fn on_ty_hint_top_down(&mut self, env: &Env, hint: &mut Hint) -> ControlFlow<()> {
match hint {
Hint(pos, box Hint_::Hlike(_)) if !env.like_type_hints_enabled() => {
env.emit_error(ExperimentalFeature::LikeType(pos.clone()));
}
_ => (),
}
Continue(())
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/validate_method_private_final.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 nast::Class_;
use nast::Method_;
use crate::prelude::*;
#[derive(Clone, Copy, Default)]
pub struct ValidateMethodPrivateFinalPass {
in_trait: bool,
}
impl Pass for ValidateMethodPrivateFinalPass {
fn on_ty_class__top_down(&mut self, _env: &Env, elem: &mut Class_) -> ControlFlow<()> {
self.in_trait = elem.kind.is_ctrait();
ControlFlow::Continue(())
}
fn on_ty_method__bottom_up(&mut self, env: &Env, elem: &mut Method_) -> ControlFlow<()> {
if !self.in_trait && elem.final_ && elem.visibility.is_private() {
env.emit_error(NastCheckError::PrivateAndFinal(elem.name.pos().clone()))
}
ControlFlow::Continue(())
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/validate_module.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 nast::ModuleDef;
use crate::prelude::*;
#[derive(Clone, Copy, Default)]
pub struct ValidateModulePass;
impl Pass for ValidateModulePass {
fn on_ty_module_def_bottom_up(&mut self, env: &Env, module: &mut ModuleDef) -> ControlFlow<()> {
if !env.allow_module_declarations() {
env.emit_error(NamingError::ModuleDeclarationOutsideAllowedFiles(
module.span.clone(),
));
}
Continue(())
}
}
#[cfg(test)]
mod tests {
use nast::Id;
use nast::ModuleDef;
use nast::Pos;
use nast::UserAttributes;
use oxidized::typechecker_options::TypecheckerOptions;
use super::*;
use crate::env::ProgramSpecificOptions;
fn mk_module(name: &str) -> ModuleDef {
ModuleDef {
annotation: (),
name: Id(Pos::NONE, name.to_string()),
user_attributes: UserAttributes::default(),
file_attributes: vec![],
span: Pos::NONE,
mode: oxidized::file_info::Mode::Mstrict,
doc_comment: None,
exports: None,
imports: None,
}
}
#[test]
fn test_module_def_not_allowed() {
let env = Env::new(
&TypecheckerOptions::default(),
&ProgramSpecificOptions {
allow_module_declarations: false,
..Default::default()
},
);
let mut module = mk_module("foo");
module.transform(&env, &mut ValidateModulePass);
assert!(matches!(
env.into_errors().as_slice(),
[NamingPhaseError::Naming(
NamingError::ModuleDeclarationOutsideAllowedFiles(_)
)]
));
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/validate_php_lambda.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 nast::Expr;
use nast::Expr_;
use crate::prelude::*;
#[derive(Clone, Copy, Default)]
pub struct ValidatePhpLambdaPass;
impl Pass for ValidatePhpLambdaPass {
fn on_ty_expr_bottom_up(&mut self, env: &Env, expr: &mut Expr) -> ControlFlow<()> {
if env.error_php_lambdas() && matches!(expr, Expr(_, _, Expr_::Efun(_))) {
env.emit_error(NastCheckError::PhpLambdaDisallowed(expr.pos().clone()));
}
Continue(())
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/validate_shape_name.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 nast::Expr;
use nast::Expr_;
use nast::ShapeFieldName;
use crate::prelude::*;
#[derive(Clone, Copy, Default)]
pub struct ValidateShapeNamePass;
impl Pass for ValidateShapeNamePass {
fn on_ty_expr_bottom_up(&mut self, env: &Env, expr: &mut Expr) -> ControlFlow<()> {
if let Expr(_, _, Expr_::Shape(flds)) = expr {
error_if_duplicate_names(flds, env);
}
Continue(())
}
}
fn error_if_duplicate_names(flds: &[(ShapeFieldName, Expr)], env: &Env) {
let mut seen = hash::HashSet::<&ShapeFieldName>::default();
for (name, _) in flds {
if seen.contains(name) {
env.emit_error(NamingError::FieldNameAlreadyBound(name.get_pos().clone()));
}
seen.insert(name);
}
}
#[cfg(test)]
mod tests {
use nast::Expr;
use nast::Pos;
use oxidized::typechecker_options::TypecheckerOptions;
use super::*;
use crate::env::ProgramSpecificOptions;
fn mk_shape_lit_int_field_name(name: &str) -> ShapeFieldName {
ShapeFieldName::SFlitInt((Pos::NONE, name.to_string()))
}
fn mk_shape(flds: Vec<(ShapeFieldName, Expr)>) -> Expr {
Expr((), Pos::NONE, Expr_::Shape(flds))
}
#[test]
fn test_duplicate_field_names() {
let env = Env::new(
&TypecheckerOptions::default(),
&ProgramSpecificOptions::default(),
);
let f = mk_shape_lit_int_field_name("foo");
let mut shape = mk_shape(vec![
(f.clone(), elab_utils::expr::null()),
(f, elab_utils::expr::null()),
]);
shape.transform(&env, &mut ValidateShapeNamePass);
assert!(matches!(
&env.into_errors()[..],
[NamingPhaseError::Naming(
NamingError::FieldNameAlreadyBound { .. }
)]
));
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/validate_supportdyn.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 naming_special_names_rust as sn;
use nast::Hint_;
use nast::Id;
use oxidized::naming_phase_error::ExperimentalFeature;
use crate::prelude::*;
#[derive(Clone, Copy, Default)]
pub struct ValidateSupportDynPass;
impl Pass for ValidateSupportDynPass {
fn on_ty_hint__bottom_up(&mut self, env: &Env, hint_: &mut Hint_) -> ControlFlow<()> {
if env.is_hhi() || env.is_systemlib() || env.supportdynamic_type_hint_enabled() {
return Continue(());
}
match hint_ {
Hint_::Happly(Id(pos, ty_name), _) if ty_name == sn::classes::SUPPORT_DYN => {
env.emit_error(NamingPhaseError::ExperimentalFeature(
ExperimentalFeature::Supportdyn(pos.clone()),
));
}
_ => (),
}
Continue(())
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/validate_trait_internal.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 nast::Class_;
use crate::prelude::*;
#[derive(Copy, Clone, Default)]
pub struct ValidateTraitInternalPass;
impl Pass for ValidateTraitInternalPass {
fn on_ty_class__bottom_up(&mut self, env: &Env, class_: &mut Class_) -> ControlFlow<()> {
if class_.module.is_some() && class_.kind.is_ctrait() && !class_.internal {
class_
.methods
.iter()
.filter(|m| m.visibility.is_internal())
.for_each(|m| {
env.emit_error(NastCheckError::InternalMemberInsidePublicTrait {
member_pos: m.span.clone(),
trait_pos: class_.name.pos().clone(),
})
});
class_
.vars
.iter()
.filter(|cv| cv.visibility.is_internal())
.for_each(|cv| {
env.emit_error(NastCheckError::InternalMemberInsidePublicTrait {
member_pos: cv.span.clone(),
trait_pos: class_.name.pos().clone(),
})
});
}
ControlFlow::Continue(())
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/validate_user_attribute_arity.rs | // Copyright (c) Meta Platforms, Inc. and affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::ops::ControlFlow;
use nast::Class_;
use nast::Fun_;
use nast::Method_;
use nast::UserAttribute;
use crate::prelude::*;
#[derive(Copy, Clone, Default)]
pub struct ValidateUserAttributeArityPass;
impl Pass for ValidateUserAttributeArityPass {
fn on_ty_fun__bottom_up(&mut self, env: &Env, elem: &mut Fun_) -> ControlFlow<(), ()> {
AritySpec::Range(0, 1).check(sn::user_attributes::POLICIED, &elem.user_attributes, env);
AritySpec::Exact(0).check(sn::user_attributes::INFERFLOWS, &elem.user_attributes, env);
AritySpec::Range(1, 2).check(sn::user_attributes::DEPRECATED, &elem.user_attributes, env);
elem.params.iter().for_each(|fp| {
AritySpec::Exact(0).check(sn::user_attributes::EXTERNAL, &fp.user_attributes, env);
AritySpec::Exact(0).check(sn::user_attributes::CAN_CALL, &fp.user_attributes, env);
});
ControlFlow::Continue(())
}
fn on_ty_class__bottom_up(&mut self, env: &Env, elem: &mut Class_) -> ControlFlow<(), ()> {
AritySpec::Exact(1).check(sn::user_attributes::DOCS, &elem.user_attributes, env);
ControlFlow::Continue(())
}
fn on_ty_method__bottom_up(&mut self, env: &Env, elem: &mut Method_) -> ControlFlow<(), ()> {
AritySpec::Range(0, 1).check(sn::user_attributes::POLICIED, &elem.user_attributes, env);
AritySpec::Exact(0).check(sn::user_attributes::INFERFLOWS, &elem.user_attributes, env);
AritySpec::Range(1, 2).check(sn::user_attributes::DEPRECATED, &elem.user_attributes, env);
ControlFlow::Continue(())
}
}
#[derive(Copy, Clone)]
enum AritySpec {
Exact(usize),
Range(usize, usize),
}
impl AritySpec {
fn check(self, attr_name: &str, user_attrs: &[UserAttribute], env: &Env) {
if let Some(ua) = user_attrs.iter().find(|ua| ua.name.name() == attr_name) {
let actual = ua.params.len();
match self {
AritySpec::Range(expected, _) if actual < expected => {
env.emit_error(NastCheckError::AttributeTooFewArguments {
pos: ua.name.pos().clone(),
name: ua.name.name().to_string(),
expected: expected.try_into().unwrap(),
})
}
AritySpec::Range(_, expected) if actual > expected => {
env.emit_error(NastCheckError::AttributeTooManyArguments {
pos: ua.name.pos().clone(),
name: ua.name.name().to_string(),
expected: expected.try_into().unwrap(),
})
}
AritySpec::Exact(expected) if actual != expected => {
env.emit_error(NastCheckError::AttributeNotExactNumberOfArgs {
pos: ua.name.pos().clone(),
name: ua.name.name().to_string(),
expected: expected.try_into().unwrap(),
actual: actual.try_into().unwrap(),
})
}
_ => (),
}
}
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/validate_user_attribute_deprecated_static.rs | // Copyright (c) Meta Platforms, Inc. and affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::ops::ControlFlow;
use nast::Binop;
use nast::Expr;
use nast::Expr_;
use nast::Fun_;
use nast::Method_;
use nast::Pos;
use nast::UserAttribute;
use oxidized::ast_defs::Bop;
use crate::prelude::*;
#[derive(Copy, Clone, Default)]
pub struct ValidateUserAttributeDeprecatedStaticPass;
impl Pass for ValidateUserAttributeDeprecatedStaticPass {
fn on_ty_fun__bottom_up(&mut self, env: &Env, elem: &mut Fun_) -> ControlFlow<(), ()> {
check_deprecated_static(&elem.user_attributes, env);
ControlFlow::Continue(())
}
fn on_ty_method__bottom_up(&mut self, env: &Env, elem: &mut Method_) -> ControlFlow<(), ()> {
check_deprecated_static(&elem.user_attributes, env);
ControlFlow::Continue(())
}
}
fn check_deprecated_static(user_attrs: &[UserAttribute], env: &Env) {
user_attrs
.iter()
.find(|ua| ua.name.name() == sn::user_attributes::DEPRECATED)
.iter()
.for_each(|ua| match ua.params.as_slice() {
[msg, ..] => {
if let Some(pos) = is_static_string(msg) {
env.emit_error(NastCheckError::AttributeParamType {
pos,
x: "static string literal".to_string(),
})
}
}
_ => (),
})
}
fn is_static_string(expr: &Expr) -> Option<Pos> {
let mut exprs = vec![expr];
while let Some(expr) = exprs.pop() {
match &expr.2 {
Expr_::Binop(box Binop {
bop: Bop::Dot,
lhs,
rhs,
}) => {
exprs.push(lhs);
exprs.push(rhs);
}
Expr_::String(..) => (),
_ => return Some(expr.1.clone()),
}
}
None
} |
Rust | hhvm/hphp/hack/src/elab/passes/validate_user_attribute_dynamically_callable.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 nast::FunDef;
use nast::Method_;
use nast::Pos;
use nast::ReifyKind;
use nast::Tparam;
use nast::UserAttribute;
use nast::Visibility;
use crate::prelude::*;
#[derive(Copy, Clone, Default)]
pub struct ValidateUserAttributeDynamicallyCallable;
impl Pass for ValidateUserAttributeDynamicallyCallable {
fn on_ty_fun_def_top_down(&mut self, env: &Env, elem: &mut FunDef) -> ControlFlow<()> {
dynamically_callable_attr_pos(&elem.fun.user_attributes)
.into_iter()
.for_each(|pos| {
if has_reified_generics(&elem.tparams) {
env.emit_error(NastCheckError::DynamicallyCallableReified(pos.clone()))
}
});
Continue(())
}
fn on_ty_method__top_down(&mut self, env: &Env, elem: &mut Method_) -> ControlFlow<()> {
dynamically_callable_attr_pos(&elem.user_attributes)
.into_iter()
.for_each(|pos| {
match &elem.visibility {
Visibility::Private | Visibility::Protected => {
env.emit_error(NamingError::IllegalUseOfDynamicallyCallable {
attr_pos: pos.clone(),
meth_pos: elem.name.pos().clone(),
vis: elem.visibility.into(),
});
}
Visibility::Public | Visibility::Internal => (),
}
if has_reified_generics(&elem.tparams) {
env.emit_error(NastCheckError::DynamicallyCallableReified(pos.clone()))
}
});
Continue(())
}
}
fn has_reified_generics(tparams: &[Tparam]) -> bool {
tparams
.iter()
.any(|tp| matches!(tp.reified, ReifyKind::Reified | ReifyKind::SoftReified))
}
fn dynamically_callable_attr_pos(attrs: &[UserAttribute]) -> Option<&Pos> {
attrs
.iter()
.find(|ua| ua.name.name() == sn::user_attributes::DYNAMICALLY_CALLABLE)
.map(|ua| ua.name.pos())
} |
Rust | hhvm/hphp/hack/src/elab/passes/validate_user_attribute_entry_point.rs | // Copyright (c) Meta Platforms, Inc. and affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::ops::ControlFlow;
use nast::FunDef;
use crate::prelude::*;
#[derive(Copy, Clone, Default)]
pub struct ValidateUserAttributeEntryPointPass;
impl Pass for ValidateUserAttributeEntryPointPass {
// Ban arguments on functions with the __EntryPoint attribute.
fn on_ty_fun_def_bottom_up(&mut self, env: &Env, elem: &mut FunDef) -> ControlFlow<()> {
if elem
.fun
.user_attributes
.iter()
.any(|ua| ua.name.name() == sn::user_attributes::ENTRY_POINT)
{
match elem.fun.params.as_slice() {
[] => (),
[param, ..] => {
env.emit_error(NastCheckError::EntrypointArguments(param.pos.clone()))
}
}
if let Some(param) = elem.fun.params.iter().find(|p| p.is_variadic) {
env.emit_error(NastCheckError::EntrypointArguments(param.pos.clone()))
}
match elem.tparams.as_slice() {
[] => (),
[tparam, ..] => env.emit_error(NastCheckError::EntrypointGenerics(
tparam.name.pos().clone(),
)),
}
}
ControlFlow::Continue(())
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/validate_user_attribute_infer_flows.rs | // Copyright (c) Meta Platforms, Inc. and affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::ops::ControlFlow;
use nast::Fun_;
use nast::Method_;
use nast::UserAttribute;
use crate::prelude::*;
#[derive(Copy, Clone, Default)]
pub struct ValidateUserAttributeInferFlowsPass;
impl Pass for ValidateUserAttributeInferFlowsPass {
fn on_ty_fun__bottom_up(&mut self, env: &Env, elem: &mut Fun_) -> ControlFlow<(), ()> {
if !env.infer_flows() {
check_ifc_infer_flows(&elem.user_attributes, env)
}
ControlFlow::Continue(())
}
fn on_ty_method__bottom_up(&mut self, env: &Env, elem: &mut Method_) -> ControlFlow<(), ()> {
if !env.infer_flows() {
check_ifc_infer_flows(&elem.user_attributes, env)
}
ControlFlow::Continue(())
}
}
fn check_ifc_infer_flows(user_attrs: &[UserAttribute], env: &Env) {
if let Some(ua) = user_attrs
.iter()
.find(|ua| ua.name.name() == sn::user_attributes::INFERFLOWS)
{
env.emit_error(ExperimentalFeature::IFCInferFlows(ua.name.pos().clone()))
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/validate_user_attribute_memoize.rs | // Copyright (c) Meta Platforms, Inc. and affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::ops::ControlFlow;
use nast::FunParam;
use nast::Fun_;
use nast::Method_;
use crate::prelude::*;
#[derive(Copy, Clone, Default)]
pub struct ValidateUserAttributeMemoizePass;
// Ban variadic arguments on memoized methods.
impl Pass for ValidateUserAttributeMemoizePass {
fn on_ty_fun__bottom_up(&mut self, env: &Env, elem: &mut Fun_) -> ControlFlow<(), ()> {
if elem
.user_attributes
.iter()
.any(|ua| ua.name.name() == sn::user_attributes::MEMOIZE)
{
check_variadic_param(&elem.params, env)
}
ControlFlow::Continue(())
}
fn on_ty_method__bottom_up(&mut self, env: &Env, elem: &mut Method_) -> ControlFlow<(), ()> {
let memo_opt = elem
.user_attributes
.iter()
.find(|ua| ua.name.name() == sn::user_attributes::MEMOIZE);
let memo_lsb_opt = elem
.user_attributes
.iter()
.find(|ua| ua.name.name() == sn::user_attributes::MEMOIZE_LSB);
match (memo_opt, memo_lsb_opt) {
(Some(memo), Some(memo_lsb)) => {
check_variadic_param(&elem.params, env);
env.emit_error(NastCheckError::AttributeConflictingMemoize {
pos: memo.name.pos().clone(),
second_pos: memo_lsb.name.pos().clone(),
})
}
(Some(_), _) | (_, Some(_)) => check_variadic_param(&elem.params, env),
_ => (),
}
ControlFlow::Continue(())
}
}
fn check_variadic_param(params: &[FunParam], env: &Env) {
if let Some(param) = params.iter().find(|fp| fp.is_variadic) {
env.emit_error(NastCheckError::VariadicMemoize(param.pos.clone()))
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/validate_user_attribute_no_auto_dynamic.rs | // Copyright (c) Meta Platforms, Inc. and affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::ops::ControlFlow;
use nast::Class_;
use nast::Fun_;
use nast::Method_;
use nast::UserAttribute;
use crate::prelude::*;
#[derive(Copy, Clone, Default)]
pub struct ValidateUserAttributeNoAutoDynamic;
impl Pass for ValidateUserAttributeNoAutoDynamic {
fn on_ty_fun__bottom_up(&mut self, env: &Env, elem: &mut Fun_) -> ControlFlow<()> {
if !env.is_hhi() && !env.no_auto_dynamic_enabled() {
check_no_auto_dynamic(&elem.user_attributes, env);
}
Continue(())
}
fn on_ty_method__bottom_up(&mut self, env: &Env, elem: &mut Method_) -> ControlFlow<()> {
if !env.is_hhi() && !env.no_auto_dynamic_enabled() {
check_no_auto_dynamic(&elem.user_attributes, env);
}
Continue(())
}
fn on_ty_class__bottom_up(&mut self, env: &Env, elem: &mut Class_) -> ControlFlow<()> {
if !env.is_hhi() && !env.no_auto_dynamic_enabled() {
check_no_auto_dynamic(&elem.user_attributes, env);
}
Continue(())
}
}
fn check_no_auto_dynamic(user_attrs: &[UserAttribute], env: &Env) {
user_attrs
.iter()
.find(|ua| ua.name.name() == sn::user_attributes::NO_AUTO_DYNAMIC)
.iter()
.for_each(|ua| {
env.emit_error(NastCheckError::AttributeNoAutoDynamic(
ua.name.pos().clone(),
))
})
} |
Rust | hhvm/hphp/hack/src/elab/passes/validate_user_attribute_soft_internal.rs | // Copyright (c) Meta Platforms, Inc. and affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::ops::ControlFlow;
use nast::Class_;
use nast::FunDef;
use nast::Fun_;
use nast::Method_;
use nast::UserAttribute;
use nast::Visibility;
use crate::prelude::*;
#[derive(Copy, Clone, Default)]
pub struct ValidateUserAttributeSoftInternalPass;
impl Pass for ValidateUserAttributeSoftInternalPass {
fn on_ty_class__bottom_up(&mut self, env: &Env, elem: &mut Class_) -> ControlFlow<(), ()> {
check_soft_internal(elem.internal, &elem.user_attributes, env);
elem.vars.iter().for_each(|cv| {
check_soft_internal(
cv.visibility == Visibility::Internal,
&cv.user_attributes,
env,
)
});
ControlFlow::Continue(())
}
fn on_ty_fun__bottom_up(&mut self, env: &Env, elem: &mut Fun_) -> ControlFlow<(), ()> {
elem.params
.iter()
.for_each(|p| check_soft_internal_on_param(&p.visibility, &p.user_attributes, env));
ControlFlow::Continue(())
}
fn on_ty_fun_def_bottom_up(&mut self, env: &Env, elem: &mut FunDef) -> ControlFlow<(), ()> {
check_soft_internal(elem.internal, &elem.fun.user_attributes, env);
ControlFlow::Continue(())
}
fn on_ty_method__bottom_up(&mut self, env: &Env, elem: &mut Method_) -> ControlFlow<(), ()> {
check_soft_internal(
elem.visibility == Visibility::Internal,
&elem.user_attributes,
env,
);
elem.params
.iter()
.for_each(|p| check_soft_internal_on_param(&p.visibility, &p.user_attributes, env));
ControlFlow::Continue(())
}
}
fn check_soft_internal(is_internal: bool, user_attrs: &[UserAttribute], env: &Env) {
if !is_internal && let Some(ua) = user_attrs
.iter()
.find(|ua| ua.name.name() == sn::user_attributes::SOFT_INTERNAL)
{
env.emit_error(
NastCheckError::SoftInternalWithoutInternal(ua.name.pos().clone()),
)
}
}
fn check_soft_internal_on_param(
visiblity_opt: &Option<Visibility>,
user_attrs: &[UserAttribute],
env: &Env,
) {
user_attrs
.iter()
.find(|ua| ua.name.name() == sn::user_attributes::SOFT_INTERNAL)
.iter()
.for_each(|ua| match visiblity_opt {
Some(Visibility::Internal) => (),
Some(Visibility::Private | Visibility::Protected | Visibility::Public) => env
.emit_error(NastCheckError::SoftInternalWithoutInternal(
ua.name.pos().clone(),
)),
_ => env.emit_error(NastCheckError::WrongExpressionKindBuiltinAttribute {
pos: ua.name.pos().clone(),
attr_name: ua.name.name().to_string(),
expr_kind: "a parameter".to_string(),
}),
})
} |
Rust | hhvm/hphp/hack/src/elab/passes/validate_xhp_attribute.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 oxidized::nast::Expr_;
use oxidized::nast::XhpAttribute;
use oxidized::nast::XhpSimple;
use crate::prelude::*;
#[derive(Clone, Copy, Default)]
pub struct ValidateXhpAttributePass;
impl Pass for ValidateXhpAttributePass {
fn on_ty_expr__bottom_up(&mut self, env: &Env, expr: &mut Expr_) -> ControlFlow<()> {
if let Expr_::Xml(box (_, attrs, _)) = expr {
error_if_repeated_attribute(env, attrs);
}
Continue(())
}
}
// Produce a syntax error on XHP expressions of the form: `<foo x={1} x={2} />`
//
// This is not currently enforced in the parser because syntax errors cannot be
// HH_FIXME'd. Once codebases are clean, we can move this check to the parser
// itself.
fn error_if_repeated_attribute(env: &Env, attrs: &[XhpAttribute]) {
let mut seen = hash::HashSet::<&str>::default();
for attr in attrs {
match attr {
XhpAttribute::XhpSimple(XhpSimple {
name: (pos, name), ..
}) if seen.contains(name as &str) => {
env.emit_error(ParsingError::XhpParsingError {
pos: pos.clone(),
msg: format!("Cannot redeclare {}", name),
});
break; // This isn't usual but consistent with today's OCaml.
}
XhpAttribute::XhpSimple(XhpSimple {
name: (_, name), ..
}) => {
seen.insert(name);
}
XhpAttribute::XhpSpread(_) => (),
}
}
} |
Rust | hhvm/hphp/hack/src/elab/passes/validate_xhp_name.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 nast::Hint_;
use nast::Id;
use crate::prelude::*;
#[derive(Clone, Copy, Default)]
pub struct ValidateXhpNamePass;
impl Pass for ValidateXhpNamePass {
fn on_ty_hint__top_down(&mut self, env: &Env, hint_: &mut Hint_) -> ControlFlow<()> {
match hint_ {
// "some common Xhp screw ups"
Hint_::Happly(Id(pos, name), _) if ["Xhp", ":Xhp", "XHP"].contains(&name.as_str()) => {
env.emit_error(NamingError::DisallowedXhpType {
pos: pos.clone(),
ty_name: name.clone(),
})
}
_ => (),
}
Continue(())
}
}
#[cfg(test)]
mod tests {
use nast::Pos;
use super::*;
#[test]
fn test_bad_xhp_name() {
let env = Env::default();
let mut pass = ValidateXhpNamePass;
let mut hint_ = Hint_::Happly(Id(Pos::NONE, "Xhp".to_string()), vec![]);
hint_.transform(&env, &mut pass);
assert!(matches!(
env.into_errors().as_slice(),
&[NamingPhaseError::Naming(
NamingError::DisallowedXhpType { .. }
)]
))
}
} |
OCaml | hhvm/hphp/hack/src/errors/contextual_error_formatter.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 String_utils
let column_width line_number = max 3 (Errors.num_digits line_number)
let line_margin (line_num : int option) col_width : string =
let padded_num =
match line_num with
| Some line_num -> Printf.sprintf "%*d" col_width line_num
| None -> String.make col_width ' '
in
Tty.apply_color (Tty.Normal Tty.Cyan) (padded_num ^ " |")
(* Get the lines of source code associated with this position. *)
let load_context_lines (pos : Pos.absolute) : string list =
let path = Pos.filename pos in
let line = Pos.line pos in
let end_line = Pos.end_line pos in
let lines = Errors.read_lines path in
(* Line numbers are 1-indexed. *)
List.filteri lines ~f:(fun i _ -> i + 1 >= line && i + 1 <= end_line)
let format_context_lines (pos : Pos.absolute) (lines : string list) col_width :
string =
let lines =
match lines with
| [] -> [Tty.apply_color (Tty.Dim Tty.Default) "No source found"]
| ls -> ls
in
let line_num = Pos.line pos in
let format_line i (line : string) =
Printf.sprintf "%s %s" (line_margin (Some (line_num + i)) col_width) line
in
let formatted_lines = List.mapi ~f:format_line lines in
(* TODO: display all the lines, showing the underline on all of them. *)
List.hd_exn formatted_lines
let format_filename (pos : Pos.absolute) : string =
let relative_path path =
let cwd = Filename.concat (Sys.getcwd ()) "" in
lstrip path cwd
in
let filename = relative_path (Pos.filename pos) in
Printf.sprintf
" %s %s"
(Tty.apply_color (Tty.Normal Tty.Cyan) "-->")
(Tty.apply_color (Tty.Normal Tty.Green) filename)
(* Format this message as " ^^^ You did something wrong here". *)
let format_substring_underline
(pos : Pos.absolute)
(msg : string)
(first_context_line : string option)
is_first
col_width : string =
let (start_line, start_column) = Pos.line_column pos in
let (end_line, end_column) = Pos.end_line_column pos in
let underline_width =
match first_context_line with
| None -> 4 (* Arbitrary choice when source isn't available. *)
| Some first_context_line ->
if start_line = end_line then
end_column - start_column
else
String.length first_context_line - start_column
in
let underline = String.make (max underline_width 1) '^' in
let underline_padding =
if Option.is_some first_context_line then
String.make start_column ' '
else
""
in
let color =
if is_first then
Tty.Bold Tty.Red
else
Tty.Dim Tty.Default
in
Printf.sprintf
"%s %s%s"
(line_margin None col_width)
underline_padding
(Tty.apply_color
color
(if is_first then
underline
else
underline ^ " " ^ msg))
(* Format the line of code associated with this message, and the message itself. *)
let format_message (msg : string) (pos : Pos.absolute) ~is_first ~col_width :
string * string =
let col_width =
Option.value col_width ~default:(column_width (Pos.line pos))
in
let context_lines = load_context_lines pos in
let pretty_ctx = format_context_lines pos context_lines col_width in
let pretty_msg =
format_substring_underline
pos
msg
(List.hd context_lines)
is_first
col_width
in
(pretty_ctx, pretty_msg)
(* Work out the column width needed for each file. Files with many
lines need a wider column due to the higher line numbers. *)
let col_widths (msgs : Pos.absolute Message.t list) : int Core.String.Map.t =
(* Find the longest line number for every file in msgs. *)
let longest_lines =
List.fold msgs ~init:String.Map.empty ~f:(fun acc msg ->
let filename = Pos.filename (Message.get_message_pos msg) in
let current_max =
Option.value (String.Map.find acc filename) ~default:0
in
String.Map.set
acc
~key:filename
~data:(max current_max (Pos.line (Message.get_message_pos msg))))
in
String.Map.map longest_lines ~f:column_width
(** Format the list of messages in a given error with context.
The list may not be ordered, and multiple messages may occur on one line.
*)
let format_error (error : Errors.finalized_error) : string =
(* Sort messages such that messages in the same file are together.
Does not reorder the files or messages within a file. *)
let msgs =
User_error.get_messages error
|> Errors.combining_sort ~f:(fun msg ->
Message.get_message_pos msg |> Pos.filename)
in
(* The first message is the 'primary' message, so add a boolean to distinguish it. *)
let rec label_first msgs is_first =
match msgs with
| msg :: msgs -> (msg, is_first) :: label_first msgs false
| [] -> []
in
let labelled_msgs = label_first msgs true in
(* Sort messages by line number, so we can display with context. *)
let cmp (m1, _) (m2, _) =
match
String.compare
(Message.get_message_pos m1 |> Pos.filename)
(Message.get_message_pos m2 |> Pos.filename)
with
| 0 ->
Int.compare
(Message.get_message_pos m1 |> Pos.line)
(Message.get_message_pos m2 |> Pos.line)
| _ -> 0
in
let sorted_msgs = List.stable_sort ~compare:cmp labelled_msgs in
(* For every message, show it alongside the relevant line. If there
are multiple messages associated with the line, only show it once. *)
let col_widths = col_widths msgs in
let rec aux msgs prev : string list =
match msgs with
| (msg, is_first) :: msgs ->
let pos = Message.get_message_pos msg in
let filename = Pos.filename pos in
let line = Pos.line pos in
let col_width = String.Map.find col_widths filename in
let (pretty_ctx, pretty_msg) =
format_message (Message.get_message_str msg) pos ~is_first ~col_width
in
let formatted : string list =
match prev with
| Some (prev_filename, prev_line)
when String.equal prev_filename filename && prev_line = line ->
(* Previous message was on this line too, just show the message itself*)
[pretty_msg]
| Some (prev_filename, _) when String.equal prev_filename filename ->
(* Previous message was this file, but an earlier line. *)
[pretty_ctx; pretty_msg]
| _ -> [format_filename pos; pretty_ctx; pretty_msg]
in
formatted @ aux msgs (Some (filename, line))
| [] -> []
in
String.concat ~sep:"\n" (aux sorted_msgs None) ^ "\n"
let to_string
?(claim_color : Tty.raw_color option) (error : Errors.finalized_error) :
string =
let error_code = User_error.get_code error in
let custom_msgs = error.User_error.custom_msgs in
let msgl = User_error.to_list error in
let buf = Buffer.create 50 in
let color = Option.value claim_color ~default:Tty.Red in
(match msgl with
| [] -> failwith "Impossible: an error always has non-empty list of messages"
| (_, msg) :: _ ->
Buffer.add_string
buf
(Printf.sprintf
"%s %s\n"
(Tty.apply_color
(Tty.Bold color)
(User_error.error_code_to_string error_code))
(Tty.apply_color (Tty.Bold Tty.Default) msg)));
(try Buffer.add_string buf (format_error error) with
| _ ->
Buffer.add_string
buf
"Error could not be pretty-printed. Please file a bug.");
Buffer.add_string buf "\n";
if not @@ List.is_empty custom_msgs then
Buffer.add_string
buf
(String.concat ~sep:"\n" error.User_error.custom_msgs ^ "\n");
Buffer.contents buf |
OCaml Interface | hhvm/hphp/hack/src/errors/contextual_error_formatter.mli | (*
* 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.
*
*)
val to_string : ?claim_color:Tty.raw_color -> Errors.finalized_error -> string |
hhvm/hphp/hack/src/errors/dune | (rule
(target error_message_sentinel.fb.ml)
(action
(copy# facebook/error_message_sentinel.ml error_message_sentinel.fb.ml)))
(library
(name error_codes)
(wrapped false)
(preprocess
(pps ppx_deriving.std))
(modules
error_codes
)
)
(library
(name user_error)
(wrapped false)
(preprocess
(pps ppx_deriving.std))
(modules
markdown_lite
render
message
quickfix
user_error)
(libraries
core_kernel
pos_or_decl
hh_autoimport
utils_multifile
error_codes
)
)
(library
(name errors)
(wrapped false)
(preprocess
(pps ppx_deriving.std))
(modules
contextual_error_formatter
error_category
errors
highlighted_error_formatter
phase_error
quickfix_ffp
raw_error_formatter
error_message_sentinel)
(libraries
core_kernel
error_codes
full_fidelity
hh_autoimport
logging
pos_or_decl
ast
server_load_flag
utils_exit
utils_multifile
user_error
(select
error_message_sentinel.ml
from
(facebook -> error_message_sentinel.fb.ml)
(-> error_message_sentinel.stubs.ml)))) |
|
OCaml | hhvm/hphp/hack/src/errors/errors.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
type error_code = int
type format =
| Context (** Underlined references and color *)
| Raw (** Compact format with color but no references *)
| Highlighted (** Numbered and colored references *)
| Plain (** Verbose positions and no color *)
let claim_as_reason : Pos.t Message.t -> Pos_or_decl.t Message.t =
(fun (p, m) -> (Pos_or_decl.of_raw_pos p, m))
(* The file of analysis being currently performed *)
let current_file : Relative_path.t ref = ref Relative_path.default
let current_span : Pos.t ref = ref Pos.none
let ignore_pos_outside_current_span : bool ref = ref false
let allow_errors_in_default_path = ref true
type finalized_error = (Pos.absolute, Pos.absolute) User_error.t
[@@deriving eq, ord, show]
type error = (Pos.t, Pos_or_decl.t) User_error.t [@@deriving eq, ord, show]
type per_file_errors = error list
type t = error list Relative_path.Map.t [@@deriving eq, show]
let files_t_fold v ~f ~init =
Relative_path.Map.fold v ~init ~f:(fun path v acc -> f path v acc)
let files_t_map v ~f = Relative_path.Map.map v ~f
(** [files_t_merge f x y] is a merge by [file], i.e. given "x:t" and "y:t" it
goes through every (file) mentioned in either of them, and combines
the error-lists using the provided callback. Cost is O(x). *)
let files_t_merge
~(f :
Relative_path.t ->
error list option ->
error list option ->
error list option)
(x : t)
(y : t) : t =
(* Using fold instead of merge to make the runtime proportional to the size
* of first argument (like List.rev_append ) *)
Relative_path.Map.fold x ~init:y ~f:(fun path x acc ->
let y = Relative_path.Map.find_opt y path in
match f path (Some x) y with
| None -> Relative_path.Map.remove acc path
| Some data -> Relative_path.Map.add acc ~key:path ~data)
let files_t_to_list x =
files_t_fold x ~f:(fun _ x acc -> List.rev_append x acc) ~init:[] |> List.rev
(** Values constructed here should not be used with incremental mode.
See assert in incremental_update. *)
let from_error_list errors =
if List.is_empty errors then
Relative_path.Map.empty
else
Relative_path.Map.singleton Relative_path.default errors
(* Get most recently-ish added error. *)
let get_last error_map =
(* If this map has more than one element, we pick an arbitrary file. Because
* of that, we might not end up with the most recent error and generate a
* less-specific error message. This should be rare. *)
match Relative_path.Map.max_binding_opt error_map with
| None -> None
| Some (_, error_list) ->
(match List.rev error_list with
| [] -> None
| e :: _ -> Some e)
let iter t ~f =
Relative_path.Map.iter t ~f:(fun _path errors -> List.iter errors ~f)
module Error = struct
type t = error [@@deriving ord]
end
module ErrorSet = Caml.Set.Make (Error)
module FinalizedError = struct
type t = finalized_error [@@deriving ord]
end
module FinalizedErrorSet = Caml.Set.Make (FinalizedError)
let drop_fixmed_errors (errs : ('a, 'b) User_error.t list) :
('a, 'b) User_error.t list =
List.filter errs ~f:(fun e -> not e.User_error.is_fixmed)
let drop_fixmed_errors_in_files (t : t) : t =
Relative_path.Map.fold
t
~init:Relative_path.Map.empty
~f:(fun file errs acc ->
let errs_without_fixmes = drop_fixmed_errors errs in
if List.is_empty errs_without_fixmes then
acc
else
Relative_path.Map.add acc ~key:file ~data:errs_without_fixmes)
let drop_fixmes_if (err : t) (drop : bool) : t =
if drop then
drop_fixmed_errors_in_files err
else
err
(** Get all errors emitted. Drops errors with valid HH_FIXME comments
unless ~drop_fixmed:false is set. *)
let get_error_list ?(drop_fixmed = true) err =
files_t_to_list (drop_fixmes_if err drop_fixmed)
let (error_map : error list Relative_path.Map.t ref) =
ref Relative_path.Map.empty
let accumulate_errors = ref false
(* Are we in the middle of folding a decl? ("lazy" means it happens on-demand
during the course of the typecheck, rather than all upfront). *)
let in_lazy_decl = ref false
let (is_hh_fixme : (Pos.t -> error_code -> bool) ref) = ref (fun _ _ -> false)
let badpos_message =
Printf.sprintf
"Incomplete position information! Your type error is in this file, but we could only find related positions in another file. %s"
Error_message_sentinel.please_file_a_bug_message
let badpos_message_2 =
Printf.sprintf
"Incomplete position information! We couldn't find the exact line of your type error in this definition. %s"
Error_message_sentinel.please_file_a_bug_message
let try_with_result (f1 : unit -> 'res) (f2 : 'res -> error -> 'res) : 'res =
let error_map_copy = !error_map in
let accumulate_errors_copy = !accumulate_errors in
let is_hh_fixme_copy = !is_hh_fixme in
(is_hh_fixme := (fun _ _ -> false));
error_map := Relative_path.Map.empty;
accumulate_errors := true;
let (result, errors) =
Utils.try_finally
~f:
begin
fun () ->
let result = f1 () in
(result, !error_map)
end
~finally:
begin
fun () ->
error_map := error_map_copy;
accumulate_errors := accumulate_errors_copy;
is_hh_fixme := is_hh_fixme_copy
end
in
match get_last errors with
| None -> result
| Some
User_error.
{ code; claim; reasons; quickfixes; custom_msgs; is_fixmed = _ } ->
(* Remove bad position sentinel if present: we might be about to add a new primary
* error position. *)
let (claim, reasons) =
let (prim_pos, msg) = claim in
if String.equal msg badpos_message || String.equal msg badpos_message_2
then
match reasons with
| [] -> failwith "in try_with_result"
| (_p, claim) :: reasons -> ((prim_pos, claim), reasons)
else
(claim, reasons)
in
f2 result @@ User_error.make code claim reasons ~quickfixes ~custom_msgs
let try_with_result_pure ~fail f g =
let error_map_copy = !error_map in
let accumulate_errors_copy = !accumulate_errors in
let is_hh_fixme_copy = !is_hh_fixme in
(is_hh_fixme := (fun _ _ -> false));
error_map := Relative_path.Map.empty;
accumulate_errors := true;
let (result, errors) =
Utils.try_finally
~f:
begin
fun () ->
let result = f () in
(result, !error_map)
end
~finally:
begin
fun () ->
error_map := error_map_copy;
accumulate_errors := accumulate_errors_copy;
is_hh_fixme := is_hh_fixme_copy
end
in
match get_last errors with
| None when not @@ fail result -> result
| _ -> g result
(* Reset errors before running [f] so that we can return the errors
* caused by f. These errors are not added in the global list of errors. *)
let do_ ?(apply_fixmes = true) ?(drop_fixmed = true) f =
let error_map_copy = !error_map in
let accumulate_errors_copy = !accumulate_errors in
error_map := Relative_path.Map.empty;
accumulate_errors := true;
let is_hh_fixme_copy = !is_hh_fixme in
(if not apply_fixmes then is_hh_fixme := (fun _ _ -> false));
let (result, out_errors) =
Utils.try_finally
~f:
begin
fun () ->
let result = f () in
(result, !error_map)
end
~finally:
begin
fun () ->
error_map := error_map_copy;
accumulate_errors := accumulate_errors_copy;
is_hh_fixme := is_hh_fixme_copy
end
in
let out_errors = files_t_map ~f:List.rev out_errors in
(drop_fixmes_if out_errors drop_fixmed, result)
let run_in_context path f =
let context_copy = !current_file in
current_file := path;
Utils.try_finally ~f ~finally:(fun () -> current_file := context_copy)
let run_with_span span f =
let old_span = !current_span in
current_span := span;
Utils.try_finally ~f ~finally:(fun () -> current_span := old_span)
(* Log important data if lazy_decl triggers a crash *)
let lazy_decl_error_logging error error_map to_absolute to_string =
let error_list = files_t_to_list !error_map in
(* Print the current error list, which should be empty *)
Printf.eprintf "%s" "Error list(should be empty):\n";
List.iter error_list ~f:(fun err ->
let msg = err |> to_absolute |> to_string in
Printf.eprintf "%s\n" msg);
Printf.eprintf "%s" "Offending error:\n";
Printf.eprintf "%s" error;
(* Print out a larger stack trace *)
Printf.eprintf "%s" "Callstack:\n";
Printf.eprintf
"%s"
(Caml.Printexc.raw_backtrace_to_string (Caml.Printexc.get_callstack 500));
(* Exit with special error code so we can see the log after *)
Exit.exit Exit_status.Lazy_decl_bug
(*****************************************************************************)
(* Error code printing. *)
(*****************************************************************************)
let compare_internal
(x : ('a, 'b) User_error.t)
(y : ('a, 'b) User_error.t)
~compare_code
~compare_claim_fn
~compare_claim
~compare_reason : int =
let User_error.
{
code = x_code;
claim = x_claim;
reasons = x_messages;
custom_msgs = _;
quickfixes = _;
is_fixmed = _;
} =
x
in
let User_error.
{
code = y_code;
claim = y_claim;
reasons = y_messages;
custom_msgs = _;
quickfixes = _;
is_fixmed = _;
} =
y
in
(* The primary sort order is by file *)
let comparison =
compare_claim_fn (fst x_claim |> Pos.filename) (fst y_claim |> Pos.filename)
in
(* Then within each file, sort by category *)
let comparison =
if comparison = 0 then
compare_code x_code y_code
else
comparison
in
(* If the error codes are the same, sort by position *)
let comparison =
if comparison = 0 then
compare_claim (fst x_claim) (fst y_claim)
else
comparison
in
(* If the primary positions are also the same, sort by message text *)
let comparison =
if comparison = 0 then
String.compare (snd x_claim) (snd y_claim)
else
comparison
in
(* Finally, if the message text is also the same, then continue comparing
the reason messages (which indicate the reason why Hack believes
there is an error reported in the claim message) *)
if comparison = 0 then
(List.compare (Message.compare compare_reason)) x_messages y_messages
else
comparison
let compare (x : error) (y : error) : int =
compare_internal
x
y
~compare_code:Int.compare
~compare_claim_fn:Relative_path.compare
~compare_claim:Pos.compare
~compare_reason:Pos_or_decl.compare
let compare_finalized (x : finalized_error) (y : finalized_error) : int =
compare_internal
x
y
~compare_code:Int.compare
~compare_claim_fn:String.compare
~compare_claim:Pos.compare_absolute
~compare_reason:Pos.compare_absolute
let sort (err : error list) : error list =
let compare_exact_code = Int.compare in
let compare_category x_code y_code =
Int.compare (x_code / 1000) (y_code / 1000)
in
let compare_claim_fn = Relative_path.compare in
let compare_claim = Pos.compare in
let compare_reason = Pos_or_decl.compare in
(* Sort using the exact code to ensure sort stability, but use the category to deduplicate *)
let equal x y =
compare_internal
~compare_code:compare_category
~compare_claim_fn
~compare_claim
~compare_reason
x
y
= 0
in
List.sort
~compare:(fun x y ->
compare_internal
~compare_code:compare_exact_code
~compare_claim_fn
~compare_claim
~compare_reason
x
y)
err
|> List.remove_consecutive_duplicates
~equal:(fun x y -> equal x y)
~which_to_keep:`First (* Match Rust dedup_by *)
let get_sorted_error_list ?(drop_fixmed = true) err =
sort (files_t_to_list (drop_fixmes_if err drop_fixmed))
let sort_and_finalize (errors : t) : finalized_error list =
errors |> get_sorted_error_list |> List.map ~f:User_error.to_absolute
(* Getters and setter for passed-in map, based on current context *)
let get_current_list t =
Relative_path.Map.find_opt t !current_file |> Option.value ~default:[]
let set_current_list file_t_map new_list =
file_t_map :=
Relative_path.Map.add !file_t_map ~key:!current_file ~data:new_list
let run_and_check_for_errors (f : unit -> 'res) : 'res * bool =
let old_error_list = get_current_list !error_map in
let old_count = List.length old_error_list in
let result = f () in
let new_error_list = get_current_list !error_map in
let new_count = List.length new_error_list in
(result, not (Int.equal old_count new_count))
let do_with_context ?(drop_fixmed = true) path f =
run_in_context path (fun () -> do_ ~drop_fixmed f)
(** Turn on lazy decl mode for the duration of the closure.
This runs without returning the original state,
since we collect it later in do_with_lazy_decls_ *)
let run_in_decl_mode f =
let old_in_lazy_decl = !in_lazy_decl in
in_lazy_decl := true;
Utils.try_finally ~f ~finally:(fun () -> in_lazy_decl := old_in_lazy_decl)
let read_lines path =
try In_channel.read_lines path with
| Sys_error _ ->
(try Multifile.read_file_from_multifile path with
| Sys_error _ -> [])
let num_digits x = int_of_float (Float.log10 (float_of_int x)) + 1
(* Sort [xs] such that all the values that return the same
value for (f x) are consecutive. For any two elements
x1 and x2 in xs where (f x1) = (f x2), if x1 occurs before x2 in
xs, then x1 also occurs before x2 in the returned list. *)
let combining_sort (xs : 'a list) ~(f : 'a -> string) : _ list =
let rec build_map xs grouped keys =
match xs with
| x :: xs ->
let key = f x in
(match String.Map.find grouped key with
| Some members ->
let grouped = String.Map.set grouped ~key ~data:(members @ [x]) in
build_map xs grouped keys
| None ->
let grouped = String.Map.set grouped ~key ~data:[x] in
build_map xs grouped (key :: keys))
| [] -> (grouped, keys)
in
let (grouped, keys) = build_map xs String.Map.empty [] in
List.concat_map (List.rev keys) ~f:(fun fn -> String.Map.find_exn grouped fn)
(* E.g. "10 errors found." *)
let format_summary format ~displayed_count ~dropped_count ~max_errors :
string option =
match format with
| Context
| Highlighted ->
let found_count = displayed_count + Option.value dropped_count ~default:0 in
let found_message =
Printf.sprintf
"%d error%s found"
found_count
(if found_count = 1 then
""
else
"s")
in
let truncated_message =
match (max_errors, dropped_count) with
| (Some max_errors, Some dropped_count) when dropped_count > 0 ->
Printf.sprintf
" (only showing first %d, dropped %d).\n"
max_errors
dropped_count
| (Some max_errors, None) when displayed_count >= max_errors ->
Printf.sprintf
" (max-errors is %d; more errors may exist).\n"
max_errors
| _ -> ".\n"
in
Some (found_message ^ truncated_message)
| Raw
| Plain ->
None
let report_pos_from_reason = ref false
let to_string error = User_error.to_string !report_pos_from_reason error
let log_unexpected error path desc =
HackEventLogger.invariant_violation_bug
desc
~path
~pos:
(error
|> User_error.to_absolute
|> User_error.get_pos
|> Pos.show_absolute);
Hh_logger.log
"UNEXPECTED: %s\n%s"
desc
(Exception.get_current_callstack_string 99 |> Exception.clean_stack);
()
let add_error_impl error =
if !accumulate_errors then
let () =
match !current_file with
| path
when Relative_path.equal path Relative_path.default
&& not !allow_errors_in_default_path ->
log_unexpected error path "adding an error in default path"
| _ -> ()
in
(* Cheap test to avoid duplicating most recent error *)
let error_list = get_current_list !error_map in
match error_list with
| old_error :: _ when equal_error error old_error -> ()
| _ -> set_current_list error_map (error :: error_list)
else
(* We have an error, but haven't handled it in any way *)
let msg = error |> User_error.to_absolute |> to_string in
if !in_lazy_decl then
lazy_decl_error_logging msg error_map User_error.to_absolute to_string
else if error.User_error.is_fixmed then
()
else
Utils.assert_false_log_backtrace (Some msg)
(* Whether we've found at least one error *)
let currently_has_errors () = not (List.is_empty (get_current_list !error_map))
module Parsing = Error_codes.Parsing
module Naming = Error_codes.Naming
module NastCheck = Error_codes.NastCheck
module Typing = Error_codes.Typing
module GlobalAccessCheck = Error_codes.GlobalAccessCheck
(*****************************************************************************)
(* Types *)
(*****************************************************************************)
module type Error_category = Error_category.S
(*****************************************************************************)
(* HH_FIXMEs hook *)
(*****************************************************************************)
let error_codes_treated_strictly = ref (ISet.of_list [])
let is_strict_code code = ISet.mem code !error_codes_treated_strictly
(* The 'phps FixmeAllHackErrors' tool must be kept in sync with this list *)
let hard_banned_codes =
ISet.of_list
[
Typing.err_code Typing.InvalidIsAsExpressionHint;
Typing.err_code Typing.InvalidEnforceableTypeArgument;
Typing.err_code Typing.RequireArgsReify;
Typing.err_code Typing.InvalidReifiedArgument;
Typing.err_code Typing.GenericsNotAllowed;
Typing.err_code Typing.InvalidNewableTypeArgument;
Typing.err_code Typing.InvalidNewableTypeParamConstraints;
Typing.err_code Typing.NewWithoutNewable;
Typing.err_code Typing.NewClassReified;
Typing.err_code Typing.MemoizeReified;
Typing.err_code Typing.ClassGetReified;
]
let allowed_fixme_codes_strict = ref ISet.empty
let set_allow_errors_in_default_path x = allow_errors_in_default_path := x
let is_allowed_code_strict code = ISet.mem code !allowed_fixme_codes_strict
let (get_hh_fixme_pos : (Pos.t -> error_code -> Pos.t option) ref) =
ref (fun _ _ -> None)
let (is_hh_fixme_disallowed : (Pos.t -> error_code -> bool) ref) =
ref (fun _ _ -> false)
let code_agnostic_fixme = ref false
(*****************************************************************************)
(* Errors accumulator. *)
(*****************************************************************************)
(* We still want to error somewhere to avoid silencing any kind of errors, which
* could cause errors to creep into the codebase. *)
let wrap_error_in_different_file ~current_file ~current_span claim reasons =
let reasons = claim :: reasons in
let message =
List.map reasons ~f:(fun (pos, msg) ->
Pos.print_verbose_relative (Pos_or_decl.unsafe_to_raw_pos pos)
^ ": "
^ msg)
in
let stack =
Exception.get_current_callstack_string 99 |> Exception.clean_stack
in
HackEventLogger.type_check_primary_position_bug ~current_file ~message ~stack;
let claim =
if Pos.equal current_span Pos.none then
(Pos.make_from current_file, badpos_message)
else
(current_span, badpos_message_2)
in
(claim, reasons)
(* If primary position in error list isn't in current file, wrap with a sentinel error *)
let check_pos_msg :
Pos.t Message.t * Pos_or_decl.t Message.t list ->
Pos.t Message.t * Pos_or_decl.t Message.t list =
fun (claim, reasons) ->
let pos = fst claim in
let current_file = !current_file in
let current_span = !current_span in
(* If error is reported inside the current span, or no span has been set but the error
* is reported in the current file, then accept the error *)
if
!ignore_pos_outside_current_span
|| Pos.contains current_span pos
|| Pos.equal current_span Pos.none
&& Relative_path.equal (Pos.filename pos) current_file
|| Relative_path.equal current_file Relative_path.default
then
(claim, reasons)
else
wrap_error_in_different_file
~current_file
~current_span
(claim_as_reason claim)
reasons
let add_error_with_fixme_error error explanation =
let User_error.
{ code; claim; reasons = _; quickfixes; custom_msgs; is_fixmed = _ } =
error
in
let (pos, _) = claim in
let pos = Option.value (!get_hh_fixme_pos pos code) ~default:pos in
add_error_impl error;
add_error_impl
@@ User_error.make code (pos, explanation) [] ~quickfixes ~custom_msgs
let add_applied_fixme error =
let error = { error with User_error.is_fixmed = true } in
add_error_impl error
let rec add code pos msg = add_list code (pos, msg) []
and fixme_present (pos : Pos.t) code =
!is_hh_fixme pos code || !is_hh_fixme_disallowed pos code
and add_list code ?quickfixes (claim : _ Message.t) reasons =
add_error @@ User_error.make code claim reasons ?quickfixes
and add_error (error : error) =
let User_error.
{ code; claim; reasons; quickfixes; custom_msgs; is_fixmed = _ } =
error
in
let (claim, reasons) = check_pos_msg (claim, reasons) in
let error = User_error.make code claim reasons ~quickfixes ~custom_msgs in
let pos = fst claim in
if not (fixme_present pos code) then
(* Fixmes and banned decl fixmes are separated by the parser because Errors can't recover
* the position information after the fact. This is the default case, where an HH_FIXME
* comment is not present. Therefore, the remaining cases are variations on behavior when
* a fixme is present *)
add_error_impl error
else if ISet.mem code hard_banned_codes then
let explanation =
Printf.sprintf
"You cannot use `HH_FIXME` or `HH_IGNORE_ERROR` comments to suppress error %d, and this cannot be enabled by configuration"
code
in
add_error_with_fixme_error error explanation
else if Relative_path.(is_hhi (prefix (Pos.filename pos))) then
add_applied_fixme error
else if !report_pos_from_reason && Pos.get_from_reason pos then
let explanation =
"You cannot use `HH_FIXME` or `HH_IGNORE_ERROR` comments to suppress an error whose position was derived from reason information"
in
add_error_with_fixme_error error explanation
else if !is_hh_fixme_disallowed pos code then
let explanation =
Printf.sprintf
"You cannot use `HH_FIXME` or `HH_IGNORE_ERROR` comments to suppress error %d in declarations"
code
in
add_error_with_fixme_error error explanation
else if is_allowed_code_strict code then
add_applied_fixme error
else
let explanation =
Printf.sprintf
"You cannot use `HH_FIXME` or `HH_IGNORE_ERROR` comments to suppress error %d"
code
in
add_error_with_fixme_error error explanation
and merge err' err =
let append _ x y =
let x = Option.value x ~default:[] in
let y = Option.value y ~default:[] in
Some (List.rev_append x y)
in
files_t_merge ~f:append err' err
and incremental_update ~(old : t) ~(new_ : t) ~(rechecked : Relative_path.Set.t)
: t =
(* Helper to detect coding oversight *)
let assert_path_is_real (path : Relative_path.t) : unit =
if Relative_path.equal path Relative_path.default then
Utils.assert_false_log_backtrace
(Some
("Default (untracked) error sources should not get into incremental "
^ "mode. There might be a missing call to `Errors.do_with_context`/"
^ "`run_in_context` somwhere or incorrectly used `Errors.from_error_list`."
))
in
(* Replace old errors with new *)
let res : t =
files_t_merge new_ old ~f:(fun path new_ old ->
assert_path_is_real path;
match new_ with
| Some new_ -> Some new_
| None -> old)
in
(* For files that were rechecked, but had no errors - remove them from maps *)
let res : t =
Relative_path.Set.fold rechecked ~init:res ~f:(fun path acc ->
if Relative_path.Map.mem new_ path then
acc
else
Relative_path.Map.remove acc path)
in
res
let count ?(drop_fixmed = true) err =
files_t_fold
(drop_fixmes_if err drop_fixmed)
~f:(fun _ x acc -> acc + List.length x)
~init:0
let is_empty ?(drop_fixmed = true) err =
Relative_path.Map.is_empty (drop_fixmes_if err drop_fixmed)
let get_current_span () = !current_span
and empty = Relative_path.Map.empty
let from_file_error_list (errors : (Relative_path.t * error) list) : t =
List.fold errors ~init:Relative_path.Map.empty ~f:(fun errors (file, error) ->
let errors_for_file =
Relative_path.Map.find_opt errors file |> Option.value ~default:[]
in
let errors_for_file = error :: errors_for_file in
Relative_path.Map.add errors ~key:file ~data:errors_for_file)
let as_map (t : t) : error list Relative_path.Map.t = t
let merge_into_current errors = error_map := merge errors !error_map
(*****************************************************************************)
(* Accessors. (All methods delegated to the parameterized module.) *)
(*****************************************************************************)
let per_file_error_count ?(drop_fixmed = true) (errors : per_file_errors) : int
=
let errors =
if drop_fixmed then
drop_fixmed_errors errors
else
errors
in
List.length errors
let get_file_errors ?(drop_fixmed = true) (t : t) (file : Relative_path.t) :
per_file_errors =
match Relative_path.Map.find_opt t file with
| None -> []
| Some errors ->
if drop_fixmed then
drop_fixmed_errors errors
else
errors
let iter_error_list ?(drop_fixmed = true) f err =
List.iter ~f (get_sorted_error_list ~drop_fixmed err)
let fold_errors
?(drop_fixmed = true)
(t : t)
~(init : 'a)
~(f : Relative_path.t -> error -> 'a -> 'a) =
let t = drop_fixmes_if t drop_fixmed in
files_t_fold t ~init ~f:(fun source errors acc ->
List.fold_right errors ~init:acc ~f:(f source))
let fold_errors_in
?(drop_fixmed = true)
(t : t)
~(file : Relative_path.t)
~(init : 'a)
~(f : error -> 'a -> 'a) =
let t = drop_fixmes_if t drop_fixmed in
match Relative_path.Map.find_opt t file with
| None -> init
| Some errors -> List.fold_right errors ~init ~f
(* Get paths that have errors which haven't been HH_FIXME'd. *)
let get_failed_files (err : t) =
let err = drop_fixmed_errors_in_files err in
files_t_fold err ~init:Relative_path.Set.empty ~f:(fun source _ acc ->
Relative_path.Set.add acc source)
(* Count errors which haven't been HH_FIXME'd. *)
let error_count : t -> int =
fun errors ->
Relative_path.Map.fold errors ~init:0 ~f:(fun _path errors count ->
count + per_file_error_count ~drop_fixmed:true errors)
exception Done of ISet.t
let first_n_distinct_error_codes ~(n : int) (t : t) : error_code list =
let codes =
try
Relative_path.Map.fold t ~init:ISet.empty ~f:(fun _path errors codes ->
List.fold errors ~init:codes ~f:(fun codes User_error.{ code; _ } ->
let codes = ISet.add code codes in
if ISet.cardinal codes >= n then
raise (Done codes)
else
codes))
with
| Done codes -> codes
in
ISet.elements codes
(* Get the error code of the first error which hasn't been HH_FIXME'd. *)
let choose_code_opt (t : t) : int option =
drop_fixmed_errors_in_files t |> first_n_distinct_error_codes ~n:1 |> List.hd
let as_telemetry : t -> Telemetry.t =
fun errors ->
Telemetry.create ()
|> Telemetry.int_ ~key:"count" ~value:(error_count errors)
|> Telemetry.int_list
~key:"first_5_distinct_error_codes"
~value:
(first_n_distinct_error_codes
~n:5
(drop_fixmed_errors_in_files errors))
(*****************************************************************************)
(* Error code printing. *)
(*****************************************************************************)
let unimplemented_feature pos msg = add 0 pos ("Feature not implemented: " ^ msg)
let experimental_feature pos msg =
add 0 pos ("Cannot use experimental feature: " ^ msg)
(*****************************************************************************)
(* Typing errors *)
(*****************************************************************************)
let log_exception_occurred pos e =
let pos_str = pos |> Pos.to_absolute |> Pos.string in
HackEventLogger.type_check_exn_bug ~path:(Pos.filename pos) ~pos:pos_str ~e;
Hh_logger.error
"Exception while typechecking at position %s\n%s"
pos_str
(Exception.to_string e)
let log_invariant_violation ~desc pos telemetry =
let pos_str = pos |> Pos.to_absolute |> Pos.string in
HackEventLogger.invariant_violation_bug
desc
~path:(Pos.filename pos)
~pos:pos_str
~telemetry;
Hh_logger.error
"Invariant violation at position %s\n%s"
pos_str
Telemetry.(telemetry |> string_ ~key:"desc" ~value:desc |> to_string)
(* The contents of the following error message can trigger `hh rage` in
* sandcastle. If you change it, please make sure the existing trigger in
* `flib/intern/sandcastle/hack/SandcastleCheckHackOnDiffsStep.php` still
* catches this error message. *)
let please_file_a_bug_message =
let hacklang_feedback_support_link =
"https://fb.workplace.com/groups/hackforhiphop/"
in
let hh_rage = Markdown_lite.md_codify "hh rage" in
Printf.sprintf
"Please run %s and post in %s."
hh_rage
hacklang_feedback_support_link
let remediation_message =
Printf.sprintf
"Addressing other errors, restarting the typechecker with %s, or rebasing might resolve this error."
(Markdown_lite.md_codify "hh restart")
let internal_compiler_error_msg =
Printf.sprintf
"Encountered an internal compiler error while typechecking this. %s %s"
remediation_message
please_file_a_bug_message
let invariant_violation pos telemetry desc ~report_to_user =
log_invariant_violation ~desc pos telemetry;
if report_to_user then
add_error
@@ User_error.make
Error_codes.Typing.(to_enum InvariantViolated)
(pos, internal_compiler_error_msg)
[]
let exception_occurred pos exn =
log_exception_occurred pos exn;
add_error
@@ User_error.make
Error_codes.Typing.(to_enum ExceptionOccurred)
(pos, internal_compiler_error_msg)
[]
let internal_error pos msg =
add_error
@@ User_error.make
Error_codes.Typing.(to_enum InternalError)
(pos, "Internal error: " ^ msg)
[]
let typechecker_timeout pos fn_name seconds =
let claim =
( pos,
Printf.sprintf
"Type checker timed out after %d seconds whilst checking function %s"
seconds
fn_name )
in
add_error
@@ User_error.make Error_codes.Typing.(to_enum TypecheckerTimeout) claim []
(*****************************************************************************)
(* Typing decl errors *)
(*****************************************************************************)
(** TODO: Remove use of `User_error.t` representation for nested error *)
let function_is_not_dynamically_callable function_name error =
let function_name = Markdown_lite.md_codify (Render.strip_ns function_name) in
let nested_error_reason = User_error.to_list_ error in
add_list
(User_error.get_code error)
( User_error.get_pos error,
"Function " ^ function_name ^ " is not dynamically callable." )
nested_error_reason
(** TODO: Remove use of `User_error.t` representation for nested error *)
let method_is_not_dynamically_callable
pos
method_name
class_name
support_dynamic_type_attribute
parent_class_opt
error_opt =
let method_name = Markdown_lite.md_codify (Render.strip_ns method_name) in
let class_name = Markdown_lite.md_codify (Render.strip_ns class_name) in
let (code, pos, nested_error_reason) =
match error_opt with
| None -> (Typing.err_code Typing.ImplementsDynamic, pos, [])
| Some error ->
( User_error.get_code error,
User_error.get_pos error,
User_error.to_list_ error )
in
let parent_class_reason =
match parent_class_opt with
| None -> []
| Some (parent_class_pos, parent_class_name) ->
let parent_class_name =
Markdown_lite.md_codify (Render.strip_ns parent_class_name)
in
[
( parent_class_pos,
"Method "
^ method_name
^ " is defined in the super class "
^ parent_class_name
^ " and is not overridden" );
]
in
let attribute_reason =
match support_dynamic_type_attribute with
| true -> []
| false ->
[
( Pos_or_decl.of_raw_pos pos,
"A parameter of "
^ method_name
^ " is not enforceable. "
^ "Try adding the <<"
^ Naming_special_names.UserAttributes.uaSupportDynamicType
^ ">> attribute to "
^ "the method to check if its code is safe for dynamic calling." );
]
in
add_list
code
( pos,
"Method "
^ method_name
^ " in class "
^ class_name
^ " is not dynamically callable." )
(parent_class_reason @ attribute_reason @ nested_error_reason)
(* Raise different types of error for accessing global variables. *)
let global_access_error error_code pos message =
add (GlobalAccessCheck.err_code error_code) pos message
(*****************************************************************************)
(* Printing *)
(*****************************************************************************)
let convert_errors_to_string ?(include_filename = false) (errors : error list) :
string list =
List.fold_right
~init:[]
~f:(fun err acc_out ->
let User_error.
{
code = _;
claim;
reasons;
custom_msgs;
quickfixes = _;
is_fixmed = _;
} =
err
in
let acc_out = custom_msgs @ acc_out in
List.fold_right
~init:acc_out
~f:(fun (pos, msg) acc_in ->
let pos = Pos_or_decl.unsafe_to_raw_pos pos in
let result = Format.asprintf "%a %s" Pos.pp pos msg in
if include_filename then
let full_result =
Printf.sprintf
"%s %s"
(Pos.to_absolute pos |> Pos.filename)
result
in
full_result :: acc_in
else
result :: acc_in)
(claim_as_reason claim :: reasons))
errors
(*****************************************************************************)
(* Try if errors. *)
(*****************************************************************************)
let try_ f1 f2 = try_with_result f1 (fun _ err -> f2 err)
let try_pred ~fail f g = try_with_result_pure ~fail f (fun _ -> g ())
let try_with_error f1 f2 =
try_ f1 (fun error ->
add_error error;
f2 ())
let has_no_errors (f : unit -> 'a) : bool =
try_
(fun () ->
let _ = f () in
true)
(fun _ -> false)
(* Runs f2 on the result only if f1 returns has no errors. *)
let try_if_no_errors f1 f2 =
let (result, error_opt) =
try_with_result
(fun () ->
let result = f1 () in
(result, None))
(fun (result, _none) error -> (result, Some error))
in
match error_opt with
| Some err ->
add_error err;
result
| None -> f2 result
(*****************************************************************************)
(* Do. *)
(*****************************************************************************)
let ignore_ f =
let allow_errors_in_default_path_copy = !allow_errors_in_default_path in
let ignore_pos_outside_current_span_copy = !ignore_pos_outside_current_span in
set_allow_errors_in_default_path true;
ignore_pos_outside_current_span := true;
let (_, result) = do_ f in
set_allow_errors_in_default_path allow_errors_in_default_path_copy;
ignore_pos_outside_current_span := ignore_pos_outside_current_span_copy;
result
let try_when f ~if_error_and:condition ~then_:do_ =
try_with_result f (fun result error ->
if condition () then
do_ error
else
add_error error;
result) |
OCaml Interface | hhvm/hphp/hack/src/errors/errors.mli | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
type error = (Pos.t, Pos_or_decl.t) User_error.t [@@deriving eq, show]
type finalized_error = (Pos.absolute, Pos.absolute) User_error.t
[@@deriving eq, show]
type format =
| Context
| Raw
| Highlighted
| Plain
(** Type representing the errors for a single file. *)
type per_file_errors
(** The type of collections of errors *)
type t [@@deriving eq, show]
val iter : t -> f:(error -> unit) -> unit
module ErrorSet : Caml.Set.S with type elt := error
module FinalizedErrorSet : Caml.Set.S with type elt := finalized_error
(** [t] is an efficient for use inside hh_server or other places that compute errors,
which also supports incremental updates based on file.
But it should not be transferred to other processes such as [hh_client] since they
for instance won't know the Hhi path that was used, and hence can't print errors.
They should use [finalized_error list] instead. *)
val sort_and_finalize : t -> finalized_error list
module Parsing : Error_category.S
module Naming : Error_category.S
module NastCheck : Error_category.S
module Typing : Error_category.S
val read_lines : string -> string list
val num_digits : int -> int
val add_error : error -> unit
(* Error codes that can be suppressed in strict mode with a FIXME based on configuration. *)
val allowed_fixme_codes_strict : ISet.t ref
val report_pos_from_reason : bool ref
val is_strict_code : int -> bool
val set_allow_errors_in_default_path : bool -> unit
val is_hh_fixme : (Pos.t -> int -> bool) ref
val is_hh_fixme_disallowed : (Pos.t -> int -> bool) ref
val get_hh_fixme_pos : (Pos.t -> int -> Pos.t option) ref
val get_current_span : unit -> Pos.t
val fixme_present : Pos.t -> int -> bool
val code_agnostic_fixme : bool ref
val convert_errors_to_string :
?include_filename:bool -> error list -> string list
val combining_sort : 'a list -> f:('a -> string) -> 'a list
val to_string : finalized_error -> string
(** Prints a summary indicating things like how many errors were
found, how many are displayed and how many were dropped. *)
val format_summary :
format ->
displayed_count:int ->
dropped_count:int option ->
max_errors:int option ->
string option
val try_ : (unit -> 'a) -> (error -> 'a) -> 'a
val try_pred : fail:('a -> bool) -> (unit -> 'a) -> (unit -> 'a) -> 'a
val try_with_error : (unit -> 'a) -> (unit -> 'a) -> 'a
val try_with_result : (unit -> 'a) -> ('a -> error -> 'a) -> 'a
val run_and_check_for_errors : (unit -> 'a) -> 'a * bool
(** Return the list of errors caused by the function passed as parameter
along with its result. *)
val do_ : ?apply_fixmes:bool -> ?drop_fixmed:bool -> (unit -> 'a) -> t * 'a
(** Return the list of errors caused by the function passed as parameter
along with its result. *)
val do_with_context :
?drop_fixmed:bool -> Relative_path.t -> (unit -> 'a) -> t * 'a
val run_in_context : Relative_path.t -> (unit -> 'a) -> 'a
(** Turn on lazy decl mode for the duration of the closure.
This runs without returning the original state,
since we collect it later in do_with_lazy_decls_ *)
val run_in_decl_mode : (unit -> 'a) -> 'a
(* Run this function with span for the definition being checked.
* This is used to check that the primary position for errors is not located
* outside the span of the definition.
*)
val run_with_span : Pos.t -> (unit -> 'a) -> 'a
(** ignore errors produced by function passed in argument. *)
val ignore_ : (unit -> 'res) -> 'res
val try_when :
(unit -> 'res) -> if_error_and:(unit -> bool) -> then_:(error -> unit) -> 'res
val has_no_errors : (unit -> 'res) -> bool
val currently_has_errors : unit -> bool
val try_if_no_errors : (unit -> 'res) -> ('res -> 'res) -> 'res
val merge : t -> t -> t
val merge_into_current : t -> unit
(** [incremental_update ~old ~new_ ~rechecked] is for updating errors.
It starts with [old], removes every error in [rechecked],
then adds every error mentioned in [new_]. *)
val incremental_update : old:t -> new_:t -> rechecked:Relative_path.Set.t -> t
val empty : t
val is_empty : ?drop_fixmed:bool -> t -> bool
val count : ?drop_fixmed:bool -> t -> int
val get_error_list : ?drop_fixmed:bool -> t -> error list
val get_sorted_error_list : ?drop_fixmed:bool -> t -> error list
val as_map : t -> error list Relative_path.Map.t
val from_error_list : error list -> t
val drop_fixmed_errors :
('a, 'b) User_error.t list -> ('a, 'b) User_error.t list
val drop_fixmed_errors_in_files : t -> t
val from_file_error_list : (Relative_path.t * error) list -> t
val per_file_error_count : ?drop_fixmed:bool -> per_file_errors -> int
val get_file_errors :
?drop_fixmed:bool -> t -> Relative_path.t -> per_file_errors
val iter_error_list : ?drop_fixmed:bool -> (error -> unit) -> t -> unit
val fold_errors :
?drop_fixmed:bool ->
t ->
init:'a ->
f:(Relative_path.t -> error -> 'a -> 'a) ->
'a
val fold_errors_in :
?drop_fixmed:bool ->
t ->
file:Relative_path.t ->
init:'a ->
f:(error -> 'a -> 'a) ->
'a
val get_failed_files : t -> Relative_path.Set.t
val as_telemetry : t -> Telemetry.t
val choose_code_opt : t -> int option
val compare : error -> error -> int
val compare_finalized : finalized_error -> finalized_error -> int
val sort : error list -> error list
(***************************************
* *
* Specific errors *
* *
***************************************)
val internal_error : Pos.t -> string -> unit
val unimplemented_feature : Pos.t -> string -> unit
val experimental_feature : Pos.t -> string -> unit
(* The intention is to introduce invariant violations with `report_to_user`
set to `false` initially. Then we observe and confirm that the invariant is
not repeatedly violated. Only then, we set it to `true` in a subsequent
release. This should prevent us from blocking users unexpectedly while
gradually introducing signal for unexpected compiler states. *)
val invariant_violation :
Pos.t -> Telemetry.t -> string -> report_to_user:bool -> unit
val exception_occurred : Pos.t -> Exception.t -> unit
val typechecker_timeout : Pos.t -> string -> int -> unit
val method_is_not_dynamically_callable :
Pos.t ->
string ->
string ->
bool ->
(Pos_or_decl.t * string) option ->
(Pos.t, Pos_or_decl.t) User_error.t option ->
unit
val function_is_not_dynamically_callable : string -> error -> unit
val global_access_error :
Error_codes.GlobalAccessCheck.t -> Pos.t -> string -> unit |
Rust | hhvm/hphp/hack/src/errors/errors.rs | // Copyright (c) Meta Platforms, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
mod fmt_plain;
mod fmt_raw;
mod user_error;
use std::io::Write;
pub use fmt_plain::*;
pub use fmt_raw::*;
pub use oxidized::errors::*;
pub use relative_path::RelativePathCtx;
pub use user_error::*;
/// Render this list of errors using the requested error_format.
/// If `is_term` is true, ansi colors and styles will be used according to the format.
/// Absolute paths are formed (at the discretion of the error format) from error
/// positions using the provided RelativePathCtx.
pub fn print_error_list<'e, I>(
mut w: impl Write,
is_term: bool,
roots: &RelativePathCtx,
error_format: Format,
errs: I,
) -> std::io::Result<()>
where
I: IntoIterator<Item = &'e Error>,
{
match error_format {
Format::Plain => {
for err in errs {
writeln!(w, "{}", FmtPlain(err, roots))?;
}
}
Format::Raw => {
for err in errs {
writeln!(w, "{}", FmtRaw(err, roots, is_term))?;
}
}
bad => todo!("{bad}"),
}
Ok(())
} |
OCaml | hhvm/hphp/hack/src/errors/error_category.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.
*
*)
module type S = sig
type t [@@deriving enum, show]
val err_code : t -> int
end |
OCaml | hhvm/hphp/hack/src/errors/error_codes.ml | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(*****************************************************************************)
(* Error codes.
* Each error has a unique number associated with it. The following modules
* define the error code associated with each kind of error.
* It is ok to extend the codes with new values, it is NOT OK to change the
* value of an existing error to a different error code!
*
* When removing error codes, you should NOT delete them! Instead, prefer to
* comment them out as documentation and append DEPRECATED to the name.
* See below for plenty of examples.
*)
(*****************************************************************************)
module Parsing = struct
type t =
| FixmeFormat [@value 1001]
| ParsingError [@value 1002]
(* | UnexpectedEofDEPRECATED [@value 1003] *)
(* | UnterminatedCommentDEPRECATED [@value 1004] *)
(* | UnterminatedXhpCommentDEPRECATED [@value 1005] *)
(* | CallTimePassByReferenceDEPRECATED [@value 1006] *)
| XhpParsingError [@value 1007]
| HhIgnoreComment [@value 1008]
| PackageConfigError [@value 1009]
(* Add new Parsing codes here! Comment out when deprecating. *)
[@@deriving enum, show { with_path = false }]
let err_code = to_enum
end
module Naming = struct
type t =
| AddATypehint [@value 2001]
(* | TypeparamAlokDEPRECATED [@value 2002] *)
| AssertArity [@value 2003]
| PrimitiveInvalidAlias [@value 2004]
(* | CyclicConstraintDEPRECATED [@value 2005] *)
| DidYouMeanNaming [@value 2006]
(* | DifferentScopeDEPRECATED [@value 2007] *)
| DisallowedXhpType [@value 2008]
(* | DoubleInsteadOfFloatDEPRECATED [@value 2009] *)
(* | DynamicClassDEPRECATED [@value 2010] *)
| LvarInObjGet [@value 2011]
| ErrorNameAlreadyBound [@value 2012]
| ExpectedCollection [@value 2013]
| ExpectedVariable [@value 2014]
| FdNameAlreadyBound [@value 2015]
(* | GenArrayRecArityDEPRECATED [@value 2016] *)
(* | GenArrayVaRecArityDEPRECATED [@value 2017] *)
(* | GenaArityDEPRECATED [@value 2018] *)
(* | GenericClassVarDEPRECATED [@value 2019] *)
(* | GenvaArityDEPRECATED [@value 2020] *)
| IllegalClass [@value 2021]
| IllegalClassMeth [@value 2022]
| IllegalConstant [@value 2023]
| IllegalFun [@value 2024]
| IllegalInstMeth [@value 2025]
| IllegalMethCaller [@value 2026]
| IllegalMethFun [@value 2027]
(* | IntegerInsteadOfIntDEPRECATED [@value 2028] *)
| InvalidReqExtends [@value 2029]
| InvalidReqImplements [@value 2030]
(* | LocalConstDEPRECATED [@value 2031] *)
| LowercaseThis [@value 2032]
| MethodNameAlreadyBound [@value 2033]
| MissingArrow [@value 2034]
| MissingTypehint [@value 2035]
| NameAlreadyBound [@value 2036]
| NamingTooFewArguments [@value 2037]
| NamingTooManyArguments [@value 2038]
| PrimitiveToplevel [@value 2039]
(* | RealInsteadOfFloatDEPRECATED [@value 2040] *)
| ShadowedTypeParam [@value 2041]
| StartWith_T [@value 2042]
| ThisMustBeReturn [@value 2043]
| ThisNoArgument [@value 2044]
| ThisHintOutsideClass [@value 2045]
| ThisReserved [@value 2046]
| HigherKindedTypesUnsupportedFeature [@value 2047]
(* | TypedefConstraintDEPRECATED [@value 2048] *)
| UnboundName [@value 2049]
| Undefined [@value 2050]
| UnexpectedArrow [@value 2051]
| UnexpectedTypedef [@value 2052]
| UsingInternalClass [@value 2053]
| VoidCast [@value 2054]
| ObjectCast [@value 2055]
| UnsetCast [@value 2056]
(* | NullsafePropertyAccessDEPRECATED [@value 2057] *)
| IllegalTrait [@value 2058]
(* | ShapeTypehintDEPRECATED [@value 2059] *)
| DynamicNewInStrictMode [@value 2060]
| InvalidTypeAccessRoot [@value 2061]
| DuplicateUserAttribute [@value 2062]
| ReturnOnlyTypehint [@value 2063]
| UnexpectedTypeArguments [@value 2064]
| TooManyTypeArguments [@value 2065]
| ClassnameParam [@value 2066]
(* | InvalidInstanceofDEPRECATED [@value 2067] *)
| NameIsReserved [@value 2068]
| DollardollarUnused [@value 2069]
| IllegalMemberVariableClass [@value 2070]
| TooFewTypeArguments [@value 2071]
(* | GotoLabelAlreadyDefinedDEPRECATED [@value 2072] *)
(* | GotoLabelUndefinedDEPRECATED [@value 2073] *)
(* | GotoLabelDefinedInFinallyDEPRECATED [@value 2074] *)
(* | GotoInvokedInFinallyDEPRECATED [@value 2075] *)
(* | DynamicClassPropertyNameInStrictModeDEPRECATED [@value 2076] *)
| ThisAsLexicalVariable [@value 2077]
| DynamicClassNameInStrictMode [@value 2078]
| XhpOptionalRequiredAttr [@value 2079]
| XhpRequiredWithDefault [@value 2080]
(* | VariableVariablesDisallowedDEPRECATED [@value 2081] *)
| ArrayTypehintsDisallowed [@value 2082]
(* | ArrayLiteralsDisallowedDEPRECATED [@value 2083] *)
| WildcardHintDisallowed [@value 2084]
(* | AttributeClassNameConflictDEPRECATED [@value 2085] *)
| MethodNeedsVisibility [@value 2086]
(* | ReferenceInStrictModeDEPRECATED [@value 2087] *)
(* | ReferenceInRxDEPRECATED [@value 2088] *)
(* | DeclareStatementDEPRECATED [@value 2089] *)
(* | MisplacedRxOfScopeDEPRECATED [@value 2090] *)
(* | RxOfScopeAndExplicitRxDEPRECATED [@value 2091] *)
(* | UnsupportedFeatureDEPRECATED [@value 2092] *)
(* | TraitInterfaceConstructorPromoDEPRECATED [@value 2093] *)
| NonstaticPropertyWithLSB [@value 2094]
(* | ReferenceInAnonUseClauseDEPRECATED [@value 2095] *)
(* | RxMoveInvalidLocationDEPRECATED [@value 2096] *)
(* | MisplacedMutabilityHintDEPRECATED [@value 2097] *)
(* | MutabilityHintInNonRxDEPRECATED [@value 2098] *)
(* | InvalidReturnMutableHintDEPRECATED [@value 2099] *)
(* | NoTparamsOnTypeConstsDEPRECATED [@value 2100] *)
(* | PocketUniversesDuplicationDEPRECATED [@value 2101] *)
| UnsupportedTraitUseAs [@value 2102]
| UnsupportedInsteadOf [@value 2103]
(* | InvalidTraitUseAsVisibilityDEPRECATED [@value 2104] *)
| InvalidFunPointer [@value 2105]
| IllegalUseOfDynamicallyCallable [@value 2106]
(* | PocketUniversesNotInClassDEPRECATED [@value 2107] *)
(* | PocketUniversesAtomMissingDEPRECATED [@value 2108] *)
(* | PocketUniversesAtomUnknownDEPRECATED [@value 2109] *)
(* | PocketUniversesLocalizationDEPRECATED [@value 2110] *)
| ClassMethNonFinalSelf [@value 2111]
| ParentInFunctionPointer [@value 2112]
| SelfInNonFinalFunctionPointer [@value 2113]
| ClassMethNonFinalCLASS [@value 2114]
| WildcardTypeParamDisallowed [@value 2115]
(* | CallingAssertDEPRECATED [@value 2116] *)
| InvalidWildcardContext [@value 2117]
| ExplicitConsistentConstructor [@value 2118]
| InvalidReqClass [@value 2119]
| ModuleDeclarationOutsideAllowedFiles [@value 2120]
| DynamicMethodAccess [@value 2121]
| TypeConstantInEnumClassOutsideAllowedLocations [@value 2122]
| InvalidBuiltinType [@value 2123]
| InvalidMemoizeLabel [@value 2124]
| DynamicHintDisallowed [@value 2125]
| IllegalTypedLocal [@value 2126]
(* Add new Naming codes here! Comment out when deprecating. *)
[@@deriving enum, show { with_path = false }]
let err_code = to_enum
end
module NastCheck = struct
type t =
| AbstractBody [@value 3001]
| AbstractWithBody [@value 3002]
| AwaitInSyncFunction [@value 3003]
| CallBeforeInit [@value 3004]
| CaseFallthrough [@value 3005]
| ContinueInSwitch [@value 3006]
(* | DangerousMethodNameDEPRECATED [@value 3007] *)
| DefaultFallthrough [@value 3008]
| InterfaceWithMemberVariable [@value 3009]
| InterfaceWithStaticMemberVariable [@value 3010]
| Magic [@value 3011]
| NoConstructParent [@value 3012]
| NonInterface [@value 3013]
| NotAbstractWithoutBody [@value 3014]
| NotInitialized [@value 3015]
| NotPublicInterface [@value 3016]
| RequiresNonClass [@value 3017]
| ReturnInFinally [@value 3018]
| ReturnInGen [@value 3019]
| ToStringReturnsString [@value 3020]
| ToStringVisibility [@value 3021]
| ToplevelBreak [@value 3022]
| ToplevelContinue [@value 3023]
| UsesNonTrait [@value 3024]
| IllegalFunctionName [@value 3025]
| NotAbstractWithoutTypeconst [@value 3026]
| TypeconstDependsOnExternalTparam [@value 3027]
(* | TypeconstAssignedTparamDEPRECATED [@value 3028] *)
(* | AbstractWithTypeconstDEPRECATED [@value 3029] *)
| ConstructorRequired [@value 3030]
| InterfaceWithPartialTypeconst [@value 3031]
| MultipleXhpCategory [@value 3032]
(* | OptionalShapeFieldsNotSupportedDEPRECATED [@value 3033] *)
(* | AwaitNotAllowedDEPRECATED [@value 3034] *)
(* | AsyncInInterfaceDEPRECATED [@value 3035] *)
(* | AwaitInCoroutineDEPRECATED [@value 3036] *)
(* | YieldInCoroutineDEPRECATED [@value 3037] *)
(* | SuspendOutsideOfCoroutineDEPRECATED [@value 3038] *)
(* | SuspendInFinallyDEPRECATED [@value 3039] *)
(* | BreakContinueNNotSupportedDEPRECATED [@value 3040] *)
| StaticMemoizedFunction [@value 3041]
(* | InoutParamsInCoroutineDEPRECATED [@value 3042] *)
| InoutParamsSpecial [@value 3043]
(* | InoutParamsMixByrefDEPRECATED [@value 3044] *)
| InoutParamsMemoize [@value 3045]
(* | InoutParamsRetByRefDEPRECATED [@value 3046] *)
| ReadingFromAppend [@value 3047]
(* | ConstAttributeProhibitedDEPRECATED [@value 3048] *)
(* | GlobalInReactiveContextDEPRECATED [@value 3049] *)
(* | InoutArgumentBadExprDEPRECATED [@value 3050] *)
(* | MutableParamsOutsideOfSyncDEPRECATED [@value 3051] *)
(* | MutableAsyncMethodDEPRECATED [@value 3052] *)
(* | MutableMethodsMustBeReactiveDEPRECATED [@value 3053] *)
(* | MutableAttributeOnFunctionDEPRECATED [@value 3054] *)
(* | MutableReturnAnnotatedDeclsMustBeReactiveDEPRECATED [@value 3055] *)
| IllegalDestructor [@value 3056]
(* | ConditionallyReactiveFunctionDEPRECATED [@value 3057] *)
(* | MultipleConditionallyReactiveAnnotationsDEPRECATED [@value 3058] *)
(* | ConditionallyReactiveAnnotationInvalidArgumentsDEPRECATED [@value 3059] *)
(* | MissingReactivityForConditionDEPRECATED [@value 3060] *)
(* | MultipleReactivityAnnotationsDEPRECATED [@value 3061] *)
(* | RxIsEnabledInvalidLocationDEPRECATED [@value 3062] *)
(* | MaybeRxInvalidLocationDEPRECATED [@value 3063] *)
(* | NoOnlyrxIfRxfuncForRxIfArgsDEPRECATED [@value 3064] *)
(* | CoroutineInConstructorDEPRECATED [@value 3065] *)
(* | IllegalReturnByRefDEPRECATED [@value 3066] *)
(* | IllegalByRefExprDEPRECATED [@value 3067] *)
(* | VariadicByRefParamDEPRECATED [@value 3068] *)
(* | MaybeMutableAttributeOnFunctionDEPRECATED [@value 3069] *)
(* | ConflictingMutableAndMaybeMutableAttributesDEPRECATED [@value 3070] *)
(* | MaybeMutableMethodsMustBeReactiveDEPRECATED [@value 3071] *)
| RequiresFinalClass [@value 3072]
| InterfaceUsesTrait [@value 3073]
| NonstaticMethodInAbstractFinalClass [@value 3074]
(* | MutableOnStaticDEPRECATED [@value 3075] *)
(* | ClassnameConstInstanceOfDEPRECATED [@value 3076] *)
(* | ByRefParamOnConstructDEPRECATED [@value 3077] *)
(* | ByRefDynamicCallDEPRECATED [@value 3078] *)
(* | ByRefPropertyDEPRECATED [@value 3079] *)
(* | ByRefCallDEPRECATED [@value 3080] *)
| SwitchNonTerminalDefault [@value 3081]
| SwitchMultipleDefault [@value 3082]
| RepeatedRecordFieldName [@value 3083]
| PhpLambdaDisallowed [@value 3084]
| EntryPointArguments [@value 3085]
| VariadicMemoize [@value 3086]
| AbstractMethodMemoize [@value 3087]
| InstancePropertyInAbstractFinalClass [@value 3088]
| DynamicallyCallableReified [@value 3089]
| IllegalContext [@value 3090]
(* | InvalidConstFunAttributeDEPRECATED [@value 3091] *)
| ListRvalue [@value 3092]
| PartiallyAbstractTypeconstDefinition [@value 3093]
| EntryPointGenerics [@value 3094]
| InternalProtectedOrPrivate [@value 3095]
| InoutInTransformedPsuedofunction [@value 3096]
| PrivateAndFinal [@value 3097]
(* | InternalOutsideModuleDEPRECATED [@value 3098] *)
| InternalMemberInsidePublicTrait [@value 3099]
| AttributeConflictingMemoize [@value 3100]
| RefinementInTypeStruct [@value 3101]
| Soft_internal_without_internal [@value 3102]
(* Add new NastCheck codes here! Comment out when deprecating. *)
[@@deriving enum, show { with_path = false }]
let err_code = to_enum
end
module Typing = struct
type t =
| InternalError [@value 0]
(* | AbstractClassFinalDEPRECATED [@value 4001] *)
| UninstantiableClass [@value 4002]
(* | AnonymousRecursiveDEPRECATED [@value 4003] *)
(* | AnonymousRecursiveCallDEPRECATED [@value 4004] *)
| ArrayAccessRead [@value 4005]
| ArrayAppend [@value 4006]
| ArrayCast [@value 4007]
| ArrayGetArity [@value 4008]
| BadCall [@value 4009]
(* | ClassArityDEPRECATED [@value 4010] *)
| ConstMutation [@value 4011]
| ConstructorNoArgs [@value 4012]
| CyclicClassDef [@value 4013]
| CyclicTypedef [@value 4014]
| DiscardedAwaitable [@value 4015]
| IssetEmptyInStrict [@value 4016]
(* | DynamicYieldPrivateDEPRECATED [@value 4017] *)
| EnumConstantTypeBad [@value 4018]
| EnumSwitchNonexhaustive [@value 4019]
| EnumSwitchNotConst [@value 4020]
| EnumSwitchRedundant [@value 4021]
| EnumSwitchRedundantDefault [@value 4022]
| EnumSwitchWrongClass [@value 4023]
| EnumTypeBad [@value 4024]
(* | EnumTypeTypedefMixedDEPRECATED [@value 4025] *)
| ExpectedClass [@value 4026]
| ExpectedLiteralFormatString [@value 4027]
(* | ExpectedStaticIntDEPRECATED [@value 4028] *)
| ExpectedTparam [@value 4029]
| ExpectingReturnTypeHint [@value 4030]
(* | ExpectingReturnTypeHintSuggestDEPRECATED [@value 4031] *)
| ExpectingTypeHint [@value 4032]
| ExpectingTypeHintVariadic [@value 4033]
(* | RetiredError4034DEPRECATED [@value 4034] *)
| ExtendFinal [@value 4035]
| FieldKinds [@value 4036]
(* | FieldMissingDEPRECATED [@value 4037] *)
| FormatString [@value 4038]
| FunArityMismatch [@value 4039]
| FunTooFewArgs [@value 4040]
| FunTooManyArgs [@value 4041]
| FunUnexpectedNonvariadic [@value 4042]
| FunVariadicityHhVsPhp56 [@value 4043]
(* | GenaExpectsArrayDEPRECATED [@value 4044] *)
| GenericArrayStrict [@value 4045]
| GenericStatic [@value 4046]
| ImplementAbstract [@value 4047]
(* | InterfaceFinalDEPRECATED [@value 4048] *)
| InvalidShapeFieldConst [@value 4049]
| InvalidShapeFieldLiteral [@value 4050]
| InvalidShapeFieldName [@value 4051]
| InvalidShapeFieldType [@value 4052]
| MemberNotFound [@value 4053]
| MemberNotImplemented [@value 4054]
| MissingAssign [@value 4055]
| MissingConstructor [@value 4056]
| MissingField [@value 4057]
(* | NegativeTupleIndexDEPRECATED [@value 4058] *)
| SelfOutsideClass [@value 4059]
| NewStaticInconsistent [@value 4060]
| StaticOutsideClass [@value 4061]
| NonObjectMemberRead [@value 4062]
| NullContainer [@value 4063]
| NullMemberRead [@value 4064]
(* | NullableParameterDEPRECATED [@value 4065] *)
| OptionReturnOnlyTypehint [@value 4066]
| ObjectString [@value 4067]
(* | OptionMixedDEPRECATED [@value 4068] *)
(* | OverflowDEPRECATED [@value 4069] *)
| OverrideFinal [@value 4070]
| OverridePerTrait [@value 4071]
(* | PairArityDEPRECATED [@value 4072] *)
| AbstractCall [@value 4073]
| ParentInTrait [@value 4074]
| ParentOutsideClass [@value 4075]
| ParentUndefined [@value 4076]
| PreviousDefault [@value 4077]
| PrivateClassMeth [@value 4078]
| PrivateInstMeth [@value 4079]
| PrivateOverride [@value 4080]
| ProtectedClassMeth [@value 4081]
| ProtectedInstMeth [@value 4082]
| ReadBeforeWrite [@value 4083]
| ReturnInVoid [@value 4084]
| ShapeFieldClassMismatch [@value 4085]
| ShapeFieldTypeMismatch [@value 4086]
| ShouldNotBeOverride [@value 4087]
(* | SketchyNullCheckDEPRECATED [@value 4088] *)
(* | SketchyNullCheckPrimitiveDEPRECATED [@value 4089] *)
| SmemberNotFound [@value 4090]
| StaticDynamic [@value 4091]
(* | StaticOverflowDEPRECATED [@value 4092] *)
(* | RetiredError4093DEPRECATED [@value 4093] *)
(* | ThisInStaticDEPRECATED [@value 4094] *)
| ThisVarOutsideClass [@value 4095]
(* | TraitFinalDEPRECATED [@value 4096] *)
(* | TupleArityDEPRECATED [@value 4097] *)
(* | TupleArityMismatchDEPRECATED [@value 4098] *)
(* | TupleIndexTooLargeDEPRECATED [@value 4099] *)
| TupleSyntax [@value 4100]
| TypeArityMismatch [@value 4101]
(* | TypeParamArityDEPRECATED [@value 4102] *)
(* | RetiredError4103DEPRECATED [@value 4103] *)
| TypingTooFewArgs [@value 4104]
| TypingTooManyArgs [@value 4105]
| UnboundGlobal [@value 4106]
| UnboundNameTyping [@value 4107]
| UndefinedField [@value 4108]
| UndefinedParent [@value 4109]
| UnifyError [@value 4110]
| UnsatisfiedReq [@value 4111]
| Visibility [@value 4112]
| VisibilityExtends [@value 4113]
(* | VoidParameterDEPRECATED [@value 4114] *)
| WrongExtendKind [@value 4115]
| GenericUnify [@value 4116]
(* | NullsafeNotNeededDEPRECATED [@value 4117] *)
| TrivialStrictEq [@value 4118]
| VoidUsage [@value 4119]
| DeclaredCovariant [@value 4120]
| DeclaredContravariant [@value 4121]
(* | UnsetInStrictDEPRECATED [@value 4122] *)
| StrictMembersNotKnown [@value 4123]
| ErasedGenericAtRuntime [@value 4124]
(* | DynamicClassDEPRECATED [@value 4125] *)
| AttributeTooManyArguments [@value 4126]
| AttributeParamType [@value 4127]
| DeprecatedUse [@value 4128]
| AbstractConstUsage [@value 4129]
| CannotDeclareConstant [@value 4130]
| CyclicTypeconst [@value 4131]
| NullsafePropertyWriteContext [@value 4132]
| NoreturnUsage [@value 4133]
(* | ThisLvalueDEPRECATED [@value 4134] *)
| UnsetNonidxInStrict [@value 4135]
| InvalidShapeFieldNameEmpty [@value 4136]
(* | InvalidShapeFieldNameNumberDEPRECATED [@value 4137] *)
| ShapeFieldsUnknown [@value 4138]
| InvalidShapeRemoveKey [@value 4139]
(* | MissingOptionalFieldDEPRECATED [@value 4140] *)
| ShapeFieldUnset [@value 4141]
| AbstractConcreteOverride [@value 4142]
| LocalVariableModifedAndUsed [@value 4143]
| LocalVariableModifedTwice [@value 4144]
| AssignDuringCase [@value 4145]
| CyclicEnumConstraint [@value 4146]
| UnpackingDisallowed [@value 4147]
| InvalidClassname [@value 4148]
| InvalidMemoizedParam [@value 4149]
| IllegalTypeStructure [@value 4150]
| NotNullableCompareNullTrivial [@value 4151]
(* | ClassPropertyOnlyStaticLiteralDEPRECATED [@value 4152] *)
| AttributeTooFewArguments [@value 4153]
(* | ReferenceExprDEPRECATED [@value 4154] *)
| UnificationCycle [@value 4155]
| KeysetSet [@value 4156]
| EqIncompatibleTypes [@value 4157]
| ContravariantThis [@value 4158]
(* | InstanceofAlwaysFalseDEPRECATED [@value 4159] *)
(* | InstanceofAlwaysTrueDEPRECATED [@value 4160] *)
(* | AmbiguousMemberDEPRECATED [@value 4161] *)
(* | InstanceofGenericClassnameDEPRECATED [@value 4162] *)
| RequiredFieldIsOptional [@value 4163]
| FinalProperty [@value 4164]
| ArrayGetWithOptionalField [@value 4165]
| UnknownFieldDisallowedInShape [@value 4166]
| NullableCast [@value 4167]
(* | PassByRefAnnotationMissingDEPRECATED [@value 4168] *)
(* | NonCallArgumentInSuspendDEPRECATED [@value 4169] *)
(* | NonCoroutineCallInSuspendDEPRECATED [@value 4170] *)
(* | CoroutineCallOutsideOfSuspendDEPRECATED [@value 4171] *)
(* | FunctionIsNotCoroutineDEPRECATED [@value 4172] *)
(* | CoroutinnessMismatchDEPRECATED [@value 4173] *)
(* | ExpectingAwaitableReturnTypeHintDEPRECATED [@value 4174] *)
(* | ReffinessInvariantDEPRECATED [@value 4175] *)
(* | DollardollarLvalueDEPRECATED [@value 4176] *)
(* | StaticMethodOnInterfaceDEPRECATED [@value 4177] *)
| DuplicateUsingVar [@value 4178]
| IllegalDisposable [@value 4179]
| EscapingDisposable [@value 4180]
(* | PassByRefAnnotationUnexpectedDEPRECATED [@value 4181] *)
| InoutAnnotationMissing [@value 4182]
| InoutAnnotationUnexpected [@value 4183]
| InoutnessMismatch [@value 4184]
| StaticSyntheticMethod [@value 4185]
| TraitReuse [@value 4186]
| InvalidNewDisposable [@value 4187]
| EscapingDisposableParameter [@value 4188]
| AcceptDisposableInvariant [@value 4189]
| InvalidDisposableHint [@value 4190]
| XhpRequired [@value 4191]
| EscapingThis [@value 4192]
| IllegalXhpChild [@value 4193]
| MustExtendDisposable [@value 4194]
| InvalidIsAsExpressionHint [@value 4195]
| AssigningToConst [@value 4196]
| SelfConstParentNot [@value 4197]
(* | ParentConstSelfNotDEPRECATED [@value 4198] *)
(* | PartiallyValidIsAsExpressionHintDEPRECATED [@value 4199] *)
(* | NonreactiveFunctionCallDEPRECATED [@value 4200] *)
(* | NonreactiveIndexingDEPRECATED [@value 4201] *)
(* | ObjSetReactiveDEPRECATED [@value 4202] *)
(* | FunReactivityMismatchDEPRECATED [@value 4203] *)
| OverridingPropConstMismatch [@value 4204]
| InvalidReturnDisposable [@value 4205]
| InvalidDisposableReturnHint [@value 4206]
| ReturnDisposableMismatch [@value 4207]
| InoutArgumentBadType [@value 4208]
(* | InconsistentUnsetDEPRECATED [@value 4209] *)
(* | ReassignMutableVarDEPRECATED [@value 4210] *)
(* | InvalidFreezeTargetDEPRECATED [@value 4211] *)
(* | InvalidFreezeUseDEPRECATED [@value 4212] *)
(* | FreezeInNonreactiveContextDEPRECATED [@value 4213] *)
(* | MutableCallOnImmutableDEPRECATED [@value 4214] *)
(* | MutableArgumentMismatchDEPRECATED [@value 4215] *)
(* | InvalidMutableReturnResultDEPRECATED [@value 4216] *)
(* | MutableReturnResultMismatchDEPRECATED [@value 4217] *)
(* | NonreactiveCallFromShallowDEPRECATED [@value 4218] *)
| EnumTypeTypedefNonnull [@value 4219]
(* | RxEnabledInNonRxContextDEPRECATED [@value 4220] *)
(* | RxEnabledInLambdasDEPRECATED [@value 4221] *)
| AmbiguousLambda [@value 4222]
| EllipsisStrictMode [@value 4223]
(* | UntypedLambdaStrictModeDEPRECATED [@value 4224] *)
(* | BindingRefInArrayDEPRECATED [@value 4225] *)
| OutputInWrongContext [@value 4226]
(* | SuperglobalInReactiveContextDEPRECATED [@value 4227] *)
| StaticPropertyInWrongContext [@value 4228]
(* | StaticInReactiveContextDEPRECATED [@value 4229] *)
(* | GlobalInReactiveContextDEPRECATED [@value 4230] *)
| WrongExpressionKindAttribute [@value 4231]
(* | AttributeClassNoConstructorArgsDEPRECATED [@value 4232] *)
(* | InvalidTypeForOnlyrxIfRxfuncParameterDEPRECATED [@value 4233] *)
(* | MissingAnnotationForOnlyrxIfRxfuncParameterDEPRECATED [@value 4234] *)
(* | CannotReturnBorrowedValueAsImmutableDEPRECATED [@value 4235] *)
| DeclOverrideMissingHint [@value 4236]
(* | InvalidConditionallyReactiveCallDEPRECATED [@value 4237] *)
| ExtendSealed [@value 4238]
(* | SealedFinalDEPRECATED [@value 4239] *)
| ComparisonInvalidTypes [@value 4240]
(* | OptionVoidDEPRECATED [@value 4241] *)
(* | MutableInNonreactiveContextDEPRECATED [@value 4242] *)
(* | InvalidArgumentOfRxMutableFunctionDEPRECATED [@value 4243] *)
(* | LetVarImmutabilityViolationDEPRECATED [@value 4244] *)
(* | UnsealableDEPRECATED [@value 4245] *)
(* | ReturnVoidToRxMismatchDEPRECATED [@value 4246] *)
(* | ReturnsVoidToRxAsNonExpressionStatementDEPRECATED [@value 4247] *)
(* | NonawaitedAwaitableInReactiveContextDEPRECATED [@value 4248] *)
| ShapesKeyExistsAlwaysTrue [@value 4249]
| ShapesKeyExistsAlwaysFalse [@value 4250]
| ShapesMethodAccessWithNonExistentField [@value 4251]
| NonClassMember [@value 4252]
(* | PassingArrayCellByRefDEPRECATED [@value 4253] *)
(* | CallSiteReactivityMismatchDEPRECATED [@value 4254] *)
(* | RxParameterConditionMismatchDEPRECATED [@value 4255] *)
| AmbiguousObjectAccess [@value 4256]
(* | ExtendPPLDEPRECATED [@value 4257] *)
(* | ReassignMaybeMutableVarDEPRECATED [@value 4258] *)
(* | MaybeMutableArgumentMismatchDEPRECATED [@value 4259] *)
(* | ImmutableArgumentMismatchDEPRECATED [@value 4260] *)
(* | ImmutableCallOnMutableDEPRECATED [@value 4261] *)
(* | InvalidCallMaybeMutableDEPRECATED [@value 4262] *)
(* | MutabilityMismatchDEPRECATED [@value 4263] *)
(* | InvalidPPLCallDEPRECATED [@value 4264] *)
(* | InvalidPPLStaticCallDEPRECATED [@value 4265] *)
(* | TypeTestInLambdaDEPRECATED [@value 4266] *)
(* | InvalidTraversableInRxDEPRECATED [@value 4267] *)
(* | ReassignMutableThisDEPRECATED [@value 4268] *)
(* | MutableExpressionAsMultipleMutableArgumentsDEPRECATED [@value 4269] *)
(* | InvalidUnsetTargetInRxDEPRECATED [@value 4270] *)
(* | CoroutineOutsideExperimentalDEPRECATED [@value 4271] *)
(* | PPLMethPointerDEPRECATED [@value 4272] *)
(* | InvalidTruthinessTestDEPRECATED [@value 4273] *)
| RePrefixedNonString [@value 4274]
| BadRegexPattern [@value 4275]
(* | SketchyTruthinessTestDEPRECATED [@value 4276] *)
| LateInitWithDefault [@value 4277]
| OverrideMemoizeLSB [@value 4278]
| ClassVarTypeGenericParam [@value 4279]
| InvalidSwitchCaseValueType [@value 4280]
| StringCast [@value 4281]
| BadLateInitOverride [@value 4282]
(* | EscapingMutableObjectDEPRECATED [@value 4283] *)
| OverrideLSB [@value 4284]
| MultipleConcreteDefs [@value 4285]
(* | MoveInNonreactiveContextDEPRECATED [@value 4286] *)
| InvalidMoveUse [@value 4287]
| InvalidMoveTarget [@value 4288]
(* | IgnoredResultOfFreezeDEPRECATED [@value 4289] *)
(* | IgnoredResultOfMoveDEPRECATED [@value 4290] *)
| UnexpectedTy [@value 4291]
| UnserializableType [@value 4292]
(* | InconsistentMutabilityDEPRECATED [@value 4293] *)
(* | InvalidMutabilityFlavorInAssignmentDEPRECATED [@value 4294] *)
(* | OptionNullDEPRECATED [@value 4295] *)
| UnknownObjectMember [@value 4296]
| UnknownType [@value 4297]
| InvalidArrayKeyRead [@value 4298]
(* | ReferenceExprNotFunctionArgDEPRECATED [@value 4299] *)
(* | RedundantRxConditionDEPRECATED [@value 4300] *)
| RedeclaringMissingMethod [@value 4301]
| InvalidEnforceableTypeArgument [@value 4302]
| RequireArgsReify [@value 4303]
| TypecheckerTimeout [@value 4304]
| InvalidReifiedArgument [@value 4305]
| GenericsNotAllowed [@value 4306]
| InvalidNewableTypeArgument [@value 4307]
| InvalidNewableTypeParamConstraints [@value 4308]
| NewWithoutNewable [@value 4309]
| NewClassReified [@value 4310]
| MemoizeReified [@value 4311]
| ConsistentConstructReified [@value 4312]
| MethodVariance [@value 4313]
| MissingXhpRequiredAttr [@value 4314]
| BadXhpAttrRequiredOverride [@value 4315]
(* | ReifiedTparamVariadicDEPRECATED [@value 4316] *)
| UnresolvedTypeVariable [@value 4317]
| InvalidSubString [@value 4318]
| InvalidArrayKeyConstraint [@value 4319]
| OverrideNoDefaultTypeconst [@value 4320]
| ShapeAccessWithNonExistentField [@value 4321]
| DisallowPHPArraysAttr [@value 4322]
| TypeConstraintViolation [@value 4323]
| IndexTypeMismatch [@value 4324]
| ExpectedStringlike [@value 4325]
| TypeConstantMismatch [@value 4326]
(* | TypeConstantRedeclarationDEPRECATED [@value 4327] *)
| ConstantDoesNotMatchEnumType [@value 4328]
| EnumConstraintMustBeArraykey [@value 4329]
| EnumSubtypeMustHaveCompatibleConstraint [@value 4330]
| ParameterDefaultValueWrongType [@value 4331]
| NewtypeAliasMustSatisfyConstraint [@value 4332]
(* | BadFunctionTypevarDEPRECATED [@value 4333] *)
(* | BadClassTypevarDEPRECATED [@value 4334] *)
(* | BadMethodTypevarDEPRECATED [@value 4335] *)
| MissingReturnInNonVoidFunction [@value 4336]
| InoutReturnTypeMismatch [@value 4337]
| ClassConstantValueDoesNotMatchHint [@value 4338]
| ClassPropertyInitializerTypeDoesNotMatchHint [@value 4339]
| BadDeclOverride [@value 4340]
| BadMethodOverride [@value 4341]
| BadEnumExtends [@value 4342]
| XhpAttributeValueDoesNotMatchHint [@value 4343]
| TraitPropConstClass [@value 4344]
| EnumUnderlyingTypeMustBeArraykey [@value 4345]
| ClassGetReified [@value 4346]
| RequireGenericExplicit [@value 4347]
| ClassConstantTypeMismatch [@value 4348]
(* | PocketUniversesExpansionDEPRECATED [@value 4349] *)
(* | PocketUniversesTypingDEPRECATED [@value 4350] *)
| RecordInitValueDoesNotMatchHint [@value 4351]
| AbstractTconstNotAllowed [@value 4352]
(* | NewAbstractRecordDEPRECATED [@value 4353] *)
(* | RecordMissingRequiredFieldDEPRECATED [@value 4354] *)
(* | RecordUnknownFieldDEPRECATED [@value 4355] *)
(* | CyclicRecordDefDEPRECATED [@value 4356] *)
| InvalidDestructure [@value 4357]
| StaticMethWithClassReifiedGeneric [@value 4358]
| SplatArrayRequired [@value 4359]
| SplatArrayVariadic [@value 4360]
| ExceptionOccurred [@value 4361]
| InvalidReifiedFunctionPointer [@value 4362]
| BadFunctionPointerConstruction [@value 4363]
(* | NotARecordDEPRECATED [@value 4364] *)
| TraitReuseInsideClass [@value 4365]
| RedundantGeneric [@value 4366]
(* | PocketUniversesInvalidUpperBoundsDEPRECATED [@value 4367] *)
(* | PocketUniversesRefinementDEPRECATED [@value 4368] *)
(* | PocketUniversesReservedSyntaxDEPRECATED [@value 4369] *)
| ArrayAccessWrite [@value 4370]
| InvalidArrayKeyWrite [@value 4371]
| NullMemberWrite [@value 4372]
| NonObjectMemberWrite [@value 4373]
| ConcreteConstInterfaceOverride [@value 4374]
| MethCallerTrait [@value 4375]
(* | PocketUniversesAttributesDEPRECATED [@value 4376] *)
| DuplicateInterface [@value 4377]
| TypeParameterNameAlreadyUsedNonShadow [@value 4378]
| IllegalInformationFlow [@value 4379]
| ContextImplicitPolicyLeakage [@value 4380]
| ReifiedFunctionReference [@value 4381]
| ClassMethAbstractCall [@value 4382]
| KindMismatch [@value 4383]
| UnboundNameTypeConstantAccess [@value 4384]
| UnknownInformationFlow [@value 4385]
| CallsiteCIPPMismatch [@value 4386]
| NonpureFunctionCall [@value 4387]
| IncompatibleEnumInclusion [@value 4388]
| RedeclaringClassishConstant [@value 4389]
| CallCoeffects [@value 4390]
| AbstractFunctionPointer [@value 4391]
| UnnecessaryAttribute [@value 4392]
| InheritedMethodCaseDiffers [@value 4393]
| EnumClassLabelUnknown [@value 4394]
(* | ViaLabelInvalidParameterDEPRECATED [@value 4395] *)
| EnumClassLabelAsExpression [@value 4396]
(* | EnumClassLabelInvalidArgumentDEPRECATED [@value 4397] *)
| IFCInternalError [@value 4398]
| IFCExternalContravariant [@value 4399]
| IFCPolicyMismatch [@value 4400]
| OpCoeffects [@value 4401]
| ImplementsDynamic [@value 4402]
| SubtypeCoeffects [@value 4403]
| ImmutableLocal [@value 4404]
| EnumClassesReservedSyntax [@value 4405]
| NonsenseMemberSelection [@value 4406]
| ConsiderMethCaller [@value 4407]
| EnumSupertypingReservedSyntax [@value 4408]
| ReadonlyValueModified [@value 4409]
(* | ReadonlyVarMismatchDEPRECATED [@value 4410] *)
| ReadonlyMismatch [@value 4411]
| ExplicitReadonlyCast [@value 4412]
| ReadonlyMethodCall [@value 4413]
| StrictStrConcatTypeMismatch [@value 4414]
| StrictStrInterpTypeMismatch [@value 4415]
| InvalidMethCallerCallingConvention [@value 4416]
(* | UnsafeCastDEPRECATED [@value 4417] *)
| ReadonlyException [@value 4418]
| InvalidTypeHint [@value 4419]
| ExperimentalExpressionTrees [@value 4420]
| ReturnsWithAndWithoutValue [@value 4421]
| NonVoidAnnotationOnReturnVoidFun [@value 4422]
| BitwiseMathInvalidArgument [@value 4423]
| CyclicClassConstant [@value 4424]
| PrivateDynamicRead [@value 4425]
| PrivateDynamicWrite [@value 4426]
| IncDecInvalidArgument [@value 4427]
| ReadonlyClosureCall [@value 4428]
| MathInvalidArgument [@value 4429]
| TypeconstConcreteConcreteOverride [@value 4430]
| PrivateMethCaller [@value 4431]
| ProtectedMethCaller [@value 4432]
| BadConditionalSupportDynamic [@value 4433]
| ReadonlyInvalidAsMut [@value 4434]
| InvalidKeysetValue [@value 4435]
| UnresolvedTypeVariableProjection [@value 4436]
(* | FunctionPointerWithViaLabelDEPRECATED [@value 4437] *)
| InvalidEchoArgument [@value 4438]
| DiamondTraitMethod [@value 4439]
| ReifiedStaticMethodInExprTree [@value 4440]
| InvariantViolated [@value 4441]
| RigidTVarEscape [@value 4442]
| StrictEqValueIncompatibleTypes [@value 4443]
| ModuleError [@value 4444]
| SealedNotSubtype [@value 4445]
| ModuleHintError [@value 4446]
| MemoizeObjectWithoutGlobals [@value 4447]
| ExpressionTreeNonPublicProperty [@value 4448]
| CovariantIndexTypeMismatch [@value 4449]
| InoutInPseudofunction [@value 4450]
| TraitParentConstructInconsistent [@value 4451]
| HHExpectEquivalentFailure [@value 4452]
| HHExpectFailure [@value 4453]
| CallLvalue [@value 4454]
| UnsafeCastAwait [@value 4455]
| HigherKindedTypesUnsupportedFeature [@value 4456]
| ThisFinal [@value 4457]
| ExactClassFinal [@value 4458]
(* | GlobalVariableWriteDEPRECATED [@value 4459] *)
(* | GlobalVariableInFunctionCallDEPRECATED [@value 4460] *)
(* | MemoizedFunctionCallDEPRECATED [@value 4461] *)
| DiamondTraitProperty [@value 4462]
| ConstructNotInstanceMethod [@value 4463]
| InvalidMethCallerReadonlyReturn [@value 4464]
| AbstractMemberInConcreteClass [@value 4465]
| TraitNotUsed [@value 4466]
| OverrideAsync [@value 4467]
| InexactTConstAccess [@value 4468]
| UnsupportedRefinement [@value 4469]
| InvalidClassRefinement [@value 4470]
| InvalidRefinedConstKind [@value 4471]
| InvalidCrossPackage [@value 4472]
| InvalidCrossPackageSoft [@value 4473]
| AttributeNoAutoDynamic [@value 4474]
| IllegalCaseTypeVariants [@value 4475]
(* Add new Typing codes here! Comment out when deprecating. *)
[@@deriving enum, show { with_path = false }]
let err_code = to_enum
end
(* 5xxx: reserved for FB lint *)
(* 6xxx: reserved for FB ai *)
(* 7xxx: reserved for FB ai *)
(* 8xxx: had been used for forward/back-compat; no longer *)
(* 9xxx: reserved for FB ai *)
(* 10xxx: reserved for FB ai *)
(* 11xxx: reserved for global access check (fbcode/hphp/hack/src/typing/tast_check/global_access_check.ml),
* which is used to detect potential data leaks caused by global variable access.
* 11001 represents the error when a global variable is definitely written.
* 11002 represents the warning when a global variable is possibly written via reference.
* 11003 represents the warning when a global variable is possibly written via function calls.
* 11004 represents the error when a global variable is definitely read.
*)
module GlobalAccessCheck = struct
type t =
| DefiniteGlobalWrite [@value 11001]
| PossibleGlobalWriteViaReference [@value 11002]
| PossibleGlobalWriteViaFunctionCall [@value 11003]
| DefiniteGlobalRead [@value 11004]
(* Add new GlobalAccessCheck codes here! Comment out when deprecating. *)
[@@deriving enum, show { with_path = false }]
let err_code = to_enum
end |
OCaml | hhvm/hphp/hack/src/errors/error_message_sentinel.stubs.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.
*
*)
let remediation_message =
Printf.sprintf
"Addressing other errors or restarting the typechecker with %s might resolve this error."
(Markdown_lite.md_codify "hh restart")
let please_file_a_bug_message =
"If remediation attempts don't work, please file a bug report." |
Rust | hhvm/hphp/hack/src/errors/fmt_plain.rs | // Copyright (c) Meta Platforms, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use oxidized::message::Message;
use oxidized::pos_or_decl::PosOrDecl;
use oxidized::user_error::UserError;
use rc_pos::Pos;
use relative_path::RelativePathCtx;
use crate::ErrorCode;
/// A `std::fmt::Display` implementation that displays the error in the
/// Errors.Plain format produced by OCaml Errors.to_string.
pub struct FmtPlain<'a>(pub &'a UserError<Pos, PosOrDecl>, pub &'a RelativePathCtx);
impl<'a> std::fmt::Display for FmtPlain<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let Self(
UserError {
code,
claim: Message(pos, msg),
reasons,
custom_msgs,
quickfixes: _,
is_fixmed: _,
},
ctx,
) = self;
let code = FmtErrorCode(*code);
write!(f, "{}\n{} ({})", pos.absolute(ctx), msg, code)?;
for Message(pos, msg) in reasons {
write!(f, "\n {}\n {}", pos.absolute(ctx), msg)?;
}
for msg in custom_msgs {
write!(f, "\n {}", msg)?;
}
Ok(())
}
}
pub struct FmtErrorCode(pub ErrorCode);
impl std::fmt::Display for FmtErrorCode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let Self(code) = self;
write!(f, "{}[{:04}]", error_kind(*code), code)
}
}
fn error_kind(error_code: ErrorCode) -> &'static str {
match error_code / 1000 {
1 => "Parsing",
2 => "Naming",
3 => "NastCheck",
4 => "Typing",
5 => "Lint",
8 => "Init",
_ => "Other",
}
} |
Rust | hhvm/hphp/hack/src/errors/fmt_raw.rs | // Copyright (c) Meta Platforms, 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 ansi_term::Color;
use ansi_term::Style;
use oxidized::message::Message;
use oxidized::pos_or_decl::PosOrDecl;
use oxidized::user_error::UserError;
use rc_pos::Pos;
use relative_path::RelativePathCtx;
use crate::FmtErrorCode;
pub struct FmtRaw<'a>(
pub &'a UserError<Pos, PosOrDecl>,
pub &'a RelativePathCtx,
pub bool,
);
impl<'a> std::fmt::Display for FmtRaw<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let Self(
UserError {
code,
claim: Message(pos, msg),
reasons,
custom_msgs,
quickfixes: _,
is_fixmed: _,
},
ctx,
is_term,
) = self;
// TODO: filename should cwd-relative if terminal, otherwise absolute
// in hh_single_type_check, Pos.filename is the original path from the
// cli, not the absolute path, complicating the logic. Lets just use
// canonical path for now.
let filename = pos.filename().to_absolute(ctx);
let (line, start, end) = pos.info_pos();
write!(
f,
"{}:{}:{},{}: {} ({})",
Styled(Color::Red.bold(), filename.display(), *is_term),
Styled(Color::Yellow.normal(), line, *is_term),
Styled(Color::Cyan.normal(), start, *is_term),
Styled(Color::Cyan.normal(), end, *is_term),
Styled(Color::Red.bold(), msg, *is_term),
Styled(Color::Yellow.normal(), FmtErrorCode(*code), *is_term),
)?;
for Message(pos, msg) in reasons {
let filename = pos.filename().to_absolute(ctx);
let (line, start, end) = pos.info_pos();
writeln!(f)?;
write!(
f,
" {}:{}:{},{}: {}",
Styled(Color::Red.normal(), filename.display(), *is_term),
Styled(Color::Yellow.normal(), line, *is_term),
Styled(Color::Cyan.normal(), start, *is_term),
Styled(Color::Cyan.normal(), end, *is_term),
Styled(Color::Green.normal(), msg, *is_term),
)?;
}
for msg in custom_msgs {
writeln!(f)?;
write!(f, " {}", Styled(Color::Green.normal(), msg, *is_term),)?;
}
Ok(())
}
}
struct Styled<T>(Style, T, bool);
impl<T: std::fmt::Display> std::fmt::Display for Styled<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self(_, x, false) => x.fmt(f),
Self(style, x, true) => style.paint(x.to_string()).fmt(f),
}
}
} |
OCaml | hhvm/hphp/hack/src/errors/highlighted_error_formatter.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 String_utils
type error_code = int
type marker = int * Tty.raw_color
type marked_message = {
original_index: int;
marker: marker;
message: Pos.absolute Message.t;
}
(* A position_group is a record composed of a position (we'll call
the aggregate_position) and a list of marked_message. Each
marked_message contains a position, and all of these positions are
closed enough together to be printed in one coalesced code context.
For example, say we have the following code:
1 | <?hh
2 |
3 | function f(): dict<int,
4 | int>
5 | {
6 | return "hello";
7 | }
8 |
We would be given three individual positions (one corresponding to line 2
and two corresponding to lines 6), i.e.
Typing[4110] Invalid return type [1]
-> Expected dict<int, int> [2]
-> But got string [1]
They are close enough together so that code only needs to be printed once
for all of them since their context overlaps. Thus the position_group would
be composed of a list of the three individual aforementioned positions, as
well as the aggregate_position whose first line is 1 and last line 7, and
the final output would look like this.
1 | <?hh
2 |
[2] 3 | function f(): dict<int,
[2] 4 | int>
5 | {
[1] 6 | return "hello";
7 | }
*)
type position_group = {
aggregate_position: Pos.absolute;
messages: marked_message list;
}
let n_extra_lines_hl = 2
(* 'char' because this is intended to be a string of length 1 *)
let out_of_bounds_char = "_"
let background_highlighted = Tty.apply_color (Tty.Dim Tty.Default)
let default_highlighted s = s
let line_num_highlighted line_num =
background_highlighted (string_of_int line_num)
(* Checks if a line (or line/col pair) is inside a position,
taking care to handle zero-width positions and positions
spanning multiple lines.
Some examples:
0 1 2
01234567890123456789012
Example 1: 1 class Foo extends {}
Example 2: 1 function }
Example 3: 1 function {
2 return 3;
3 }
In example 1, the error position is [1,21] - [1,21) with length 1;
column 21 of line 1 is within that error position.
In example 2, error position is [1,0] - [1,0) with length 0;
column 0 of line 1 is within that error position.
In Example 2, the error position is [1,10] - [2,0) with length 1;
column 10 of line 1 (but nothing in line 2) is within that error position.
*)
let pos_contains (pos : Pos.absolute) ?(col_num : int option) (line_num : int) :
bool =
let (first_line, first_col) = Pos.line_column pos in
let (last_line, last_col) = Pos.end_line_column pos in
let is_col_okay = Option.value_map col_num ~default:true in
let last_col =
match Pos.length pos with
| 0 -> last_col + 1
| _ -> last_col
in
(* A position's first line, first column, and last line
are all checked inclusively. The position's last column
is checked inclusively if the length of the position is zero,
and exclusively otherwise, in order to correctly highlight
zero-width positions. Line_num is 1-indexed, col_num is 0-indexed. *)
if first_line = last_line then
first_line = line_num
&& is_col_okay ~f:(fun cn -> first_col <= cn && cn < last_col)
else if line_num = first_line then
is_col_okay ~f:(fun cn -> first_col <= cn)
else if line_num = last_line then
(* When only checking for a line's inclusion in a position
(i.e. when col_num = None), special care must be taken when
the line we're checking is the last line of the position:
since the end_column is exclusive, the end_column's value
must be non-zero signifying there is at least one character
on it to be highlighted. *)
last_col > 0 && is_col_okay ~f:(fun cn -> cn < last_col)
else
first_line < line_num && line_num < last_line
(* Gets the list of unique marker/position tuples associated with a line. *)
let markers_and_positions_for_line
(position_group : position_group) (line_num : int) :
(marker * Pos.absolute) list =
List.filter position_group.messages ~f:(fun mm ->
pos_contains (Message.get_message_pos mm.message) line_num)
|> List.dedup_and_sort ~compare:(fun mm1 mm2 ->
let (mk1, _) = mm1.marker in
let (mk2, _) = mm2.marker in
Int.compare mk1 mk2)
|> List.map ~f:(fun mm -> (mm.marker, Message.get_message_pos mm.message))
(* Gets the string containing the markers that should be displayed next to this line,
e.g. something like "[1,4,5]" *)
let markers_string
(position_group : position_group) ?(apply_color = true) (line_num : int) =
let add_color f s =
if apply_color then
f s
else
s
in
let markers =
markers_and_positions_for_line position_group line_num |> List.map ~f:fst
in
match markers with
| [] -> ""
| markers ->
let ms =
List.map markers ~f:(fun (marker, color) ->
let marker_str = string_of_int marker in
add_color (Tty.apply_color (Tty.Normal color)) marker_str)
in
let lbracket = add_color background_highlighted "[" in
let rbracket = add_color background_highlighted "]" in
let comma = add_color background_highlighted "," in
let prefix =
Printf.sprintf "%s%s%s" lbracket (String.concat ~sep:comma ms) rbracket
in
prefix
let line_margin_highlighted position_group line_num col_width_raw : string =
(* Separate the margin into several sections:
|markers|space(s)|line_num|space|vertical_bar|
i.e.
[1,2] 9 |
[3] 10 |
We need to do this because each has its own color and length
*)
let nspaces =
let markers_raw_len =
markers_string position_group line_num ~apply_color:false |> String.length
in
let line_num_raw_len = string_of_int line_num |> String.length in
max (col_width_raw - (markers_raw_len + line_num_raw_len)) 1
in
let markers_pretty = markers_string position_group line_num in
let spaces = String.make nspaces ' ' in
let line_num_pretty = line_num_highlighted line_num in
let prefix =
Printf.sprintf
"%s%s%s%s"
markers_pretty
spaces
line_num_pretty
(background_highlighted " |")
in
prefix
(* line_num is 1-based *)
let line_highlighted position_group ~(line_num : int) ~(line : string option) =
match line with
| None -> Tty.apply_color (Tty.Dim Tty.Default) "No source found"
| Some line ->
(match markers_and_positions_for_line position_group line_num with
| [] -> default_highlighted line
| ms ->
let get_markers_at_col col_num =
List.filter ms ~f:(fun (_, pos) -> pos_contains pos ~col_num line_num)
in
let color_column ms c =
(* Prefer shorter smaller positions so the boundaries between overlapping
positions are visible. Take the lowest-number (presumably more important)
to break ties. *)
let ((_, color), _) =
List.stable_sort ms ~compare:(fun ((m1, _), p1) ((m2, _), p2) ->
match Int.compare (Pos.length p1) (Pos.length p2) with
| 0 -> Int.compare m1 m2
| v -> v)
|> List.hd_exn
in
Tty.apply_color (Tty.Normal color) c
in
let highlighted_columns : string list =
(* Not String.mapi because we don't want to return a char from each element *)
List.mapi (String.to_list line) ~f:(fun i c ->
match get_markers_at_col i with
| [] -> default_highlighted (Char.to_string c)
| ms -> color_column ms (Char.to_string c))
in
(* Add extra column when position spans multiple lines and we're on the last line. Handles
the case where a position exists for after file but there is no character to highlight *)
let extra_column =
let (end_line, end_col) =
Pos.end_line_column position_group.aggregate_position
in
if line_num = end_line || (line_num + 1 = end_line && end_col = 0) then
match get_markers_at_col (String.length line) with
| [] -> ""
| ms -> color_column ms out_of_bounds_char
else
""
in
String.concat highlighted_columns ^ extra_column)
(* Prefixes each line with its corresponding formatted margin *)
let format_context_lines_highlighted
~(position_group : position_group)
~(lines : (int * string option) list)
~(col_width : int) : string =
let format_line (line_num, line) =
Printf.sprintf
"%s %s"
(line_margin_highlighted position_group line_num col_width)
(line_highlighted position_group ~line_num ~line)
in
let formatted_lines = List.map ~f:format_line lines in
String.concat ~sep:"\n" formatted_lines
(* Gets lines from a position, including additional before/after
lines from the current position; line numbers are 1-indexed.
If the position references one extra line than actually
in the file, we append a line with a sentinel character ('_')
so that we have a line to highlight later. *)
let load_context_lines_for_highlighted ~before ~after ~(pos : Pos.absolute) :
(int * string option) list =
let path = Pos.filename pos in
let (start_line, _start_col) = Pos.line_column pos in
let (end_line, end_col) = Pos.end_line_column pos in
(* Type checker internal errors report the whole file. Limit our
output to at most 1,000 lines. *)
let end_line = min (start_line + 1000) end_line in
let lines = Errors.read_lines path in
match lines with
| [] ->
List.range ~start:`inclusive ~stop:`inclusive start_line end_line
|> List.map ~f:(fun line_num -> (line_num, None))
| lines ->
let numbered_lines = List.mapi lines ~f:(fun i l -> (i + 1, Some l)) in
let original_lines =
List.filter numbered_lines ~f:(fun (i, _) ->
i >= start_line - before && i <= end_line + after)
in
let additional_line =
let last_line =
match List.last original_lines with
| Some (last_line, _) -> last_line
| None -> 0
in
if end_line > last_line && end_col > 0 then
Some (end_line, out_of_bounds_char)
else
None
in
(match additional_line with
| None -> original_lines
| Some (line_num, additional) ->
original_lines @ [(line_num, Some additional)])
let format_context_highlighted
(col_width : int) (position_group : position_group) =
let lines =
load_context_lines_for_highlighted
~before:n_extra_lines_hl
~after:n_extra_lines_hl
~pos:position_group.aggregate_position
in
format_context_lines_highlighted ~position_group ~lines ~col_width
(* The column width will be the length of the largest prefix before
the " |", which is composed of the list of markers, a space, and
the line number. The column size will be the same for all messages
in this error, regardless of file, so that they are all aligned.
Returns the length of the raw (uncolored) prefix string.
For example:
overlap_pos.php:11:10
8 |
9 |
[2] 10 | function returns_int(): int {
[1,3] 11 | return 'foo';
12 | }
13 |
The length of the column is the length of "[1,3] 11" = 8 *)
let col_width_for_highlighted (position_groups : position_group list) =
let largest_line_length =
let message_positions (messages : marked_message list) =
List.map messages ~f:(fun mm -> Message.get_message_pos mm.message)
in
let line_nums =
List.map position_groups ~f:(fun pg -> pg.messages |> message_positions)
|> List.concat_no_order
|> List.map ~f:Pos.end_line
in
List.max_elt line_nums ~compare:Int.compare
|> Option.value ~default:0
|> Errors.num_digits
in
let max_marker_prefix_length =
let markers_strs (pg : position_group) =
let pos = pg.aggregate_position in
let start_line = Pos.line pos in
let end_line = Pos.end_line pos in
List.range start_line (end_line + 1)
|> List.map ~f:(fun line_num ->
markers_string pg ~apply_color:false line_num)
in
let marker_lens =
List.map position_groups ~f:markers_strs
|> List.concat
|> List.map ~f:String.length
in
List.max_elt marker_lens ~compare:Int.compare |> Option.value ~default:0
in
(* +1 for the space between them *)
let col_width = max_marker_prefix_length + 1 + largest_line_length in
col_width
(* Each list of position_groups in the returned list is from a different file.
The first position_group in the list will contain _at least_ the first (i.e. main)
message. The list of marked_messages in each position group is ordered by increasing
line number (so the main message isn't necessarily first). *)
let position_groups_by_file marker_and_msgs : position_group list list =
let msgs_by_file : marked_message list list =
List.group marker_and_msgs ~break:(fun mm1 mm2 ->
let p1 = Message.get_message_pos mm1.message in
let p2 = Message.get_message_pos mm2.message in
String.compare (Pos.filename p1) (Pos.filename p2) <> 0)
(* Must make sure list of positions is ordered *)
|> List.map ~f:(fun msgs ->
List.sort
~compare:(fun mm1 mm2 ->
let p1 = Message.get_message_pos mm1.message in
let p2 = Message.get_message_pos mm2.message in
Int.compare (Pos.line p1) (Pos.line p2))
msgs)
in
let close_enough prev_pos curr_pos =
let line1_end = Pos.end_line prev_pos in
let line2_begin = Pos.line curr_pos in
(* Example:
line1_end = 10:
[3] 10 | $z = 3 * $x;
11 | if ($z is int) {
12 | echo 'int';
line2_begin = 16
14 | echo 'not int';
15 | }
[1] 16 | return $z;
Then they should be conjoined as such:
[3] 10 | $z = 3 * $x;
11 | if ($z is int) {
12 | echo 'int';
13 | } else
14 | echo 'not int';
15 | }
[1] 16 | return $z;
If they were any farther away, the line
13 | } else
would be replaced with
:
to signify more than one interposing line.
*)
line1_end + n_extra_lines_hl + 2 >= line2_begin - n_extra_lines_hl
in
(* Group marked messages that are sufficiently close. *)
let grouped_messages (messages : marked_message list) :
marked_message list list =
List.group messages ~break:(fun prev_mm curr_mm ->
let prev_pos = Message.get_message_pos prev_mm.message in
let curr_pos = Message.get_message_pos curr_mm.message in
not (close_enough prev_pos curr_pos))
in
List.map msgs_by_file ~f:(fun (mmsgl : marked_message list) ->
grouped_messages mmsgl
|> List.map ~f:(fun messages ->
{
aggregate_position =
List.map
~f:(fun mm -> Message.get_message_pos mm.message)
messages
|> List.reduce_exn ~f:Pos.merge;
messages;
}))
let format_file_name_and_pos (pgl : position_group list) =
let relative_path path =
let cwd = Filename.concat (Sys.getcwd ()) "" in
lstrip path cwd
in
(* Primary position for the file is the one with the lowest-numbered
marker across all positions in each position_group of the list *)
let primary_pos =
List.concat_map pgl ~f:(fun pg -> pg.messages)
|> List.stable_sort ~compare:(fun mm1 mm2 ->
let (mk1, _) = mm1.marker in
let (mk2, _) = mm2.marker in
Int.compare mk1 mk2)
|> List.hd_exn
|> fun { message; _ } -> message |> Message.get_message_pos
in
let filename = relative_path (Pos.filename primary_pos) in
let (line, col) = Pos.line_column primary_pos in
let dirname =
let dn = Filename.dirname filename in
if String.equal Filename.current_dir_name dn then
""
else
background_highlighted (Filename.dirname filename ^ "/")
in
let filename = default_highlighted (Filename.basename filename) in
let pretty_filename = Printf.sprintf "%s%s" dirname filename in
let pretty_position =
Printf.sprintf ":%d:%d" line (col + 1) |> background_highlighted
in
let line_info = pretty_filename ^ pretty_position in
line_info
let format_all_contexts_highlighted (marker_and_msgs : marked_message list) =
(* Create a set of position_groups (set of positions that can be written in the same snippet) *)
let position_groups = position_groups_by_file marker_and_msgs in
let col_width = col_width_for_highlighted (List.concat position_groups) in
let sep =
Printf.sprintf
"\n%s %s\n"
(String.make col_width ' ')
(background_highlighted ":")
in
let contexts =
List.map position_groups ~f:(fun pgl ->
(* Each position_groups list (pgl) is for a single file, so separate each with ':' *)
let fn_pos = format_file_name_and_pos pgl in
let ctx_strs = List.map pgl ~f:(format_context_highlighted col_width) in
fn_pos ^ "\n" ^ String.concat ~sep ctx_strs)
in
String.concat ~sep:"\n\n" contexts ^ "\n\n"
let single_marker_highlighted marker =
let (n, color) = marker in
let lbracket = background_highlighted "[" in
let rbracket = background_highlighted "]" in
let npretty = Tty.apply_color (Tty.Normal color) (string_of_int n) in
lbracket ^ npretty ^ rbracket
let format_claim_highlighted
(error_code : error_code)
(marker : error_code * Tty.raw_color)
(msg : string) : string =
let suffix = single_marker_highlighted marker in
let (_, color) = marker in
let pretty_error_code =
Tty.apply_color
(Tty.Bold color)
(User_error.error_code_to_string error_code)
in
(* The color of any highlighted text in the message itself should match
the marker color, unless it's a Lint message (Yellow), in which case
making it Red is fine because Red is not a color available on the color
wheel for subsequent reason messages (in addition, Lint messages don't
typically have subsequent reason messages anyway) *)
let color =
match color with
| Tty.Yellow -> Tty.Red
| _ -> color
in
let pretty_msg = Markdown_lite.render ~add_bold:true ~color msg in
Printf.sprintf "%s %s %s" pretty_error_code pretty_msg suffix
let format_reason_highlighted marked_msg : string =
let suffix = single_marker_highlighted marked_msg.marker in
let pretty_arrow = background_highlighted "->" in
let pretty_msg =
Markdown_lite.render
~color:(snd marked_msg.marker)
(Message.get_message_str marked_msg.message)
in
Printf.sprintf "%s %s %s" pretty_arrow pretty_msg suffix
let make_marker n error_code : marker =
(* Explicitly list out the various codes, rather than a catch-all
for non 5 or 6 codes, to make the correspondence clear and to
make updating this in the future more straightforward *)
let claim_color =
match error_code / 1000 with
| 1 -> Tty.Red (* Parsing *)
| 2 -> Tty.Red (* Naming *)
| 3 -> Tty.Red (* NastCheck *)
| 4 -> Tty.Red (* Typing *)
| 5 -> Tty.Yellow (* Lint *)
| 6 -> Tty.Yellow (* Zoncolan (AI) *)
| 8 -> Tty.Red (* Init *)
| _ -> Tty.Red
(* Other *)
in
let color_wheel = [Tty.Cyan; Tty.Green; Tty.Magenta; Tty.Blue] in
let color =
if n <= 1 then
claim_color
else
let ix = (n - 2) mod List.length color_wheel in
List.nth_exn color_wheel ix
in
(n, color)
(* Convert a list of messages tuples into marked_message structs,
by assigning each their original index in the list and a marker.
Any messages that have the same position (meaning exact location
and size) share the same marker. *)
let mark_messages (error_code : error_code) (msgl : Pos.absolute Message.t list)
: marked_message list =
List.folding_mapi
msgl
~init:(1, [])
~f:(fun original_index (next_marker_n, existing_markers) message ->
let (next_marker_n, existing_markers, marker) =
let curr_msg_pos = Message.get_message_pos message in
match
List.find existing_markers ~f:(fun (_, pos) ->
Pos.equal_absolute curr_msg_pos pos)
with
| None ->
let marker = make_marker next_marker_n error_code in
(next_marker_n + 1, (marker, curr_msg_pos) :: existing_markers, marker)
| Some (marker, _) -> (next_marker_n, existing_markers, marker)
in
((next_marker_n, existing_markers), { original_index; marker; message }))
let to_string (error : Errors.finalized_error) : string =
let error_code = User_error.get_code error in
(* Assign messages markers according to order of original error list
and then sort these marked messages such that messages in the same
file are together. Does not reorder the files or messages within a file. *)
let marked_messages =
User_error.get_messages error
|> mark_messages error_code
|> Errors.combining_sort ~f:(fun mm ->
Message.get_message_pos mm.message |> Pos.filename)
in
(* Typing[4110] Invalid return type [1] <claim>
-> Expected int [2] <reasons>
-> But got string [1] <reasons>
*)
let (claim, reasons) =
(* Present the reasons in _exactly_ the order given in the error,
not in the marked_messages order, which is by file *)
let mms =
List.stable_sort marked_messages ~compare:(fun mm1 mm2 ->
Int.compare mm1.original_index mm2.original_index)
in
match mms with
| mm :: msgs ->
(* This very vitally assumes that the first message in the error is the main one *)
( format_claim_highlighted
error_code
mm.marker
(Message.get_message_str mm.message),
List.map msgs ~f:format_reason_highlighted )
| [] ->
failwith "Impossible: an error always has non-empty list of messages"
in
(* overlap_pos.php:4:10
1 | <?hh
2 |
[2] 3 | function returns_int(): int {
[1] 4 | return 'foo';
5 | }
*)
let all_contexts = format_all_contexts_highlighted marked_messages in
let custom_msgs = error.User_error.custom_msgs in
let buf = Buffer.create 50 in
Buffer.add_string buf (claim ^ "\n");
if not (List.is_empty reasons) then
Buffer.add_string buf (String.concat ~sep:"\n" reasons ^ "\n");
Buffer.add_string buf "\n";
Buffer.add_string buf all_contexts;
if not @@ List.is_empty custom_msgs then
Buffer.add_string
buf
(String.concat ~sep:"\n" error.User_error.custom_msgs ^ "\n");
Buffer.contents buf |
OCaml Interface | hhvm/hphp/hack/src/errors/highlighted_error_formatter.mli | (*
* 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.
*
*)
val to_string : Errors.finalized_error -> string |
OCaml | hhvm/hphp/hack/src/errors/markdown_lite.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
type delimiter =
| Backtick
| Asterisk
| DoubleAsterisk
| DoubleTilde
[@@deriving ord]
module DelimiterKind = struct
type t = delimiter
let compare = compare_delimiter
end
module DelimiterSet = Caml.Set.Make (DelimiterKind)
type tagged_char = DelimiterSet.t * char
type parse_state = {
parsed: tagged_char list;
remaining: string;
}
type parser = parse_state -> parse_state option
let delimiter_to_string = function
| Backtick -> "`"
| Asterisk -> "*"
| DoubleAsterisk -> "**"
| DoubleTilde -> "~~"
let first_and_tail_exn s =
let first = s.[0] in
let tail = String.suffix s (String.length s - 1) in
(first, tail)
(* Supports a small subset of Markdown, with some caveats
in order to handle bolding the main message:
*foo bar* for italics
**foo bar** for bold
`foo bar` for code (underlines text)
~~foo bar~~ for highlighting the text (in red by default)
The `color` parameter is only used on characters
tagged with DoubleTilde.
*)
let format_markdown
?(add_bold = false) ?(color = Tty.Red) (parsed : tagged_char list) =
let format delimiters s : string =
let styles =
if DelimiterSet.mem Backtick delimiters then
[`Underline]
else
[]
in
let styles =
(* Second condition: if we're supposed to bold the message anyway
(e.g. in the main message), then add italics to it (and add bold later below) *)
if
DelimiterSet.mem Asterisk delimiters
|| (DelimiterSet.mem DoubleAsterisk delimiters && add_bold)
then
`Italics :: styles
else
styles
in
let styles =
if DelimiterSet.mem DoubleAsterisk delimiters || add_bold then
`Bold :: styles
else
styles
in
let color =
if DelimiterSet.mem DoubleTilde delimiters then
color
else
Tty.Default
in
if List.is_empty styles then
s
else
Tty.apply_color_from_style (Tty.style_num_from_list color styles) s
in
List.group parsed ~break:(fun (set1, _) (set2, _) ->
not (DelimiterSet.equal set1 set2))
|> List.map ~f:(fun tagged_chars ->
let (delimiters, _) = List.hd_exn tagged_chars in
let s = List.map tagged_chars ~f:snd |> String.of_char_list in
format delimiters s)
|> String.concat
let eat_prefix (prefix : string) (state : parse_state) : parse_state option =
let { parsed; remaining } = state in
Option.Monad_infix.(
String.chop_prefix remaining ~prefix >>= fun remaining ->
Some { parsed; remaining })
(* Success if p s fails, returning original s *)
let fail (p : parser) (s : parse_state) =
match p s with
| None -> Some s
| Some _ -> None
(* Try first parser; if it fails, try second with original state *)
let ( |? ) (p1 : parser) (p2 : parser) (s : parse_state) =
match p1 s with
| None -> p2 s
| Some s -> Some s
let parse_single_char { parsed; remaining } =
let (first, remaining) = first_and_tail_exn remaining in
Some { parsed = parsed @ [(DelimiterSet.empty, first)]; remaining }
let rec parse_and_format_until (delimiter : delimiter) (state : parse_state) :
parse_state option =
let is_valid_section section =
(* Example: "*foo bar*" is a valid section, while
"**", "* foo bar*", "*foo bar *", and "* foo bar *" are not.
The absence of a leading space is checked before entering this function. *)
List.length section > 0 && not (Char.equal ' ' (List.hd_exn section |> snd))
in
match eat_prefix (delimiter_to_string delimiter) state with
| Some { parsed; remaining } when is_valid_section parsed ->
(* Matched a delimiter over a non-empty section;
now try and see if there are nested delimited sections
in that larger section. *)
let parsed =
parse_markdown (List.map ~f:snd parsed |> String.of_char_list) []
|> List.map
~f:
(List.map ~f:(fun (delims, c) ->
(DelimiterSet.add delimiter delims, c)))
|> List.concat
in
Some { parsed; remaining }
| _ ->
let { parsed; remaining } = state in
(match remaining with
| "" ->
(* Nothing left to try *)
None
| _ ->
let (first, remaining) = first_and_tail_exn remaining in
(* Haven't matched a delimiter yet (or did, but the section
wasn't valid), and we still have text we can try *)
parse_and_format_until
delimiter
{ parsed = (DelimiterSet.empty, first) :: parsed; remaining })
and parse_and_format_section ~(delimiter : delimiter) (s : parse_state) =
Option.Monad_infix.(
eat_prefix (delimiter_to_string delimiter) s
>>= (eat_prefix " " |> fail)
>>= parse_and_format_until delimiter)
and parse_markdown (msg : string) (acc : tagged_char list list) :
tagged_char list list =
if String.is_empty msg then
List.rev acc
else
let parse =
parse_and_format_section ~delimiter:DoubleAsterisk
|? parse_and_format_section ~delimiter:DoubleTilde
|? parse_and_format_section ~delimiter:Asterisk
|? parse_and_format_section ~delimiter:Backtick
|? parse_single_char
in
match parse { parsed = []; remaining = msg } with
| None ->
failwith "Impossible: unable to parse a single character in error message"
| Some { parsed; remaining } ->
parse_markdown remaining (List.rev parsed :: acc)
let render ?(add_bold = false) ?(color = Tty.Red) (msg : string) =
parse_markdown msg [] |> List.concat |> format_markdown ~add_bold ~color
let md_codify s = "`" ^ s ^ "`"
let md_highlight s = "~~" ^ s ^ "~~"
let md_bold s = "**" ^ s ^ "**"
let md_italicize s = "*" ^ s ^ "*" |
OCaml Interface | hhvm/hphp/hack/src/errors/markdown_lite.mli | (*
* 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.
*
*)
val render : ?add_bold:bool -> ?color:Tty.raw_color -> string -> string
val md_codify : string -> string
val md_highlight : string -> string
val md_bold : string -> string
val md_italicize : string -> string |
OCaml | hhvm/hphp/hack/src/errors/message.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.
*
*)
(* Trick the Rust generators to use a BStr, because some error
* messages include a Hack string literal, which are not utf8. *)
type t_byte_string = string [@@deriving eq, ord, show]
(** We use `Pos.t message` and `Pos_or_decl.t message` on the server
and convert to `Pos.absolute message` before sending it to the client *)
type 'a t = 'a * t_byte_string [@@deriving eq, ord, show]
let map (pos, msg) ~f = (f pos, msg)
let get_message_pos (pos, _) = pos
let get_message_str (_, str) = str |
OCaml Interface | hhvm/hphp/hack/src/errors/message.mli | (*
* 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.
*
*)
type 'a t = 'a * string [@@deriving eq, ord, show]
val map : 'a t -> f:('a -> 'b) -> 'b t
val get_message_pos : 'a t -> 'a
val get_message_str : 'a t -> string |
OCaml | hhvm/hphp/hack/src/errors/phase_error.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.
*
*)
module type S = sig
type t
module Error_code : Error_category.S
val to_user_error : t -> (Pos.t, Pos_or_decl.t) User_error.t
end |
OCaml | hhvm/hphp/hack/src/errors/quickfix.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
type 'pos qf_pos =
(* Normal position. *)
| Qpos of 'pos
(* A quickfix might want to add things to an empty class declaration,
which requires FFP to compute the { position. *)
| Qclassish_start of string
[@@deriving eq, ord, show]
type 'pos edit = string * 'pos qf_pos [@@deriving eq, ord, show]
type 'pos t = {
title: string;
edits: 'pos edit list;
}
[@@deriving eq, ord, show]
let to_absolute { title; edits } =
let edits =
List.map edits ~f:(fun (s, qfp) ->
( s,
match qfp with
| Qpos pos -> Qpos (pos |> Pos.to_absolute)
| Qclassish_start s -> Qclassish_start s ))
in
{ title; edits }
let make ~title ~new_text pos = { title; edits = [(new_text, Qpos pos)] }
let make_with_edits ~title ~edits =
{
title;
edits = List.map edits ~f:(fun (new_text, pos) -> (new_text, Qpos pos));
}
let make_classish ~title ~new_text ~classish_name =
{ title; edits = [(new_text, Qclassish_start classish_name)] }
let of_qf_pos ~(classish_starts : Pos.t SMap.t) (p : Pos.t qf_pos) : Pos.t =
match p with
| Qpos pos -> pos
| Qclassish_start name ->
(match SMap.find_opt name classish_starts with
| Some pos -> pos
| None -> Pos.none)
let get_title (quickfix : 'a t) : string = quickfix.title
let get_edits ~(classish_starts : Pos.t SMap.t) (quickfix : Pos.t t) :
(string * Pos.t) list =
List.map quickfix.edits ~f:(fun (new_text, qfp) ->
(new_text, of_qf_pos ~classish_starts qfp))
(* Sort [quickfixes] with their edit positions in descending
order. This allows us to iteratively apply the quickfixes without
messing up positions earlier in the file.*)
let sort_for_application
(classish_starts : Pos.t SMap.t) (quickfixes : Pos.t t list) : Pos.t t list
=
let first_qf_offset (quickfix : Pos.t t) : int =
let pos =
match List.hd quickfix.edits with
| Some (_, qfp) -> of_qf_pos ~classish_starts qfp
| _ -> Pos.none
in
snd (Pos.info_raw pos)
in
let compare x y = Int.compare (first_qf_offset x) (first_qf_offset y) in
List.rev (List.sort ~compare quickfixes)
let sort_edits_for_application
(classish_starts : Pos.t SMap.t) (edits : Pos.t edit list) : Pos.t edit list
=
let offset (_, qfp) =
let pos = of_qf_pos ~classish_starts qfp in
snd (Pos.info_raw pos)
in
let compare x y = Int.compare (offset x) (offset y) in
List.rev (List.sort ~compare edits)
(* Apply [edit] to [src], replacing the text at the position specified. *)
let apply_edit
(classish_starts : Pos.t SMap.t) (src : string) (edit : Pos.t edit) : string
=
let (new_text, p) = edit in
let pos = of_qf_pos ~classish_starts p in
if Pos.equal pos Pos.none then
src
else
let (start_offset, end_offset) = Pos.info_raw pos in
let src_before = String.subo src ~len:start_offset in
let src_after = String.subo src ~pos:end_offset in
src_before ^ new_text ^ src_after
let apply_quickfix
(classish_starts : Pos.t SMap.t) (src : string) (quickfix : Pos.t t) :
string =
List.fold
(sort_edits_for_application classish_starts quickfix.edits)
~init:src
~f:(apply_edit classish_starts)
(** Apply all [quickfixes] by replacing/inserting the new text in [src].
Normally this is done by the user's editor (the LSP client), but
this is useful for testing quickfixes. **)
let apply_all
(src : string) (classish_starts : Pos.t SMap.t) (quickfixes : Pos.t t list)
: string =
List.fold
(sort_for_application classish_starts quickfixes)
~init:src
~f:(apply_quickfix classish_starts) |
OCaml Interface | hhvm/hphp/hack/src/errors/quickfix.mli | (*
* 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.
*
*)
type 'pos t [@@deriving eq, ord, show]
val make : title:string -> new_text:string -> Pos.t -> Pos.t t
val make_with_edits : title:string -> edits:(string * Pos.t) list -> Pos.t t
val make_classish :
title:string -> new_text:string -> classish_name:string -> Pos.t t
val get_edits : classish_starts:Pos.t SMap.t -> Pos.t t -> (string * Pos.t) list
val get_title : Pos.t t -> string
val apply_all : string -> Pos.t SMap.t -> Pos.t t list -> string
val to_absolute : Pos.t t -> Pos.absolute t |
OCaml | hhvm/hphp/hack/src/errors/quickfix_ffp.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
module Syntax = Full_fidelity_positioned_syntax
let classish_body_brace_offset s : int option =
let open Syntax in
match s.syntax with
| ClassishBody cb ->
let open_brace = cb.classish_body_left_brace in
(match open_brace.syntax with
| Token t -> Some (t.Token.offset + t.Token.width)
| _ -> None)
| _ -> None
let namespace_name (s : Syntax.t) : string option =
let open Syntax in
match s.syntax with
| Syntax.NamespaceDeclarationHeader h ->
let name_token = h.namespace_name in
(match name_token.syntax with
| Syntax.Token _ -> Some (text name_token)
| _ ->
(* Anonymous namespace: namespace { ... } *)
None)
| _ -> None
(* Covnert ["Foo"; "Bar"] to \Foo\Bar. *)
let name_from_parts (parts : string list) : string =
String.concat (List.map parts ~f:(fun p -> "\\" ^ p))
let classish_start_offsets (s : Syntax.t) : int SMap.t =
let open Syntax in
let rec aux (acc : int SMap.t * string list) (s : Syntax.t) =
let (offsets, namespace) = acc in
match s.syntax with
| Syntax.Script s -> aux acc s.script_declarations
| Syntax.SyntaxList sl -> List.fold sl ~init:acc ~f:aux
| Syntax.NamespaceDeclaration n ->
let b = n.namespace_body in
(match b.syntax with
| Syntax.NamespaceBody nb ->
(* We're looking at: namespace Foo { ... } *)
let inner_namespace =
match namespace_name n.namespace_header with
| Some name -> name :: namespace
| None -> namespace
in
let (offsets, _) =
aux (offsets, inner_namespace) nb.namespace_declarations
in
(offsets, namespace)
| Syntax.NamespaceEmptyBody _ ->
(* We're looking at: namespace Foo; *)
let namespace =
match namespace_name n.namespace_header with
| Some name -> name :: namespace
| None -> namespace
in
(offsets, namespace)
| _ -> acc)
| Syntax.ClassishDeclaration c ->
(match classish_body_brace_offset c.classish_body with
| Some offset ->
let name = name_from_parts (namespace @ [text c.classish_name]) in
let offsets = SMap.add name offset offsets in
(offsets, namespace)
| _ -> acc)
| _ -> acc
in
fst (aux (SMap.empty, []) s)
(** Return the position of the start "{" in every classish in this
file. *)
let classish_starts
(s : Syntax.t)
(source_text : Full_fidelity_source_text.t)
(filename : Relative_path.t) : Pos.t SMap.t =
let offsets = classish_start_offsets s in
let to_pos offset =
Full_fidelity_source_text.relative_pos filename source_text offset offset
in
SMap.map to_pos offsets |
OCaml Interface | hhvm/hphp/hack/src/errors/quickfix_ffp.mli | (*
* 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.
*
*)
val classish_starts :
Full_fidelity_positioned_syntax.t ->
Full_fidelity_source_text.t ->
Relative_path.t ->
Pos.t SMap.t |
OCaml | hhvm/hphp/hack/src/errors/raw_error_formatter.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 String_utils
let format_msg file_clr err_clr ((p, s) : Pos.absolute * string) =
let (line, start, end_) = Pos.info_pos p in
let file_path =
if Unix.isatty Unix.stdout then
let cwd = Filename.concat (Sys.getcwd ()) "" in
lstrip (Pos.filename p) cwd
else
Pos.filename p
in
let line_clr = Tty.Normal Tty.Yellow in
let col_clr = Tty.Normal Tty.Cyan in
let default_clr = Tty.Normal Tty.Default in
[
(file_clr, file_path);
(default_clr, ":");
(line_clr, string_of_int line);
(default_clr, ":");
(col_clr, string_of_int start);
(default_clr, ",");
(col_clr, string_of_int end_);
(default_clr, ": ");
(err_clr, s);
]
let format_error_code code =
[
(Tty.Normal Tty.Default, " (");
(Tty.Normal Tty.Yellow, User_error.error_code_to_string code);
(Tty.Normal Tty.Default, ")");
]
let to_string (error : Errors.finalized_error) : string =
let (error_code, msgl) = User_error.(get_code error, to_list error) in
match msgl with
| [] ->
failwith "Impossible: an error always has a non-empty list of messages"
| msg :: msgl ->
let newline = (Tty.Normal Tty.Default, "\n") in
let claim =
format_msg (Tty.Bold Tty.Red) (Tty.Bold Tty.Red) msg
@ format_error_code error_code
@ [newline]
in
let reasons =
let indent = (Tty.Normal Tty.Default, " ") in
List.concat_map
~f:(fun msg ->
(indent :: format_msg (Tty.Normal Tty.Red) (Tty.Normal Tty.Green) msg)
@ [newline])
msgl
in
let custom_msgs =
match error.User_error.custom_msgs with
| [] -> []
| msgs ->
(Tty.Normal Tty.Default, "\n")
:: List.map ~f:(fun msg -> (Tty.Normal Tty.Yellow, msg)) msgs
in
let to_print = claim @ reasons @ custom_msgs in
if Unix.isatty Unix.stdout then
List.map to_print ~f:(fun (c, s) -> Tty.apply_color c s) |> String.concat
else
List.map to_print ~f:(fun (_, x) -> x) |> String.concat |
OCaml Interface | hhvm/hphp/hack/src/errors/raw_error_formatter.mli | (*
* 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.
*
*)
val to_string : Errors.finalized_error -> string |
OCaml | hhvm/hphp/hack/src/errors/render.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 strip_ns id =
id |> Utils.strip_ns |> Hh_autoimport.strip_HH_namespace_if_autoimport
let vis_to_string = function
| `public -> "public"
| `private_ -> "private"
| `internal -> "internal"
| `protected -> "protected"
let verb_to_string = function
| `extend -> "extend"
| `implement -> "implement"
| `use -> "use"
let string_of_class_member_kind = function
| `class_constant -> "class constant"
| `static_method -> "static method"
| `class_variable -> "class variable"
| `class_typeconst -> "type constant"
| `method_ -> "method"
| `property -> "property"
(* Given two equal-length strings, highlights the characters in
the second that differ from the first *)
let highlight_differences base to_highlight =
match List.zip (String.to_list base) (String.to_list to_highlight) with
| List.Or_unequal_lengths.Ok l ->
List.group l ~break:(fun (o1, s1) (o2, s2) ->
not (Bool.equal (Char.equal o1 s1) (Char.equal o2 s2)))
|> List.map ~f:(fun cs ->
let s = List.map cs ~f:snd |> String.of_char_list in
let (c1, c2) = List.hd_exn cs in
if Char.equal c1 c2 then
s
else
Markdown_lite.md_highlight s)
|> String.concat
| List.Or_unequal_lengths.Unequal_lengths -> to_highlight
let suggestion_message ?(modifier = "") orig hint hint_pos =
let s =
if
(not (String.equal orig hint))
&& String.equal (String.lowercase orig) (String.lowercase hint)
then
Printf.sprintf
"Did you mean %s%s instead (which only differs by case)?"
modifier
(highlight_differences orig hint |> Markdown_lite.md_codify)
else
Printf.sprintf
"Did you mean %s%s instead?"
modifier
(Markdown_lite.md_codify hint)
in
(hint_pos, s)
let pluralize_arguments n =
string_of_int n
^
if n = 1 then
" argument"
else
" arguments" |
OCaml Interface | hhvm/hphp/hack/src/errors/render.mli | (*
* 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.
*
*)
val strip_ns : string -> string
val verb_to_string : [< `extend | `implement | `use ] -> string
val vis_to_string : [< `internal | `private_ | `protected | `public ] -> string
val highlight_differences : string -> string -> string
val suggestion_message :
?modifier:string -> string -> string -> 'a -> 'a * string
val string_of_class_member_kind :
[< `class_constant
| `class_typeconst
| `class_variable
| `method_
| `property
| `static_method
] ->
string
val pluralize_arguments : int -> string |
OCaml | hhvm/hphp/hack/src/errors/user_error.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
type ('prim_pos, 'pos) t = {
code: int;
claim: 'prim_pos Message.t;
reasons: 'pos Message.t list;
quickfixes: 'prim_pos Quickfix.t list;
custom_msgs: string list;
is_fixmed: bool;
}
[@@deriving eq, ord, show]
let make
code
?(is_fixmed = false)
?(quickfixes = [])
?(custom_msgs = [])
claim
reasons =
{ code; claim; reasons; quickfixes; custom_msgs; is_fixmed }
let get_code { code; _ } = code
let get_pos { claim; _ } = fst claim
let quickfixes { quickfixes; _ } = quickfixes
let to_list { claim; reasons; _ } = claim :: reasons
let to_list_ { claim = (pos, claim); reasons; _ } =
(Pos_or_decl.of_raw_pos pos, claim) :: reasons
let get_messages = to_list
let to_absolute { code; claim; reasons; quickfixes; custom_msgs; is_fixmed } =
let claim = (fst claim |> Pos.to_absolute, snd claim) in
let reasons =
List.map reasons ~f:(fun (p, s) ->
(p |> Pos_or_decl.unsafe_to_raw_pos |> Pos.to_absolute, s))
in
let quickfixes = List.map quickfixes ~f:Quickfix.to_absolute in
{ code; claim; reasons; quickfixes; custom_msgs; is_fixmed }
let make_absolute code = function
| [] -> failwith "an error must have at least one message"
| claim :: reasons ->
{
code;
claim;
reasons;
quickfixes = [];
custom_msgs = [];
is_fixmed = false;
}
let to_absolute_for_test
{
code;
claim = (claim_pos, claim_msg);
reasons;
quickfixes;
custom_msgs;
is_fixmed;
} =
let f (p, s) =
let p = Pos_or_decl.unsafe_to_raw_pos p in
let path = Pos.filename p in
let path_without_prefix = Relative_path.suffix path in
let p =
Pos.set_file
(Relative_path.create Relative_path.Dummy path_without_prefix)
p
in
(Pos.to_absolute p, s)
in
let claim = f (Pos_or_decl.of_raw_pos claim_pos, claim_msg) in
let reasons = List.map ~f reasons in
let quickfixes = List.map quickfixes ~f:Quickfix.to_absolute in
{ code; claim; reasons; quickfixes; custom_msgs; is_fixmed }
let error_kind error_code =
match error_code / 1000 with
| 1 -> "Parsing"
| 2 -> "Naming"
| 3 -> "NastCheck"
| 4 -> "Typing"
| 5 -> "Lint"
| 8 -> "Init"
| _ -> "Other"
let error_code_to_string error_code =
let error_kind = error_kind error_code in
let error_number = Printf.sprintf "%04d" error_code in
error_kind ^ "[" ^ error_number ^ "]"
let to_string
report_pos_from_reason
{ code; claim; reasons; custom_msgs; quickfixes = _; is_fixmed = _ } =
let buf = Buffer.create 50 in
let (pos1, msg1) = claim in
Buffer.add_string
buf
begin
let error_code = error_code_to_string code in
let reason_msg =
if report_pos_from_reason && Pos.get_from_reason pos1 then
" [FROM REASON INFO]"
else
""
in
Printf.sprintf
"%s\n%s (%s)%s\n"
(Pos.string pos1)
msg1
error_code
reason_msg
end;
List.iter reasons ~f:(fun (p, w) ->
let msg = Printf.sprintf " %s\n %s\n" (Pos.string p) w in
Buffer.add_string buf msg);
List.iter custom_msgs ~f:(fun w ->
let msg = Printf.sprintf " %s\n" w in
Buffer.add_string buf msg);
Buffer.contents buf
let to_json error =
let (error_code, msgl) = (get_code error, to_list error) in
let elts =
List.map msgl ~f:(fun (p, w) ->
let (line, scol, ecol) = Pos.info_pos p in
Hh_json.JSON_Object
[
("descr", Hh_json.JSON_String w);
("path", Hh_json.JSON_String (Pos.filename p));
("line", Hh_json.int_ line);
("start", Hh_json.int_ scol);
("end", Hh_json.int_ ecol);
("code", Hh_json.int_ error_code);
])
in
let custom_msgs =
List.map ~f:(fun msg -> Hh_json.JSON_String msg) error.custom_msgs
in
Hh_json.JSON_Object
[
("message", Hh_json.JSON_Array elts);
("custom_messages", Hh_json.JSON_Array custom_msgs);
] |
OCaml Interface | hhvm/hphp/hack/src/errors/user_error.mli | (*
* 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.
*
*)
type ('prim_pos, 'pos) t = {
code: int;
claim: 'prim_pos Message.t;
reasons: 'pos Message.t list;
quickfixes: 'prim_pos Quickfix.t list;
custom_msgs: string list;
is_fixmed: bool;
}
[@@deriving eq, ord, show]
val make :
int ->
?is_fixmed:bool ->
?quickfixes:'a Quickfix.t list ->
?custom_msgs:string list ->
'a Message.t ->
'b Message.t list ->
('a, 'b) t
val get_code : ('a, 'b) t -> int
val get_pos : ('a, 'b) t -> 'a
val quickfixes : ('a, 'b) t -> 'a Quickfix.t list
val to_list : ('a, 'a) t -> 'a Message.t list
val to_list_ : (Pos.t, Pos_or_decl.t) t -> Pos_or_decl.t Message.t list
val get_messages : ('a, 'a) t -> 'a Message.t list
val to_absolute : (Pos.t, Pos_or_decl.t) t -> (Pos.absolute, Pos.absolute) t
val make_absolute : int -> 'a Message.t list -> ('a, 'a) t
val to_absolute_for_test :
(Pos.t, Pos_or_decl.t) t -> (Pos.absolute, Pos.absolute) t
val error_kind : int -> string
val error_code_to_string : int -> string
val to_string : bool -> (Pos.absolute, Pos.absolute) t -> string
val to_json : (Pos.absolute, Pos.absolute) t -> Hh_json.json |
Rust | hhvm/hphp/hack/src/errors/user_error.rs | // Copyright (c) Meta Platforms, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use oxidized::message::Message;
use oxidized::user_error::UserError;
use rc_pos::Pos;
use relative_path::RelativePathCtx;
use serde_json::json;
use crate::ErrorCode;
pub fn to_json(e: &UserError<Pos, Pos>, ctx: &RelativePathCtx) -> serde_json::Value {
let mut messages = Vec::new();
messages.push(msg_json(&e.claim, e.code, ctx));
messages.extend(e.reasons.iter().map(|m| msg_json(m, e.code, ctx)));
json!({
"message": messages,
})
}
fn msg_json(
Message(pos, descr): &Message<Pos>,
code: ErrorCode,
ctx: &RelativePathCtx,
) -> serde_json::Value {
let (line, scol, ecol) = pos.info_pos();
json!({
"descr": descr.to_string(),
"path": pos.filename().to_absolute(ctx),
"line": line,
"start": scol,
"end": ecol,
"code": code,
})
} |
TOML | hhvm/hphp/hack/src/errors/cargo/errors/Cargo.toml | # @generated by autocargo
[package]
name = "errors_rs"
version = "0.0.0"
edition = "2021"
[lib]
path = "../../errors.rs"
crate-type = ["lib", "staticlib"]
[dependencies]
ansi_term = "0.12"
oxidized = { version = "0.0.0", path = "../../../oxidized" }
rc_pos = { version = "0.0.0", path = "../../../utils/rust/pos" }
relative_path = { version = "0.0.0", path = "../../../utils/rust/relative_path" }
serde_json = { version = "1.0.100", features = ["float_roundtrip", "unbounded_depth"] } |
hhvm/hphp/hack/src/facts/dune | ; FFI OCaml to Rust (../../target/*/librust_facts_ffi.a)
; contains "external" function definition in .ml and
; the symbol is provided by the ocaml-rs Rust package via caml! macro
(data_only_dirs cargo rust_facts_ffi)
(library
(name rust_facts_ffi)
(modules)
(wrapped false)
(foreign_archives rust_facts_ffi))
(rule
(targets librust_facts_ffi.a)
(deps
(source_tree %{workspace_root}/hack/src))
(locks /cargo)
(action
(run
%{workspace_root}/hack/scripts/invoke_cargo.sh
rust_facts_ffi
rust_facts_ffi)))
(copy_files ffi/rust_facts_ffi.ml)
(library
(name facts)
(wrapped false)
(modules facts facts_parser rust_facts_ffi)
(libraries core_kernel parser rust_facts_ffi utils_hash)
(preprocess
(pps ppx_deriving.std))) |
|
OCaml | hhvm/hphp/hack/src/facts/facts.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 InvStringKey = struct
type t = string
let compare (x : t) (y : t) = String.compare y x
end
module InvSMap = WrappedMap.Make (InvStringKey)
module InvSSet = Caml.Set.Make (InvStringKey)
type type_kind =
| TKClass
| TKInterface
| TKEnum
| TKTrait
| TKTypeAlias
| TKUnknown
| TKMixed
let is_tk_unknown = function
| TKUnknown -> true
| TKClass
| TKInterface
| TKEnum
| TKTrait
| TKTypeAlias
| TKMixed ->
false
let is_tk_interface = function
| TKInterface -> true
| TKClass
| TKEnum
| TKTrait
| TKTypeAlias
| TKUnknown
| TKMixed ->
false
let is_tk_trait = function
| TKTrait -> true
| TKClass
| TKInterface
| TKEnum
| TKTypeAlias
| TKUnknown
| TKMixed ->
false
let type_kind_from_string s =
if String.equal s "class" then
TKClass
else if String.equal s "interface" then
TKInterface
else if String.equal s "enum" then
TKEnum
else if String.equal s "trait" then
TKTrait
else if String.equal s "typeAlias" then
TKTypeAlias
else if String.equal s "unknown" then
TKUnknown
else if String.equal s "mixed" then
TKMixed
else
raise (Failure (Printf.sprintf "No Facts.type_kind matches string: %s" s))
type type_facts = {
kind: type_kind;
flags: int;
}
type module_facts = unit
let empty_type_facts = { kind = TKUnknown; flags = 0 }
type facts = {
types: type_facts InvSMap.t;
functions: string list;
constants: string list;
}
let empty = { types = InvSMap.empty; functions = []; constants = [] }
(* Facts from JSON *)
let facts_from_json : Hh_json.json -> facts option =
Hh_json.(
let list_from_jstr_array = List.rev_map ~f:get_string_exn in
let type_facts_from_jobj entry : string * type_facts =
let name_ref = ref "" in
let ret =
List.fold_left
~init:empty_type_facts
~f:(fun acc (k, v) ->
match v with
| JSON_String name when String.equal k "name" ->
name_ref := name;
acc
| JSON_String kind when String.equal k "kindOf" ->
{ acc with kind = type_kind_from_string kind }
| JSON_Number flags when String.equal k "flags" ->
{ acc with flags = int_of_string flags }
| _ -> acc)
entry
in
(!name_ref, ret)
in
function
| JSON_Object key_values ->
Some
(List.fold
~init:empty
~f:(fun acc (k, v) ->
match v with
| JSON_Array xs when String.equal k "constants" ->
{ acc with constants = list_from_jstr_array xs }
| JSON_Array xs when String.equal k "functions" ->
{ acc with functions = list_from_jstr_array xs }
| JSON_Array types when String.equal k "types" ->
{
acc with
types =
List.fold_left
~init:InvSMap.empty
~f:(fun acc v ->
match v with
| JSON_Object entry ->
let (k, v) = type_facts_from_jobj entry in
InvSMap.add k v acc
| _ -> acc)
types;
}
| _ -> acc)
key_values)
| _ -> None) |
OCaml Interface | hhvm/hphp/hack/src/facts/facts.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.
*
*)
module InvStringKey : Map.OrderedType with type t = string
module InvSMap : WrappedMap.S with type key = InvStringKey.t
module InvSSet : Caml.Set.S with type elt = InvStringKey.t
type type_kind =
| TKClass
| TKInterface
| TKEnum
| TKTrait
| TKTypeAlias
| TKUnknown
| TKMixed
val is_tk_interface : type_kind -> bool
val is_tk_trait : type_kind -> bool
val is_tk_unknown : type_kind -> bool
type type_facts = {
kind: type_kind;
flags: int;
}
type module_facts = unit
type facts = {
types: type_facts InvSMap.t;
functions: string list;
constants: string list;
}
val empty : facts
val facts_from_json : Hh_json.json -> facts option |
Rust | hhvm/hphp/hack/src/facts/facts.rs | // Copyright (c) 2019, Facebook, Inc.
// All rights reserved.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::collections::BTreeMap;
use hhbc_string_utils::mangle_xhp_id;
use hhbc_string_utils::strip_global_ns;
use oxidized_by_ref::ast_defs::Abstraction;
use oxidized_by_ref::ast_defs::ClassishKind;
use oxidized_by_ref::direct_decl_parser::ParsedFile;
use oxidized_by_ref::shallow_decl_defs::ClassDecl;
use serde::ser::SerializeSeq;
use serde::Serializer;
use serde_derive::Serialize;
use serde_json::json;
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
enum TypeKind {
Class,
Interface,
Enum,
Trait,
TypeAlias,
Unknown,
Mixed,
}
impl Default for TypeKind {
fn default() -> Self {
Self::Unknown
}
}
type TypeFactsByName = BTreeMap<String, TypeFacts>;
#[derive(Debug, PartialEq, Serialize, Default)]
#[serde(rename_all = "camelCase")]
struct TypeFacts {
#[serde(rename = "kindOf")]
kind: TypeKind,
flags: u8,
}
#[derive(Default, Debug, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
struct Facts {
#[serde(
default,
skip_serializing_if = "TypeFactsByName::is_empty",
serialize_with = "types_to_json"
)]
types: TypeFactsByName,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
functions: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
constants: Vec<String>,
}
impl Facts {
fn to_json(&self, pretty: bool) -> String {
let json = json!(self);
if pretty {
serde_json::to_string_pretty(&json).expect("Could not serialize facts to JSON")
} else {
serde_json::to_string(&json).expect("Could not serialize facts to JSON")
}
}
fn from_decls(parsed_file: &ParsedFile<'_>) -> Facts {
let mut types = TypeFactsByName::new();
parsed_file.decls.classes().for_each(|(class_name, decl)| {
let mut name = format(class_name);
if !parsed_file.disable_xhp_element_mangling && decl.is_xhp {
// strips the namespace and mangles the class id
if let Some(id) = name.rsplit('\\').next() {
name = id.to_string();
}
}
let type_fact = TypeFacts::of_class_decl(decl);
add_or_update_classish_decl(name, type_fact, &mut types);
});
for (name, _) in parsed_file.decls.typedefs().filter(|(_, decl)| {
// Ignore context aliases
!decl.is_ctx
}) {
let type_fact = TypeFacts::of_typedef_decl();
add_or_update_classish_decl(format(name), type_fact, &mut types);
}
let mut functions = parsed_file
.decls
.funs()
.filter_map(|(name, _)| {
let name = format(name);
if name.eq("__construct") {
None
} else {
Some(name)
}
})
.collect::<Vec<String>>();
let mut constants = parsed_file
.decls
.consts()
.map(|(name, _)| format(name))
.collect::<Vec<String>>();
functions.reverse();
constants.reverse();
Facts {
types,
functions,
constants,
}
}
}
type Flags = u8;
/// Compute minimal Facts in json format, including only the information
/// required by OCaml Facts.facts_from_json().
pub fn decls_to_facts_json(parsed_file: &ParsedFile<'_>, pretty: bool) -> String {
Facts::from_decls(parsed_file).to_json(pretty)
}
#[derive(Clone, Copy)]
enum Flag {
Abstract = 1,
Final = 2,
MultipleDeclarations = 4,
}
impl Flag {
fn as_flags(&self) -> Flags {
*self as Flags
}
#[cfg(test)]
fn zero() -> Flags {
0
}
#[cfg(test)]
fn is_set(&self, flags: Flags) -> bool {
(flags & (*self as Flags)) != 0
}
fn set(self, flags: Flags) -> Flags {
flags | (self as Flags)
}
fn combine(flags1: Flags, flags2: Flags) -> Flags {
flags1 | flags2
}
}
// implementation details
/// Serialize the Map<Name, TypeFacts> as a sequence of JSON objects with `name`
/// as one of the fields.
fn types_to_json<S: Serializer>(types_by_name: &TypeFactsByName, s: S) -> Result<S::Ok, S::Error> {
let mut seq = s.serialize_seq(None)?;
for (name, types) in types_by_name.iter() {
// pull the "name" key into the associated json object, then append to list
let mut types_json = json!(types);
if let Some(m) = types_json.as_object_mut() {
m.insert("name".to_owned(), json!(name));
};
seq.serialize_element(&types_json)?;
}
seq.end()
}
impl TypeFacts {
fn of_class_decl(decl: &ClassDecl<'_>) -> TypeFacts {
let ClassDecl { kind, final_, .. } = decl;
// Set flags according to modifiers - abstract, final, static (abstract + final)
let mut flags = Flags::default();
let kind = match kind {
ClassishKind::Cclass(abstraction) => {
flags = modifiers_to_flags(flags, *final_, *abstraction);
TypeKind::Class
}
ClassishKind::Cinterface => {
flags = Flag::Abstract.as_flags();
TypeKind::Interface
}
ClassishKind::Ctrait => {
flags = Flag::Abstract.as_flags();
TypeKind::Trait
}
ClassishKind::Cenum => TypeKind::Enum,
ClassishKind::CenumClass(abstraction) => {
flags = modifiers_to_flags(flags, *final_, *abstraction);
TypeKind::Enum
}
};
TypeFacts { kind, flags }
}
fn of_typedef_decl() -> TypeFacts {
TypeFacts {
kind: TypeKind::TypeAlias,
flags: Flags::default(),
}
}
}
fn add_or_update_classish_decl(name: String, delta: TypeFacts, types: &mut TypeFactsByName) {
types
.entry(name)
.and_modify(|tf| {
if tf.kind != delta.kind {
tf.kind = TypeKind::Mixed;
}
tf.flags = Flag::MultipleDeclarations.set(tf.flags);
tf.flags = Flag::combine(tf.flags, delta.flags);
})
.or_insert(delta);
}
fn format(original_name: &str) -> String {
let unqualified = strip_global_ns(original_name);
match unqualified.rsplit('\\').next() {
Some(id) if original_name.starts_with('\\') && id.starts_with(':') => {
// only mangle already qualified xhp ids - avoid mangling string literals
// containing an xhp name, for example an attribute param ':foo:bar'
mangle_xhp_id(id.to_string())
}
_ => String::from(unqualified),
}
}
fn modifiers_to_flags(flags: Flags, is_final: bool, abstraction: Abstraction) -> Flags {
let flags = match abstraction {
Abstraction::Abstract => Flag::Abstract.set(flags),
Abstraction::Concrete => flags,
};
if is_final {
Flag::Final.set(flags)
} else {
flags
}
}
// inline tests (so stuff can remain hidden) - compiled only when tests are run (no overhead)
#[cfg(test)]
mod tests {
use pretty_assertions::assert_eq;
use super::*; // make assert_eq print huge diffs more human-readable
#[test]
fn type_kind_to_json() {
assert_eq!(json!(TypeKind::Unknown).to_string(), "\"unknown\"");
assert_eq!(json!(TypeKind::Interface).to_string(), "\"interface\"");
}
fn fake_facts() -> Facts {
let mut types = TypeFactsByName::new();
types.insert(
String::from("include_empty_both_when_trait_kind"),
TypeFacts {
kind: TypeKind::Trait,
flags: 6,
},
);
// verify requireImplements, requireExtends and requireClass are skipped if empty and Class kind
types.insert(
String::from("include_empty_neither_when_class_kind"),
TypeFacts {
kind: TypeKind::Class,
flags: 0,
},
);
// verify only requireImplements is skipped if empty and Interface kind
types.insert(
String::from("include_empty_req_extends_when_interface_kind"),
TypeFacts {
kind: TypeKind::Interface,
flags: 1,
},
);
// verify non-empty require* is included
types.insert(
String::from("include_nonempty_always"),
TypeFacts {
kind: TypeKind::Unknown,
flags: 9,
},
);
types.insert(
String::from("include_method_attrs"),
TypeFacts {
kind: TypeKind::Class,
flags: 6,
},
);
types.insert(
String::from("my_type_alias"),
TypeFacts {
kind: TypeKind::TypeAlias,
..Default::default()
},
);
Facts {
constants: vec!["c1".into(), "c2".into()],
functions: vec![],
types,
}
}
#[test]
fn to_json() {
// test to_string_pretty()
let facts = fake_facts();
assert_eq!(
facts.to_json(true),
r#"{
"constants": [
"c1",
"c2"
],
"types": [
{
"flags": 6,
"kindOf": "trait",
"name": "include_empty_both_when_trait_kind"
},
{
"flags": 0,
"kindOf": "class",
"name": "include_empty_neither_when_class_kind"
},
{
"flags": 1,
"kindOf": "interface",
"name": "include_empty_req_extends_when_interface_kind"
},
{
"flags": 6,
"kindOf": "class",
"name": "include_method_attrs"
},
{
"flags": 9,
"kindOf": "unknown",
"name": "include_nonempty_always"
},
{
"flags": 0,
"kindOf": "typeAlias",
"name": "my_type_alias"
}
]
}"#,
)
}
#[test]
fn test_flags() {
let flags = Flag::zero();
assert!(!Flag::Final.is_set(flags));
let flags = Flag::Final.set(flags);
let flags = Flag::Abstract.set(flags);
assert!(Flag::Final.is_set(flags));
assert!(Flag::Abstract.is_set(flags));
}
} |
OCaml | hhvm/hphp/hack/src/facts/facts_parser.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
open Facts
let flags_abstract = 1
let flags_final = 2
let extract_as_json_string
~(php5_compat_mode : bool)
~(hhvm_compat_mode : bool)
~(disable_legacy_soft_typehints : bool)
~(allow_new_attribute_syntax : bool)
~(disable_legacy_attribute_syntax : bool)
~(enable_xhp_class_modifier : bool)
~(disable_xhp_element_mangling : bool)
~(mangle_xhp_mode : bool)
~(auto_namespace_map : (string * string) list)
~(filename : Relative_path.t)
~(text : string) =
(* return empty string if file has syntax errors *)
let bool2int b =
if b then
1
else
0
in
ignore @@ disable_legacy_soft_typehints;
ignore @@ disable_legacy_attribute_syntax;
Rust_facts_ffi.extract_as_json_ffi
((bool2int php5_compat_mode lsl 0)
lor (bool2int hhvm_compat_mode lsl 1)
lor (bool2int allow_new_attribute_syntax lsl 2)
lor (bool2int enable_xhp_class_modifier lsl 3)
lor (bool2int disable_xhp_element_mangling lsl 4))
auto_namespace_map
filename
text
mangle_xhp_mode
|> Option.map ~f:(fun unnormalized ->
(* make it compact (same line breaks and whitespace) via Hh_json *)
(* to avoid differences in output (because many tests rely on it!) *)
unnormalized |> Hh_json.json_of_string |> Hh_json.json_to_multiline)
let from_text
~(php5_compat_mode : bool)
~(hhvm_compat_mode : bool)
~(disable_legacy_soft_typehints : bool)
~(allow_new_attribute_syntax : bool)
~(disable_legacy_attribute_syntax : bool)
~(enable_xhp_class_modifier : bool)
~(disable_xhp_element_mangling : bool)
~(mangle_xhp_mode : bool)
~(auto_namespace_map : (string * string) list)
~(filename : Relative_path.t)
~(text : string) =
let open Option in
extract_as_json_string
~php5_compat_mode
~hhvm_compat_mode
~disable_legacy_soft_typehints
~allow_new_attribute_syntax
~disable_legacy_attribute_syntax
~enable_xhp_class_modifier
~disable_xhp_element_mangling
~mangle_xhp_mode
~auto_namespace_map
~filename
~text
|> Option.map ~f:Hh_json.json_of_string
>>= facts_from_json |
OCaml Interface | hhvm/hphp/hack/src/facts/facts_parser.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 flags_abstract : int
val flags_final : int
val from_text :
php5_compat_mode:bool ->
hhvm_compat_mode:bool ->
disable_legacy_soft_typehints:bool ->
allow_new_attribute_syntax:bool ->
disable_legacy_attribute_syntax:bool ->
enable_xhp_class_modifier:bool ->
disable_xhp_element_mangling:bool ->
mangle_xhp_mode:bool ->
auto_namespace_map:(string * string) list ->
filename:Relative_path.t ->
text:string ->
Facts.facts option |
TOML | hhvm/hphp/hack/src/facts/cargo/facts_rust/Cargo.toml | # @generated by autocargo
[package]
name = "facts_rust"
version = "0.0.0"
edition = "2021"
[lib]
path = "../../facts.rs"
[dependencies]
hhbc_string_utils = { version = "0.0.0", path = "../../../hackc/utils/cargo/hhbc_string_utils" }
oxidized_by_ref = { version = "0.0.0", path = "../../../oxidized_by_ref" }
serde = { version = "1.0.176", features = ["derive", "rc"] }
serde_derive = "1.0.176"
serde_json = { version = "1.0.100", features = ["float_roundtrip", "unbounded_depth"] }
[dev-dependencies]
pretty_assertions = { version = "1.2", features = ["alloc"], default-features = false } |
TOML | hhvm/hphp/hack/src/facts/cargo/rust_facts_ffi/Cargo.toml | # @generated by autocargo
[package]
name = "rust_facts_ffi"
version = "0.0.0"
edition = "2021"
[lib]
path = "../../rust_facts_ffi/rust_facts_ffi.rs"
test = false
doctest = false
crate-type = ["lib", "staticlib"]
[dependencies]
bumpalo = { version = "3.11.1", features = ["collections"] }
direct_decl_parser = { version = "0.0.0", path = "../../../parser/api/cargo/direct_decl_parser" }
facts_rust = { version = "0.0.0", path = "../facts_rust" }
hhbc_string_utils = { version = "0.0.0", path = "../../../hackc/utils/cargo/hhbc_string_utils" }
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" }
relative_path = { version = "0.0.0", path = "../../../utils/rust/relative_path" } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.