language
stringlengths 0
24
| filename
stringlengths 9
214
| code
stringlengths 99
9.93M
|
---|---|---|
Rust | hhvm/hphp/hack/src/providers/hackrs_provider_backend/hackrs_provider_backend.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.
pub mod naming_table;
#[cfg(test)]
mod test_naming_table;
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use anyhow::Result;
use datastore::ChangesStore;
use datastore::Store;
use decl_parser::DeclParser;
use decl_parser::DeclParserOptions;
use file_provider::DiskProvider;
use file_provider::FileProvider;
use folded_decl_provider::FoldedDeclProvider;
use folded_decl_provider::LazyFoldedDeclProvider;
use naming_provider::NamingProvider;
use naming_table::NamingTable;
use ocamlrep::ptr::UnsafeOcamlPtr;
use ocamlrep::FromOcamlRep;
use ocamlrep::ToOcamlRep;
use ocamlrep_caml_builtins::Int64;
use oxidized::file_info::HashType;
use oxidized::file_info::Mode;
use oxidized::file_info::NameType;
use oxidized::file_info::Names;
use oxidized::global_options::GlobalOptions;
use oxidized::naming_types;
use oxidized_by_ref::direct_decl_parser::ParsedFileWithHashes;
use pos::RelativePath;
use pos::RelativePathCtx;
use pos::TypeName;
use shallow_decl_provider::LazyShallowDeclProvider;
use shallow_decl_provider::ShallowDeclProvider;
use shallow_decl_provider::ShallowDeclStore;
use shm_store::OcamlShmStore;
use ty::decl;
use ty::decl::folded::FoldedClass;
use ty::decl::shallow::NamedDecl;
use ty::reason::BReason as BR;
pub struct HhServerProviderBackend {
path_ctx: Arc<RelativePathCtx>,
opts: GlobalOptions,
decl_parser: DeclParser<BR>,
file_store: Arc<ChangesStore<RelativePath, FileType>>,
file_provider: Arc<FileProviderWithContext>,
naming_table: Arc<NamingTableWithContext>,
ctx_is_empty: Arc<AtomicBool>,
/// Collection of Arcs pointing to the backing stores for the
/// ShallowDeclStore below, allowing us to invoke push/pop_local_changes.
shallow_decl_changes_store: Arc<ShallowStoreWithChanges>,
shallow_decl_store: Arc<ShallowDeclStore<BR>>,
lazy_shallow_decl_provider: Arc<LazyShallowDeclProvider<BR>>,
folded_classes_shm: Arc<OcamlShmStore<TypeName, Arc<FoldedClass<BR>>>>,
folded_classes_store: Arc<ChangesStore<TypeName, Arc<FoldedClass<BR>>>>,
folded_decl_provider: Arc<LazyFoldedDeclProvider<BR>>,
}
#[derive(serde::Serialize, serde::Deserialize)]
pub struct Config {
pub path_ctx: RelativePathCtx,
pub opts: GlobalOptions,
pub db_path: Option<PathBuf>,
}
impl HhServerProviderBackend {
pub fn new(config: Config) -> Result<Self> {
let Config {
path_ctx,
opts,
db_path,
} = config;
let path_ctx = Arc::new(path_ctx);
let file_store = Arc::new(ChangesStore::new(Arc::new(OcamlShmStore::new(
"File",
shm_store::Evictability::NonEvictable,
shm_store::Compression::default(),
))));
let ctx_is_empty = Arc::new(AtomicBool::new(true));
let file_provider = Arc::new(FileProviderWithContext {
ctx_is_empty: Arc::clone(&ctx_is_empty),
backend: FileProviderWithChanges {
delta_and_changes: Arc::clone(&file_store),
disk: DiskProvider::new(Arc::clone(&path_ctx), None),
},
});
let decl_parser = DeclParser::new(
Arc::clone(&file_provider) as _,
DeclParserOptions::from_parser_options(&opts),
opts.po_deregister_php_stdlib,
);
let naming_table = Arc::new(NamingTableWithContext {
ctx_is_empty: Arc::clone(&ctx_is_empty),
fallback: NamingTable::new(db_path)?,
});
let shallow_decl_changes_store = Arc::new(ShallowStoreWithChanges::new());
let shallow_decl_store = shallow_decl_changes_store.as_shallow_decl_store();
let lazy_shallow_decl_provider = Arc::new(LazyShallowDeclProvider::new(
Arc::clone(&shallow_decl_store),
Arc::clone(&naming_table) as _,
decl_parser.clone(),
));
let folded_classes_shm = Arc::new(OcamlShmStore::new(
"Decl_Class",
shm_store::Evictability::Evictable,
shm_store::Compression::default(),
));
let folded_classes_store =
Arc::new(ChangesStore::new(Arc::clone(&folded_classes_shm) as _));
let folded_decl_provider = Arc::new(LazyFoldedDeclProvider::new(
Arc::new(opts.clone()),
Arc::clone(&folded_classes_store) as _,
Arc::clone(&lazy_shallow_decl_provider) as _,
));
Ok(Self {
path_ctx,
opts,
file_store,
file_provider,
decl_parser,
folded_decl_provider,
naming_table,
ctx_is_empty,
shallow_decl_changes_store,
shallow_decl_store,
lazy_shallow_decl_provider,
folded_classes_shm,
folded_classes_store,
})
}
pub fn config(&self) -> Config {
Config {
path_ctx: (*self.path_ctx).clone(),
db_path: self.naming_table.fallback.db_path(),
opts: self.opts.clone(),
}
}
pub fn opts(&self) -> &GlobalOptions {
&self.opts
}
/// Get our implementation of NamingProvider, which calls into OCaml to
/// provide results which take IDE buffers into consideration.
pub fn naming_table_with_context(&self) -> &NamingTableWithContext {
&self.naming_table
}
/// Get the underlying naming table (which includes the SQL database, our
/// sharedmem cache layer, and the ChangesStore layer used in tests).
pub fn naming_table(&self) -> &NamingTable {
&self.naming_table.fallback
}
pub fn file_store(&self) -> &dyn Store<RelativePath, FileType> {
&*self.file_store
}
pub fn shallow_decl_provider(&self) -> &dyn ShallowDeclProvider<BR> {
&*self.lazy_shallow_decl_provider
}
/// Decl-parse the given file, dedup duplicate definitions of the same
/// symbol (within the file, as well as removing losers of naming conflicts
/// with other files), and add the parsed decls to the shallow decl store.
pub fn parse_and_cache_decls<'a>(
&self,
path: RelativePath,
text: &'a [u8],
arena: &'a bumpalo::Bump,
) -> Result<ParsedFileWithHashes<'a>> {
let hashed_file = self.decl_parser.parse_impl(path, text, arena);
self.lazy_shallow_decl_provider.dedup_and_add_decls(
path,
(hashed_file.iter()).map(|(name, decl, _)| NamedDecl::from(&(*name, *decl))),
)?;
Ok(hashed_file)
}
/// Directly add the given decls to the shallow decl store (without removing
/// php_stdlib decls, deduping, or removing naming conflict losers).
pub fn add_decls(
&self,
decls: &[&(&str, oxidized_by_ref::shallow_decl_defs::Decl<'_>)],
) -> Result<()> {
self.shallow_decl_store
.add_decls(decls.iter().copied().map(Into::into))
}
pub fn push_local_changes(&self) {
self.file_store.push_local_changes();
self.naming_table.fallback.push_local_changes();
self.shallow_decl_changes_store.push_local_changes();
self.folded_classes_store.push_local_changes();
}
pub fn pop_local_changes(&self) {
self.file_store.pop_local_changes();
self.naming_table.fallback.pop_local_changes();
self.shallow_decl_changes_store.pop_local_changes();
self.folded_classes_store.pop_local_changes();
}
pub fn set_ctx_empty(&self, is_empty: bool) {
self.ctx_is_empty.store(is_empty, Ordering::SeqCst);
}
pub fn oldify_defs(&self, names: &Names) -> Result<()> {
self.folded_classes_store
.remove_batch(&mut names.classes.iter().map(Into::into))?;
self.shallow_decl_changes_store.oldify_defs(names)
}
pub fn remove_old_defs(&self, names: &Names) -> Result<()> {
self.folded_classes_store
.remove_batch(&mut names.classes.iter().map(Into::into))?;
self.shallow_decl_changes_store.remove_old_defs(names)
}
pub fn remove_defs(&self, names: &Names) -> Result<()> {
self.folded_classes_store
.remove_batch(&mut names.classes.iter().map(Into::into))?;
self.shallow_decl_changes_store.remove_defs(names)
}
pub fn get_old_defs(
&self,
names: &Names,
) -> Result<(
BTreeMap<pos::TypeName, Option<Arc<decl::ShallowClass<BR>>>>,
BTreeMap<pos::FunName, Option<Arc<decl::FunDecl<BR>>>>,
BTreeMap<pos::TypeName, Option<Arc<decl::TypedefDecl<BR>>>>,
BTreeMap<pos::ConstName, Option<Arc<decl::ConstDecl<BR>>>>,
BTreeMap<pos::ModuleName, Option<Arc<decl::ModuleDecl<BR>>>>,
)> {
self.shallow_decl_changes_store.get_old_defs(names)
}
}
impl rust_provider_backend_api::RustProviderBackend<BR> for HhServerProviderBackend {
fn file_provider(&self) -> &dyn FileProvider {
&*self.file_provider
}
fn naming_provider(&self) -> &dyn NamingProvider {
&*self.naming_table
}
fn shallow_decl_provider(&self) -> &dyn ShallowDeclProvider<BR> {
&*self.lazy_shallow_decl_provider
}
fn folded_decl_provider(&self) -> &dyn FoldedDeclProvider<BR> {
&*self.folded_decl_provider
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
#[rustfmt::skip]
impl HhServerProviderBackend {
/// SAFETY: This method (and all other `get_ocaml_` methods) call into the
/// OCaml runtime and may trigger a GC. Must be invoked from the main thread
/// with no concurrent interaction with the OCaml runtime. The returned
/// `UnsafeOcamlPtr` is unrooted and could be invalidated if the GC is
/// triggered after this method returns.
pub unsafe fn get_ocaml_shallow_class(&self, name: &[u8]) -> Option<UnsafeOcamlPtr> {
if self.shallow_decl_changes_store.classes.has_local_changes() { None }
else { self.shallow_decl_changes_store.classes_shm.get_ocaml_by_byte_string(name) }
}
pub unsafe fn get_ocaml_typedef(&self, name: &[u8]) -> Option<UnsafeOcamlPtr> {
if self.shallow_decl_changes_store.typedefs.has_local_changes() { None }
else { self.shallow_decl_changes_store.typedefs_shm.get_ocaml_by_byte_string(name) }
}
pub unsafe fn get_ocaml_fun(&self, name: &[u8]) -> Option<UnsafeOcamlPtr> {
if self.shallow_decl_changes_store.funs.has_local_changes() { None }
else { self.shallow_decl_changes_store.funs_shm.get_ocaml_by_byte_string(name) }
}
pub unsafe fn get_ocaml_const(&self, name: &[u8]) -> Option<UnsafeOcamlPtr> {
if self.shallow_decl_changes_store.consts.has_local_changes() { None }
else { self.shallow_decl_changes_store.consts_shm.get_ocaml_by_byte_string(name) }
}
pub unsafe fn get_ocaml_module(&self, name: &[u8]) -> Option<UnsafeOcamlPtr> {
if self.shallow_decl_changes_store.modules.has_local_changes() { None }
else { self.shallow_decl_changes_store.modules_shm.get_ocaml_by_byte_string(name) }
}
pub unsafe fn get_ocaml_folded_class(&self, name: &[u8]) -> Option<UnsafeOcamlPtr> {
if self.folded_classes_store.has_local_changes() { None }
else { self.folded_classes_shm.get_ocaml_by_byte_string(name) }
}
/// Returns `Option<UnsafeOcamlPtr>` where the `UnsafeOcamlPtr` is a value
/// of OCaml type `FileInfo.pos option`.
pub unsafe fn get_ocaml_type_pos(&self, name: &[u8]) -> Option<UnsafeOcamlPtr> {
// If the context is non-empty, fall back to the slow path by returning None.
// `self.naming_table.fallback` returns None when there are local changes.
if !self.ctx_is_empty.load(Ordering::SeqCst) { None }
else { self.naming_table.fallback.get_ocaml_type_pos(name) }
}
pub unsafe fn get_ocaml_fun_pos(&self, name: &[u8]) -> Option<UnsafeOcamlPtr> {
if !self.ctx_is_empty.load(Ordering::SeqCst) { None }
else { self.naming_table.fallback.get_ocaml_fun_pos(name) }
}
pub unsafe fn get_ocaml_const_pos(&self, name: &[u8]) -> Option<UnsafeOcamlPtr> {
if !self.ctx_is_empty.load(Ordering::SeqCst) { None }
else { self.naming_table.fallback.get_ocaml_const_pos(name) }
}
pub unsafe fn get_ocaml_module_pos(&self, name: &[u8]) -> Option<UnsafeOcamlPtr> {
if !self.ctx_is_empty.load(Ordering::SeqCst) { None }
else { self.naming_table.fallback.get_ocaml_module_pos(name) }
}
}
#[rustfmt::skip]
struct ShallowStoreWithChanges {
classes: Arc<ChangesStore <TypeName, Arc<decl::ShallowClass<BR>>>>,
classes_shm: Arc<OcamlShmStore<TypeName, Arc<decl::ShallowClass<BR>>>>,
typedefs: Arc<ChangesStore <TypeName, Arc<decl::TypedefDecl<BR>>>>,
typedefs_shm: Arc<OcamlShmStore<TypeName, Arc<decl::TypedefDecl<BR>>>>,
funs: Arc<ChangesStore <pos::FunName, Arc<decl::FunDecl<BR>>>>,
funs_shm: Arc<OcamlShmStore<pos::FunName, Arc<decl::FunDecl<BR>>>>,
consts: Arc<ChangesStore <pos::ConstName, Arc<decl::ConstDecl<BR>>>>,
consts_shm: Arc<OcamlShmStore<pos::ConstName, Arc<decl::ConstDecl<BR>>>>,
modules: Arc<ChangesStore <pos::ModuleName, Arc<decl::ModuleDecl<BR>>>>,
modules_shm: Arc<OcamlShmStore<pos::ModuleName, Arc<decl::ModuleDecl<BR>>>>,
store_view: Arc<ShallowDeclStore<BR>>,
}
impl ShallowStoreWithChanges {
#[rustfmt::skip]
fn new() -> Self {
use shm_store::{Compression, Evictability::{Evictable, NonEvictable}};
let classes_shm = Arc::new(OcamlShmStore::new("Decl_ShallowClass", NonEvictable, Compression::default()));
let typedefs_shm = Arc::new(OcamlShmStore::new("Decl_Typedef", Evictable, Compression::default()));
let funs_shm = Arc::new(OcamlShmStore::new("Decl_Fun", Evictable, Compression::default()));
let consts_shm = Arc::new(OcamlShmStore::new("Decl_GConst", Evictable, Compression::default()));
let modules_shm = Arc::new(OcamlShmStore::new("Decl_Module", Evictable, Compression::default()));
let classes = Arc::new(ChangesStore::new(Arc::clone(&classes_shm) as _));
let typedefs = Arc::new(ChangesStore::new(Arc::clone(&typedefs_shm) as _));
let funs = Arc::new(ChangesStore::new(Arc::clone(&funs_shm) as _));
let consts = Arc::new(ChangesStore::new(Arc::clone(&consts_shm) as _));
let modules = Arc::new(ChangesStore::new(Arc::clone(&modules_shm) as _));
let store_view = Arc::new(ShallowDeclStore::with_no_member_stores(
Arc::clone(&classes) as _,
Arc::clone(&typedefs) as _,
Arc::clone(&funs) as _,
Arc::clone(&consts) as _,
Arc::clone(&modules) as _,
));
Self {
classes,
typedefs,
funs,
consts,
modules,
classes_shm,
typedefs_shm,
funs_shm,
consts_shm,
modules_shm,
store_view,
}
}
fn push_local_changes(&self) {
self.classes.push_local_changes();
self.typedefs.push_local_changes();
self.funs.push_local_changes();
self.consts.push_local_changes();
self.modules.push_local_changes();
}
fn pop_local_changes(&self) {
self.classes.pop_local_changes();
self.typedefs.pop_local_changes();
self.funs.pop_local_changes();
self.consts.pop_local_changes();
self.modules.pop_local_changes();
}
fn as_shallow_decl_store(&self) -> Arc<ShallowDeclStore<BR>> {
Arc::clone(&self.store_view)
}
fn to_old_key<K: AsRef<str> + From<String> + Copy>(key: K) -> K {
format!("old${}", key.as_ref()).into()
}
fn oldify<K, V>(
&self,
store: &dyn Store<K, V>,
names: &mut dyn Iterator<Item = K>,
) -> Result<()>
where
K: AsRef<str> + From<String> + Copy,
{
let mut moves = vec![];
let mut deletes = vec![];
for name in names {
let old_name = Self::to_old_key(name);
if store.contains_key(name)? {
moves.push((name, old_name));
} else if store.contains_key(old_name)? {
deletes.push(old_name);
}
}
store.move_batch(&mut moves.into_iter())?;
store.remove_batch(&mut deletes.into_iter())?;
Ok(())
}
fn remove_old<K, V>(
&self,
store: &dyn Store<K, V>,
names: &mut dyn Iterator<Item = K>,
) -> Result<()>
where
K: AsRef<str> + From<String> + Copy,
{
let mut deletes = vec![];
for name in names {
let old_name = Self::to_old_key(name);
if store.contains_key(old_name)? {
deletes.push(old_name);
}
}
store.remove_batch(&mut deletes.into_iter())
}
fn get_old<K, V>(
&self,
store: &dyn Store<K, V>,
names: &mut dyn Iterator<Item = K>,
) -> Result<BTreeMap<K, Option<V>>>
where
K: AsRef<str> + From<String> + Copy + Ord,
{
names
.map(|name| Ok((name, store.get(Self::to_old_key(name))?)))
.collect()
}
#[rustfmt::skip]
fn oldify_defs(&self, names: &Names) -> Result<()> {
self.oldify(&*self.classes, &mut names.classes.iter().map(Into::into))?;
self.oldify(&*self.funs, &mut names.funs.iter().map(Into::into))?;
self.oldify(&*self.typedefs, &mut names.types.iter().map(Into::into))?;
self.oldify(&*self.consts, &mut names.consts.iter().map(Into::into))?;
self.oldify(&*self.modules, &mut names.modules.iter().map(Into::into))?;
Ok(())
}
#[rustfmt::skip]
fn remove_old_defs(&self, names: &Names) -> Result<()> {
self.remove_old(&*self.classes, &mut names.classes.iter().map(Into::into))?;
self.remove_old(&*self.funs, &mut names.funs.iter().map(Into::into))?;
self.remove_old(&*self.typedefs, &mut names.types.iter().map(Into::into))?;
self.remove_old(&*self.consts, &mut names.consts.iter().map(Into::into))?;
self.remove_old(&*self.modules, &mut names.modules.iter().map(Into::into))?;
Ok(())
}
#[rustfmt::skip]
fn remove_defs(&self, names: &Names) -> Result<()> {
self.classes .remove_batch(&mut names.classes.iter().map(Into::into))?;
self.funs .remove_batch(&mut names.funs.iter().map(Into::into))?;
self.typedefs.remove_batch(&mut names.types.iter().map(Into::into))?;
self.consts .remove_batch(&mut names.consts.iter().map(Into::into))?;
self.modules .remove_batch(&mut names.modules.iter().map(Into::into))?;
Ok(())
}
#[rustfmt::skip]
fn get_old_defs(
&self,
names: &Names,
) -> Result<(
BTreeMap<pos::TypeName, Option<Arc<decl::ShallowClass<BR>>>>,
BTreeMap<pos::FunName, Option<Arc<decl::FunDecl<BR>>>>,
BTreeMap<pos::TypeName, Option<Arc<decl::TypedefDecl<BR>>>>,
BTreeMap<pos::ConstName, Option<Arc<decl::ConstDecl<BR>>>>,
BTreeMap<pos::ModuleName, Option<Arc<decl::ModuleDecl<BR>>>>,
)> {
Ok((
self.get_old(&*self.classes, &mut names.classes.iter().map(Into::into))?,
self.get_old(&*self.funs, &mut names.funs.iter().map(Into::into))?,
self.get_old(&*self.typedefs, &mut names.types.iter().map(Into::into))?,
self.get_old(&*self.consts, &mut names.consts.iter().map(Into::into))?,
self.get_old(&*self.modules, &mut names.modules.iter().map(Into::into))?,
))
}
}
/// Invoke the callback registered with the given name (via
/// `Callback.register`).
///
/// # Panics
///
/// Raises a panic if no callback is registered with the given name, the
/// callback raises an exception, or the returned value cannot be converted to
/// type `T`.
///
/// # Safety
///
/// Calls into the OCaml runtime and may trigger a GC, which may invalidate any
/// unrooted ocaml values (e.g., `UnsafeOcamlPtr`, `ocamlrep::Value`).
unsafe fn call_ocaml<T: FromOcamlRep>(callback_name: &'static str, args: &impl ToOcamlRep) -> T {
let callback = ocaml_runtime::named_value(callback_name).unwrap();
let args = ocamlrep_ocamlpool::to_ocaml(args);
let ocaml_result = ocaml_runtime::callback_exn(callback, args).unwrap();
T::from_ocaml(ocaml_result).unwrap()
}
/// An implementation of `FileProvider` which calls into
/// `Provider_context.get_entries` in order to read from IDE entries before
/// falling back to reading from ChangesStore/sharedmem/disk.
#[derive(Debug)]
pub struct FileProviderWithContext {
ctx_is_empty: Arc<AtomicBool>,
backend: FileProviderWithChanges,
}
impl FileProvider for FileProviderWithContext {
fn get(&self, file: RelativePath) -> Result<bstr::BString> {
if !self.ctx_is_empty.load(Ordering::SeqCst) {
// SAFETY: We must have no unrooted values.
if let Some(s) =
unsafe { call_ocaml("hh_rust_provider_backend_get_entry_contents", &file) }
{
return Ok(s);
}
}
self.backend.get(file)
}
}
#[derive(Clone, Debug, ToOcamlRep, FromOcamlRep)]
#[derive(serde::Serialize, serde::Deserialize)]
pub enum FileType {
Disk(bstr::BString),
Ide(bstr::BString),
}
/// Port of `File_provider.ml`.
#[derive(Debug)]
struct FileProviderWithChanges {
// We could use DeltaStore here if not for the fact that the OCaml
// implementation of `File_provider.get` does not fall back to disk when the
// given path isn't present in sharedmem/local_changes (it only does so for
// `File_provider.get_contents`).
delta_and_changes: Arc<ChangesStore<RelativePath, FileType>>,
disk: DiskProvider,
}
impl FileProvider for FileProviderWithChanges {
fn get(&self, file: RelativePath) -> Result<bstr::BString> {
match self.delta_and_changes.get(file)? {
Some(FileType::Disk(contents)) => Ok(contents),
Some(FileType::Ide(contents)) => Ok(contents),
None => match self.disk.read(file) {
Ok(contents) => Ok(contents),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok("".into()),
Err(e) => Err(e.into()),
},
}
}
}
/// An implementation of `NamingProvider` which calls into `Provider_context` to
/// give naming results reflecting the contents of IDE buffers.
#[derive(Debug)]
pub struct NamingTableWithContext {
ctx_is_empty: Arc<AtomicBool>,
fallback: NamingTable,
}
impl NamingTableWithContext {
fn ctx_is_empty(&self) -> bool {
self.ctx_is_empty.load(Ordering::SeqCst)
}
fn find_symbol_in_context_with_suppression(
&self,
find_symbol_callback_name: &'static str,
fallback: impl Fn() -> Result<Option<(naming_table::Pos, NameType)>>,
name: pos::Symbol,
) -> Result<Option<(naming_table::Pos, file_info::NameType)>> {
if self.ctx_is_empty() {
fallback()
} else {
// SAFETY: We must have no unrooted values.
let ctx_pos_opt = unsafe { call_ocaml(find_symbol_callback_name, &name) };
let fallback_pos_opt = fallback()?;
match (ctx_pos_opt, fallback_pos_opt) {
(None, None) => Ok(None),
(Some(ctx_pos), None) => Ok(Some(ctx_pos)),
(None, Some((pos, name_type))) => {
if unsafe { call_ocaml("hh_rust_provider_backend_is_pos_in_ctx", &pos) } {
// If fallback said it thought the symbol was in ctx, but we definitively
// know that it isn't, then the answer is None.
Ok(None)
} else {
Ok(Some((pos, name_type)))
}
}
(Some((ctx_pos, ctx_name_type)), Some((fallback_pos, fallback_name_type))) => {
// The alphabetically first filename wins
let ctx_fn = ctx_pos.path();
let fallback_fn = fallback_pos.path();
if ctx_fn <= fallback_fn {
// symbol is either (1) a duplicate in both context and fallback, and context is the winner,
// or (2) not a duplicate, and both context and fallback claim it to be defined
// in a file that's part of the context, in which case context wins.
Ok(Some((ctx_pos, ctx_name_type)))
} else {
// symbol is a duplicate in both context and fallback, and fallback is the winner
Ok(Some((fallback_pos, fallback_name_type)))
}
}
}
}
}
pub fn get_type_pos(
&self,
name: TypeName,
) -> Result<Option<(naming_table::Pos, naming_types::KindOfType)>> {
Ok(self
.find_symbol_in_context_with_suppression(
"hh_rust_provider_backend_find_type_in_context",
|| {
let pos_opt = self.fallback.get_type_pos(name)?;
Ok(pos_opt.map(|(pos, kind)| (pos, kind.into())))
},
name.as_symbol(),
)?
.map(|(pos, name_type)| (pos, name_type.try_into().unwrap())))
}
pub fn get_fun_pos(&self, name: pos::FunName) -> Result<Option<naming_table::Pos>> {
Ok(self
.find_symbol_in_context_with_suppression(
"hh_rust_provider_backend_find_fun_in_context",
|| {
let pos_opt = self.fallback.get_fun_pos(name)?;
Ok(pos_opt.map(|pos| (pos, NameType::Fun)))
},
name.as_symbol(),
)?
.map(|(pos, _)| pos))
}
pub fn get_const_pos(&self, name: pos::ConstName) -> Result<Option<naming_table::Pos>> {
Ok(self
.find_symbol_in_context_with_suppression(
"hh_rust_provider_backend_find_const_in_context",
|| {
let pos_opt = self.fallback.get_const_pos(name)?;
Ok(pos_opt.map(|pos| (pos, NameType::Const)))
},
name.as_symbol(),
)?
.map(|(pos, _)| pos))
}
pub fn get_module_pos(&self, name: pos::ModuleName) -> Result<Option<naming_table::Pos>> {
Ok(self
.find_symbol_in_context_with_suppression(
"hh_rust_provider_backend_find_module_in_context",
|| {
let pos_opt = self.fallback.get_module_pos(name)?;
Ok(pos_opt.map(|pos| (pos, NameType::Module)))
},
name.as_symbol(),
)?
.map(|(pos, _)| pos))
}
}
impl NamingProvider for NamingTableWithContext {
fn get_type_path_and_kind(
&self,
name: pos::TypeName,
) -> Result<Option<(RelativePath, naming_types::KindOfType)>> {
Ok(self.get_type_pos(name)?.map(|(pos, k)| (pos.path(), k)))
}
fn get_fun_path(&self, name: pos::FunName) -> Result<Option<RelativePath>> {
Ok(self.get_fun_pos(name)?.map(|pos| pos.path()))
}
fn get_const_path(&self, name: pos::ConstName) -> Result<Option<RelativePath>> {
Ok(self.get_const_pos(name)?.map(|pos| pos.path()))
}
fn get_module_path(&self, name: pos::ModuleName) -> Result<Option<RelativePath>> {
Ok(self.get_module_pos(name)?.map(|pos| pos.path()))
}
fn get_canon_type_name(&self, name: pos::TypeName) -> Result<Option<pos::TypeName>> {
if !self.ctx_is_empty() {
// SAFETY: We must have no unrooted values.
if let name_opt @ Some(..) = unsafe {
call_ocaml(
"hh_rust_provider_backend_find_type_canon_name_in_context",
&name,
)
} {
return Ok(name_opt);
}
}
self.fallback.get_canon_type_name(name)
}
fn get_canon_fun_name(&self, name: pos::FunName) -> Result<Option<pos::FunName>> {
if !self.ctx_is_empty() {
// SAFETY: We must have no unrooted values.
if let name_opt @ Some(..) = unsafe {
call_ocaml(
"hh_rust_provider_backend_find_fun_canon_name_in_context",
&name,
)
} {
return Ok(name_opt);
}
}
self.fallback.get_canon_fun_name(name)
}
}
/// An id contains a pos, name and a optional decl hash. The decl hash is None
/// only in the case when we didn't compute it for performance reasons
///
/// We can't use oxidized::file_info::Id here because that data structure
/// contains an Arc, which can't be used in a multi-threading context.
#[derive(Clone, Debug)]
pub struct Id(naming_table::Pos, String, Option<Int64>);
impl From<Id> for oxidized::file_info::Id {
fn from(val: Id) -> Self {
oxidized::file_info::Id(val.0.into(), val.1, val.2)
}
}
/// Variant of `FileInfo` which is compatible with parallelism.
///
/// Can be converted into OCaml via it's `Into<oxidized::file_info::FileInfo>` trait.
#[derive(Clone, Debug)]
pub struct FileInfo {
pub hash: HashType,
pub file_mode: Option<Mode>,
pub funs: Vec<Id>,
pub classes: Vec<Id>,
pub typedefs: Vec<Id>,
pub consts: Vec<Id>,
pub modules: Vec<Id>,
}
impl From<FileInfo> for oxidized::file_info::FileInfo {
fn from(val: FileInfo) -> Self {
oxidized::file_info::FileInfo {
hash: val.hash,
file_mode: val.file_mode,
funs: val.funs.into_iter().map(Into::into).collect(),
classes: val.classes.into_iter().map(Into::into).collect(),
typedefs: val.typedefs.into_iter().map(Into::into).collect(),
consts: val.consts.into_iter().map(Into::into).collect(),
modules: val.modules.into_iter().map(Into::into).collect(),
comments: None,
}
}
}
impl<'a> From<ParsedFileWithHashes<'a>> for FileInfo {
/// c.f. OCaml Direct_decl_parser.decls_to_fileinfo
fn from(file: ParsedFileWithHashes<'a>) -> Self {
let mut info = FileInfo {
hash: HashType(Some(Int64::from(file.file_decls_hash.as_u64() as i64))),
file_mode: file.mode,
funs: vec![],
classes: vec![],
typedefs: vec![],
consts: vec![],
modules: vec![],
};
let pos = |p: &oxidized_by_ref::pos::Pos<'_>| naming_table::Pos::Full(p.into());
use oxidized_by_ref::shallow_decl_defs::Decl;
for &(name, decl, hash) in file.iter() {
let hash = Int64::from(hash.as_u64() as i64);
match decl {
Decl::Class(x) => info
.classes
.push(Id(pos(x.name.0), name.into(), Some(hash))),
Decl::Fun(x) => info.funs.push(Id(pos(x.pos), name.into(), Some(hash))),
Decl::Typedef(x) => info.typedefs.push(Id(pos(x.pos), name.into(), Some(hash))),
Decl::Const(x) => info.consts.push(Id(pos(x.pos), name.into(), Some(hash))),
Decl::Module(x) => info.modules.push(Id(pos(x.pos), name.into(), Some(hash))),
}
}
// Match OCaml ordering
info.classes.reverse();
info.funs.reverse();
info.typedefs.reverse();
info.consts.reverse();
info.modules.reverse();
info
}
} |
Rust | hhvm/hphp/hack/src/providers/hackrs_provider_backend/naming_table.rs | // Copyright (c) Meta Platforms, Inc. and affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::path::PathBuf;
use std::sync::Arc;
use anyhow::Result;
use datastore::ChangesStore;
use datastore::DeltaStore;
use datastore::ReadonlyStore;
use hh24_types::ToplevelCanonSymbolHash;
use hh24_types::ToplevelSymbolHash;
use naming_provider::NamingProvider;
use naming_types::KindOfType;
use ocamlrep::ptr::UnsafeOcamlPtr;
use oxidized::file_info::NameType;
use oxidized::naming_types;
use parking_lot::Mutex;
use pos::ConstName;
use pos::FunName;
use pos::ModuleName;
use pos::RelativePath;
use pos::TypeName;
use reverse_naming_table::ReverseNamingTable;
use shm_store::OcamlShmStore;
/// Designed after naming_heap.ml.
pub struct NamingTable {
types: ReverseNamingTable<TypeName, (Pos, KindOfType)>,
funs: ReverseNamingTable<FunName, Pos>,
consts: ChangesStore<ToplevelSymbolHash, Pos>,
consts_shm: Arc<OcamlShmStore<ToplevelSymbolHash, Option<Pos>>>,
modules: ChangesStore<ToplevelSymbolHash, Pos>,
modules_shm: Arc<OcamlShmStore<ToplevelSymbolHash, Option<Pos>>>,
db: Arc<MaybeNamingDb>,
}
impl NamingTable {
pub fn new(db_path: Option<PathBuf>) -> Result<Self> {
let db = Arc::new(MaybeNamingDb(Mutex::new(None)));
if let Some(db_path) = db_path {
db.set_db_path(db_path)?;
}
let consts_shm = Arc::new(OcamlShmStore::new(
"Naming_ConstPos",
shm_store::Evictability::NonEvictable,
shm_store::Compression::None,
));
let modules_shm = Arc::new(OcamlShmStore::new(
"Naming_ModulePos",
shm_store::Evictability::NonEvictable,
shm_store::Compression::None,
));
Ok(Self {
types: ReverseNamingTable::new(
Arc::new(TypeDb(Arc::clone(&db))),
"Naming_TypePos",
"Naming_TypeCanon",
),
funs: ReverseNamingTable::new(
Arc::new(FunDb(Arc::clone(&db))),
"Naming_FunPos",
"Naming_FunCanon",
),
consts: ChangesStore::new(Arc::new(DeltaStore::new(
Arc::clone(&consts_shm) as _,
Arc::new(ConstDb(Arc::clone(&db))),
))),
modules: ChangesStore::new(Arc::new(DeltaStore::new(
Arc::clone(&modules_shm) as _,
Arc::new(ModuleDb(Arc::clone(&db))),
))),
consts_shm,
modules_shm,
db,
})
}
pub fn db_path(&self) -> Option<PathBuf> {
self.db.db_path()
}
pub fn set_db_path(&self, db_path: PathBuf) -> Result<()> {
self.db.set_db_path(db_path)
}
pub fn add_type(
&self,
name: TypeName,
pos_and_kind: &(file_info::Pos, KindOfType),
) -> Result<()> {
self.types
.insert(name, ((&pos_and_kind.0).into(), pos_and_kind.1))
}
pub(crate) fn get_type_pos(&self, name: TypeName) -> Result<Option<(Pos, KindOfType)>> {
self.types.get_pos(name)
}
pub fn remove_type_batch(&self, names: &[TypeName]) -> Result<()> {
self.types.remove_batch(names.iter().copied())
}
pub(crate) fn get_canon_type_name(&self, name: TypeName) -> Result<Option<TypeName>> {
self.types.get_canon_name(name)
}
pub fn add_fun(&self, name: FunName, pos: &file_info::Pos) -> Result<()> {
self.funs.insert(name, pos.into())
}
pub(crate) fn get_fun_pos(&self, name: FunName) -> Result<Option<Pos>> {
self.funs.get_pos(name)
}
pub fn remove_fun_batch(&self, names: &[FunName]) -> Result<()> {
self.funs.remove_batch(names.iter().copied())
}
pub(crate) fn get_canon_fun_name(&self, name: FunName) -> Result<Option<FunName>> {
self.funs.get_canon_name(name)
}
pub fn add_const(&self, name: ConstName, pos: &file_info::Pos) -> Result<()> {
self.consts.insert(name.into(), pos.into())
}
pub(crate) fn get_const_pos(&self, name: ConstName) -> Result<Option<Pos>> {
self.consts.get(name.into())
}
pub fn remove_const_batch(&self, names: &[ConstName]) -> Result<()> {
self.consts
.remove_batch(&mut names.iter().copied().map(Into::into))
}
pub fn add_module(&self, name: ModuleName, pos: &file_info::Pos) -> Result<()> {
self.modules.insert(name.into(), pos.into())
}
pub(crate) fn get_module_pos(&self, name: ModuleName) -> Result<Option<Pos>> {
self.modules.get(name.into())
}
pub fn remove_module_batch(&self, names: &[ModuleName]) -> Result<()> {
self.modules
.remove_batch(&mut names.iter().copied().map(Into::into))
}
pub fn push_local_changes(&self) {
self.types.push_local_changes();
self.funs.push_local_changes();
self.consts.push_local_changes();
self.modules.push_local_changes();
}
pub fn pop_local_changes(&self) {
self.types.pop_local_changes();
self.funs.pop_local_changes();
self.consts.pop_local_changes();
self.modules.pop_local_changes();
}
pub fn get_filenames_by_hash(
&self,
hashes: &deps_rust::DepSet,
) -> Result<std::collections::BTreeSet<RelativePath>> {
hashes
.iter()
.filter_map(|&hash| self.get_filename_by_hash(hash).transpose())
.collect()
}
fn get_filename_by_hash(&self, hash: deps_rust::Dep) -> Result<Option<RelativePath>> {
let hash = ToplevelSymbolHash::from_u64(hash.into());
if let Some((pos, _kind)) = self.types.get_pos_by_hash(hash)? {
return Ok(Some(pos.path()));
} else if let Some(pos) = self.funs.get_pos_by_hash(hash)? {
return Ok(Some(pos.path()));
} else if let Some(pos) = self.consts.get(hash)? {
return Ok(Some(pos.path()));
};
Ok(self
.db
.with_db(|db| db.get_path_by_symbol_hash(hash))?
.as_ref()
.map(Into::into))
}
}
impl NamingTable {
/// Returns `Option<UnsafeOcamlPtr>` where the `UnsafeOcamlPtr` is a value
/// of OCaml type `FileInfo.pos option`.
///
/// SAFETY: This method (and all other `get_ocaml_` methods) call into the
/// OCaml runtime and may trigger a GC. Must be invoked from the main thread
/// with no concurrent interaction with the OCaml runtime. The returned
/// `UnsafeOcamlPtr` is unrooted and could be invalidated if the GC is
/// triggered after this method returns.
pub(crate) unsafe fn get_ocaml_type_pos(&self, name: &[u8]) -> Option<UnsafeOcamlPtr> {
self.types
.get_ocaml_pos_by_hash(ToplevelSymbolHash::from_byte_string(
// NameType::Class and NameType::Typedef are handled the same here
file_info::NameType::Class,
name,
))
// The heap has values of type Option<Pos>, and they've already been
// converted to an OCaml value here. Map `Some(ocaml_none)` to
// `None` so that the caller doesn't need to inspect the value.
.filter(|ptr| ptr.is_block())
}
pub(crate) unsafe fn get_ocaml_fun_pos(&self, name: &[u8]) -> Option<UnsafeOcamlPtr> {
self.funs
.get_ocaml_pos_by_hash(ToplevelSymbolHash::from_byte_string(
file_info::NameType::Fun,
name,
))
.filter(|ptr| ptr.is_block())
}
pub(crate) unsafe fn get_ocaml_const_pos(&self, name: &[u8]) -> Option<UnsafeOcamlPtr> {
if self.consts.has_local_changes() {
None
} else {
self.consts_shm
.get_ocaml(ToplevelSymbolHash::from_byte_string(
file_info::NameType::Const,
name,
))
.filter(|ptr| ptr.is_block())
}
}
pub(crate) unsafe fn get_ocaml_module_pos(&self, name: &[u8]) -> Option<UnsafeOcamlPtr> {
if self.modules.has_local_changes() {
None
} else {
self.modules_shm
.get_ocaml(ToplevelSymbolHash::from_byte_string(
file_info::NameType::Module,
name,
))
.filter(|ptr| ptr.is_block())
}
}
}
impl NamingProvider for NamingTable {
fn get_type_path_and_kind(
&self,
name: pos::TypeName,
) -> Result<Option<(RelativePath, KindOfType)>> {
Ok(self
.get_type_pos(name)?
.map(|(pos, kind)| (pos.path(), kind)))
}
fn get_fun_path(&self, name: pos::FunName) -> Result<Option<RelativePath>> {
Ok(self.get_fun_pos(name)?.map(|pos| pos.path()))
}
fn get_const_path(&self, name: pos::ConstName) -> Result<Option<RelativePath>> {
Ok(self.get_const_pos(name)?.map(|pos| pos.path()))
}
fn get_module_path(&self, name: pos::ModuleName) -> Result<Option<RelativePath>> {
Ok(self.get_module_pos(name)?.map(|pos| pos.path()))
}
fn get_canon_type_name(&self, name: TypeName) -> Result<Option<TypeName>> {
self.get_canon_type_name(name)
}
fn get_canon_fun_name(&self, name: FunName) -> Result<Option<FunName>> {
self.get_canon_fun_name(name)
}
}
impl std::fmt::Debug for NamingTable {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("NamingTable").finish()
}
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[derive(ocamlrep::ToOcamlRep, ocamlrep::FromOcamlRep)]
pub enum Pos {
Full(pos::BPos),
File(NameType, RelativePath),
}
impl Pos {
pub fn path(&self) -> RelativePath {
match self {
Self::Full(pos) => pos.file(),
&Self::File(_, path) => path,
}
}
}
impl From<&file_info::Pos> for Pos {
fn from(pos: &file_info::Pos) -> Self {
match pos {
file_info::Pos::Full(pos) => Self::Full(pos.into()),
file_info::Pos::File(name_type, path) => Self::File(*name_type, (&**path).into()),
}
}
}
impl From<Pos> for file_info::Pos {
fn from(pos: Pos) -> Self {
match pos {
Pos::Full(pos) => Self::Full(pos.into()),
Pos::File(name_type, path) => Self::File(name_type, Arc::new(path.into())),
}
}
}
struct MaybeNamingDb(Mutex<Option<(names::Names, PathBuf)>>);
impl MaybeNamingDb {
fn db_path(&self) -> Option<PathBuf> {
self.0.lock().as_ref().map(|(_, path)| path.clone())
}
fn set_db_path(&self, db_path: PathBuf) -> Result<()> {
let mut lock = self.0.lock();
*lock = Some((names::Names::from_file_readonly(&db_path)?, db_path));
Ok(())
}
fn with_db<T, F>(&self, f: F) -> Result<Option<T>>
where
F: FnOnce(&names::Names) -> Result<Option<T>>,
{
match &*self.0.lock() {
Some((db, _)) => Ok(f(db)?),
None => Ok(None),
}
}
}
impl std::fmt::Debug for MaybeNamingDb {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("MaybeNamingDb").finish()
}
}
#[derive(Clone, Debug)]
struct TypeDb(Arc<MaybeNamingDb>);
impl ReadonlyStore<ToplevelSymbolHash, (Pos, KindOfType)> for TypeDb {
fn get(&self, key: ToplevelSymbolHash) -> Result<Option<(Pos, KindOfType)>> {
self.0.with_db(|db| {
Ok(db.get_filename(key)?.and_then(|(path, name_type)| {
let kind = KindOfType::try_from(name_type).ok()?;
Some((Pos::File(name_type, (&path).into()), kind))
}))
})
}
}
impl ReadonlyStore<ToplevelCanonSymbolHash, TypeName> for TypeDb {
fn contains_key(&self, key: ToplevelCanonSymbolHash) -> Result<bool> {
Ok(self
.0
.with_db(|db| db.get_type_name_case_insensitive(key))?
.is_some())
}
fn get(&self, key: ToplevelCanonSymbolHash) -> Result<Option<TypeName>> {
self.0
.with_db(|db| Ok(db.get_type_name_case_insensitive(key)?.map(TypeName::new)))
}
}
#[derive(Clone, Debug)]
struct FunDb(Arc<MaybeNamingDb>);
impl ReadonlyStore<ToplevelSymbolHash, Pos> for FunDb {
fn contains_key(&self, key: ToplevelSymbolHash) -> Result<bool> {
Ok(self
.0
.with_db(|db| db.get_path_by_symbol_hash(key))?
.is_some())
}
fn get(&self, key: ToplevelSymbolHash) -> Result<Option<Pos>> {
self.0.with_db(|db| {
Ok(db
.get_path_by_symbol_hash(key)?
.map(|path| Pos::File(NameType::Fun, (&path).into())))
})
}
}
impl ReadonlyStore<ToplevelCanonSymbolHash, FunName> for FunDb {
fn contains_key(&self, key: ToplevelCanonSymbolHash) -> Result<bool> {
Ok(self
.0
.with_db(|db| db.get_fun_name_case_insensitive(key))?
.is_some())
}
fn get(&self, key: ToplevelCanonSymbolHash) -> Result<Option<FunName>> {
self.0
.with_db(|db| Ok(db.get_fun_name_case_insensitive(key)?.map(FunName::new)))
}
}
#[derive(Clone, Debug)]
struct ConstDb(Arc<MaybeNamingDb>);
impl ReadonlyStore<ToplevelSymbolHash, Pos> for ConstDb {
fn contains_key(&self, key: ToplevelSymbolHash) -> Result<bool> {
Ok(self
.0
.with_db(|db| db.get_path_by_symbol_hash(key))?
.is_some())
}
fn get(&self, key: ToplevelSymbolHash) -> Result<Option<Pos>> {
self.0.with_db(|db| {
Ok(db
.get_path_by_symbol_hash(key)?
.map(|path| Pos::File(NameType::Const, (&path).into())))
})
}
}
#[derive(Clone, Debug)]
struct ModuleDb(Arc<MaybeNamingDb>);
impl ReadonlyStore<ToplevelSymbolHash, Pos> for ModuleDb {
fn contains_key(&self, key: ToplevelSymbolHash) -> Result<bool> {
Ok(self
.0
.with_db(|db| db.get_path_by_symbol_hash(key))?
.is_some())
}
fn get(&self, key: ToplevelSymbolHash) -> Result<Option<Pos>> {
self.0.with_db(|db| {
Ok(db
.get_path_by_symbol_hash(key)?
.map(|path| Pos::File(NameType::Module, (&path).into())))
})
}
}
mod reverse_naming_table {
use std::hash::Hash;
use std::sync::Arc;
use anyhow::Result;
use datastore::ChangesStore;
use datastore::DeltaStore;
use datastore::ReadonlyStore;
use hh24_types::ToplevelCanonSymbolHash;
use hh24_types::ToplevelSymbolHash;
use serde::de::DeserializeOwned;
use serde::Serialize;
use shm_store::OcamlShmStore;
use shm_store::ShmStore;
/// In-memory delta for symbols which support a canon-name lookup API (types
/// and funs).
pub struct ReverseNamingTable<K, P> {
positions: ChangesStore<ToplevelSymbolHash, P>,
positions_shm: Arc<OcamlShmStore<ToplevelSymbolHash, Option<P>>>,
canon_names: ChangesStore<ToplevelCanonSymbolHash, K>,
}
impl<K, P> ReverseNamingTable<K, P>
where
K: Copy + Hash + Eq + Send + Sync + 'static + Serialize + DeserializeOwned,
K: Into<ToplevelSymbolHash> + Into<ToplevelCanonSymbolHash>,
P: Clone + Send + Sync + 'static + Serialize + DeserializeOwned,
P: ocamlrep::ToOcamlRep + ocamlrep::FromOcamlRep,
{
pub fn new<F>(
fallback: Arc<F>,
pos_prefix: &'static str,
canon_prefix: &'static str,
) -> Self
where
F: ReadonlyStore<ToplevelSymbolHash, P>
+ ReadonlyStore<ToplevelCanonSymbolHash, K>
+ 'static,
{
let positions_shm = Arc::new(OcamlShmStore::new(
pos_prefix,
shm_store::Evictability::NonEvictable,
shm_store::Compression::None,
));
Self {
positions: ChangesStore::new(Arc::new(DeltaStore::new(
Arc::clone(&positions_shm) as _,
Arc::clone(&fallback) as _,
))),
positions_shm,
canon_names: ChangesStore::new(Arc::new(DeltaStore::new(
Arc::new(ShmStore::new(
canon_prefix,
shm_store::Evictability::NonEvictable,
shm_store::Compression::None,
)),
fallback,
))),
}
}
pub fn insert(&self, name: K, pos: P) -> Result<()> {
self.positions.insert(name.into(), pos)?;
self.canon_names.insert(name.into(), name)?;
Ok(())
}
pub fn get_pos(&self, name: K) -> Result<Option<P>> {
self.positions.get(name.into())
}
pub fn get_pos_by_hash(&self, name: ToplevelSymbolHash) -> Result<Option<P>> {
self.positions.get(name)
}
pub fn get_canon_name(&self, name: K) -> Result<Option<K>> {
self.canon_names.get(name.into())
}
pub fn push_local_changes(&self) {
self.canon_names.push_local_changes();
self.positions.push_local_changes();
}
pub fn pop_local_changes(&self) {
self.canon_names.pop_local_changes();
self.positions.pop_local_changes();
}
pub unsafe fn get_ocaml_pos_by_hash(
&self,
hash: ToplevelSymbolHash,
) -> Option<ocamlrep::ptr::UnsafeOcamlPtr> {
if self.positions.has_local_changes() {
None
} else {
self.positions_shm.get_ocaml(hash)
}
}
pub fn remove_batch<I: Iterator<Item = K> + Clone>(&self, keys: I) -> Result<()> {
self.canon_names
.remove_batch(&mut keys.clone().map(Into::into))?;
self.positions.remove_batch(&mut keys.map(Into::into))?;
Ok(())
}
}
} |
Rust | hhvm/hphp/hack/src/providers/hackrs_provider_backend/test_naming_table.rs | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use std::path::PathBuf;
use anyhow::Result;
use hh24_types::ToplevelSymbolHash;
use maplit::btreemap;
use oxidized::naming_types;
use pos::ConstName;
use pos::FunName;
use pos::Prefix;
use pos::RelativePath;
use pos::TypeName;
use rpds::HashTrieSet;
use super::NamingTable;
// stub for hh_shared.c function called by shm_store crate
#[no_mangle]
extern "C" fn hh_log_level() -> ocamlrep::Value<'static> {
ocamlrep::Value::int(0)
}
fn setup(files: std::collections::BTreeMap<&str, &str>) -> (hh24_test::TestRepo, NamingTable) {
let repo = hh24_test::TestRepo::new(&files).unwrap();
let db_path = repo.path().join("names.sql");
hh24_test::create_naming_table(&db_path, &files).unwrap();
let naming_table = NamingTable::new(Some(db_path)).unwrap();
shm_init();
(repo, naming_table)
}
fn shm_init() {
let mem_heap_size = 2 * 1024 * 1024 * 1024;
let mmap_ptr = unsafe {
libc::mmap(
std::ptr::null_mut(),
mem_heap_size,
libc::PROT_READ | libc::PROT_WRITE,
libc::MAP_SHARED | libc::MAP_ANONYMOUS,
-1,
0,
)
};
assert_ne!(mmap_ptr, libc::MAP_FAILED);
shmffi::shmffi_init(mmap_ptr, mem_heap_size, (mem_heap_size / 2) as isize);
}
fn make_dep_from_typename(typename: &str) -> deps_rust::Dep {
deps_rust::Dep::new(ToplevelSymbolHash::from_type(typename).as_u64())
}
fn make_relative_path_from_str(test_path: &str) -> RelativePath {
RelativePath::new(Prefix::Root, PathBuf::from(test_path))
}
#[test]
fn type_test() -> Result<()> {
let (_repo, naming_table) = setup(btreemap! {
"a.php" => "class A extends B {}",
"b.php" => "class B {}"
});
let a_type = TypeName::new(r#"\A"#);
let a_relative_path = make_relative_path_from_str("a.php");
// Retrieve a typename
let (pos, kindof) = naming_table.get_type_pos(a_type).unwrap().unwrap();
let rp: RelativePath = pos.path();
assert_eq!(rp, a_relative_path);
assert_eq!(kindof, naming_types::KindOfType::TClass);
// Remove a typename
naming_table.remove_type_batch(&[a_type])?;
assert_eq!(naming_table.get_type_pos(a_type).unwrap(), None);
// Add a typename
naming_table.add_type(
a_type,
&(
oxidized::file_info::Pos::File(
oxidized::file_info::NameType::Class,
std::sync::Arc::new(a_relative_path.into()),
),
naming_types::KindOfType::TClass,
),
)?;
let (pos, kindof) = naming_table.get_type_pos(a_type).unwrap().unwrap();
let rp: RelativePath = pos.path();
assert_eq!(rp, a_relative_path);
assert_eq!(kindof, naming_types::KindOfType::TClass);
// Get name from its lowercase version
assert_eq!(
naming_table
.get_canon_type_name(TypeName::new(r#"\a"#))
.unwrap()
.unwrap(),
a_type
);
Ok(())
}
#[test]
fn fun_test() -> Result<()> {
let (_repo, naming_table) = setup(btreemap! {
"a.php" => "function A(): void { b(); }",
"b.php" => "function b(): void { A(); }",
});
let a_fun = FunName::new(r#"\A"#);
let a_relative_path = make_relative_path_from_str("a.php");
// Retrieve a fun
let pos = naming_table.get_fun_pos(a_fun).unwrap().unwrap();
let rp: RelativePath = pos.path();
assert_eq!(rp, a_relative_path);
// Remove a fun
naming_table.remove_fun_batch(&[a_fun])?;
assert_eq!(naming_table.get_fun_pos(a_fun).unwrap(), None);
// Add a fun
naming_table.add_fun(
a_fun,
&oxidized::file_info::Pos::File(
oxidized::file_info::NameType::Fun,
std::sync::Arc::new(a_relative_path.into()),
),
)?;
let pos = naming_table.get_fun_pos(a_fun).unwrap().unwrap();
let rp: RelativePath = pos.path();
assert_eq!(rp, a_relative_path);
// Get canon name from its lowercase version
assert_eq!(
naming_table
.get_canon_fun_name(FunName::new(r#"\a"#))
.unwrap()
.unwrap(),
a_fun
);
Ok(())
}
#[test]
fn const_test() -> Result<()> {
let (_repo, naming_table) = setup(btreemap! {
"a.php" => "const int A = 123;",
"lowercase_a.php" => "const int a = 321;",
});
let a_const = ConstName::new(r#"\A"#);
let a_relative_path = make_relative_path_from_str("a.php");
// Retrieve a const
let pos = naming_table.get_const_pos(a_const).unwrap().unwrap();
let rp: RelativePath = pos.path();
assert_eq!(rp, a_relative_path);
// Remove a const
naming_table.remove_const_batch(&[a_const])?;
assert_eq!(naming_table.get_const_pos(a_const).unwrap(), None);
// Add a const
naming_table.add_const(
a_const,
&oxidized::file_info::Pos::File(
oxidized::file_info::NameType::Const,
std::sync::Arc::new(a_relative_path.into()),
),
)?;
let pos = naming_table.get_const_pos(a_const).unwrap().unwrap();
let rp: RelativePath = pos.path();
assert_eq!(rp, a_relative_path);
Ok(())
}
#[test]
fn get_filenames_by_hash_test() -> Result<()> {
let (_repo, naming_table) = setup(btreemap! {
"a.php" => "class A extends B {}",
"b.php" => "class B {}"
});
let a_type = make_dep_from_typename(r#"\A"#);
let b_type = make_dep_from_typename(r#"\B"#);
let a_relative_path = make_relative_path_from_str("a.php");
let b_relative_path = make_relative_path_from_str("b.php");
let depset = HashTrieSet::new();
let depset = depset.insert(a_type);
let dep_paths = naming_table
.get_filenames_by_hash(&deps_rust::DepSet::from(depset))
.unwrap();
assert!(dep_paths.contains(&a_relative_path));
assert!(!dep_paths.contains(&b_relative_path));
let depset = HashTrieSet::new();
let depset = depset.insert(a_type);
let depset = depset.insert(b_type);
let dep_paths = naming_table
.get_filenames_by_hash(&deps_rust::DepSet::from(depset))
.unwrap();
assert!(dep_paths.contains(&a_relative_path));
assert!(dep_paths.contains(&b_relative_path));
let depset = HashTrieSet::new();
let dep_paths = naming_table
.get_filenames_by_hash(&deps_rust::DepSet::from(depset))
.unwrap();
assert!(dep_paths.is_empty());
let depset = HashTrieSet::new();
let depset = depset.insert(make_dep_from_typename(r#"\C"#));
let dep_paths = naming_table
.get_filenames_by_hash(&deps_rust::DepSet::from(depset))
.unwrap();
assert!(dep_paths.is_empty());
Ok(())
} |
hhvm/hphp/hack/src/refactor_sd/dune | (library
(name refactor_sd)
(wrapped false)
(flags (:standard -linkall))
(modules
refactor_sd
Refactor_sd_env
refactor_sd_options
refactor_sd_pretty_printer
refactor_sd_walker
refactor_sd_solver
refactor_sd_types)
(libraries
core_kernel
provider_context
aast_names_utils
relative_path
tast_env
typing_defs
typing_env_types)
(preprocess
(pps visitors.ppx ppx_deriving.std))) |
|
OCaml | hhvm/hphp/hack/src/refactor_sd/refactor_sd.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 Refactor_sd_types
open Refactor_sd_pretty_printer
module T = Tast
module Solver = Refactor_sd_solver
module Walker = Refactor_sd_walker
exception Refactor_sd_exn = Refactor_sd_exn
let add_ns name =
if Char.equal name.[0] '\\' then
name
else
"\\" ^ name
let do_
(upcasted_id : string)
(options : options)
(ctx : Provider_context.t)
(tast : T.program) =
let empty_typing_env = Tast_env.tast_env_as_typing_env (Tast_env.empty ctx) in
let upcasted_id = add_ns upcasted_id in
let upcasted_info = { element_name = upcasted_id } in
match options.analysis_mode with
| FlagTargets -> ()
| DumpConstraints ->
let print_function_constraints
(id : string) (constraints : constraint_ list) : unit =
Format.printf "Constraints for %s:\n" id;
constraints
|> List.map ~f:(show_constraint_ empty_typing_env)
|> List.sort ~compare:String.compare
|> List.iter ~f:(Format.printf "%s\n");
Format.printf "\n"
in
Walker.program upcasted_info ctx tast
|> SMap.iter print_function_constraints
| SimplifyConstraints ->
let print_callable_summary (id : string) (results : refactor_sd_result list)
: unit =
Format.printf "Summary for %s:\n" id;
List.iter results ~f:(fun result ->
Format.printf "%s\n" (show_refactor_sd_result empty_typing_env result))
in
let process_callable id constraints =
Solver.simplify empty_typing_env constraints |> print_callable_summary id
in
Walker.program upcasted_info ctx tast |> SMap.iter process_callable
| SolveConstraints -> ()
let callable = Walker.callable
let simplify = Solver.simplify
let show_refactor_sd_result = show_refactor_sd_result
let contains_upcast = function
| Exists_Upcast _ -> true
| _ -> false
let show_refactor_sd_result = show_refactor_sd_result |
OCaml Interface | hhvm/hphp/hack/src/refactor_sd/refactor_sd.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.
*
*)
(** A program analysis to find locations of upcasts to dynamic type *)
open Refactor_sd_types
exception Refactor_sd_exn of string
val do_ : string -> options -> Provider_context.t -> Tast.program -> unit
val simplify :
Typing_env_types.env -> constraint_ list -> refactor_sd_result list
val callable :
element_info ->
Tast_env.t ->
Tast.fun_param list ->
Tast.func_body ->
constraint_ list
(** Relationship with shape_analysis: is_shape_like_dict *)
val contains_upcast : refactor_sd_result -> bool
(** Relationship with shape_analysis: show_shape_result *)
val show_refactor_sd_result :
Typing_env_types.env -> refactor_sd_result -> string |
OCaml | hhvm/hphp/hack/src/refactor_sd/refactor_sd_env.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 Refactor_sd_types
module LMap = Local_id.Map
module Cont = Typing_continuations
let var_counter : int ref = ref 0
let fresh_var () : entity_ =
var_counter := !var_counter + 1;
Variable !var_counter
let union_continuation_at_lid (entity1 : entity) (entity2 : entity) :
constraint_ list * entity =
match (entity1, entity2) with
| (Some entity1_, Some entity2_) ->
let var = fresh_var () in
let constraints = [Subset (entity1_, var); Subset (entity2_, var)] in
(constraints, Some var)
| (entity, None)
| (None, entity) ->
([], entity)
let union_continuation (constraints : constraint_ list) cont1 cont2 =
let union_continuation_at_lid constraints _lid entity1_opt entity2_opt :
constraint_ list * entity option =
match (entity1_opt, entity2_opt) with
| (Some entity1, Some entity2) ->
let (new_constraints, entity) =
union_continuation_at_lid entity1 entity2
in
(new_constraints @ constraints, Some entity)
| (Some entity, None)
| (None, Some entity) ->
(constraints, Some entity)
| (None, None) -> (constraints, None)
in
let (constraints, cont) =
LMap.merge_env constraints cont1 cont2 ~combine:union_continuation_at_lid
in
(constraints, cont)
module LEnv = struct
type t = lenv
let init bindings : t = Cont.Map.add Cont.Next bindings Cont.Map.empty
let get_local_in_continuation lenv cont lid : entity =
let open Option.Monad_infix in
lenv |> Cont.Map.find_opt cont >>= LMap.find_opt lid |> Option.join
let get_local lenv : LMap.key -> entity =
get_local_in_continuation lenv Cont.Next
let set_local_in_continuation lenv cont lid entity : t =
let update_cont = function
| None -> None
| Some lenv_per_cont -> Some (LMap.add lid entity lenv_per_cont)
in
Cont.Map.update cont update_cont lenv
let set_local lenv lid entity : t =
set_local_in_continuation lenv Cont.Next lid entity
let drop_cont lenv cont : t = Cont.Map.remove cont lenv
let drop_conts lenv conts : t = List.fold ~f:drop_cont ~init:lenv conts
let replace_cont lenv cont_key cont_opt : t =
match cont_opt with
| None -> drop_cont lenv cont_key
| Some cont -> Cont.Map.add cont_key cont lenv
let restore_cont_from lenv ~from cont_key : t =
let ctxopt = Cont.Map.find_opt cont_key from in
replace_cont lenv cont_key ctxopt
let restore_conts_from lenv ~from conts : t =
List.fold ~f:(restore_cont_from ~from) ~init:lenv conts
let union (lenv1 : t) (lenv2 : t) : constraint_ list * t =
let combine constraints _ cont1 cont2 =
let (constraints, cont) = union_continuation constraints cont1 cont2 in
(constraints, Some cont)
in
Cont.Map.union_env [] lenv1 lenv2 ~combine
end
let init tast_env constraints bindings =
{ constraints; lenv = LEnv.init bindings; tast_env }
let add_constraint env constraint_ =
{ env with constraints = constraint_ :: env.constraints }
let reset_constraints env = { env with constraints = [] }
let get_local env = LEnv.get_local env.lenv
let set_local env lid entity =
let lenv = LEnv.set_local env.lenv lid entity in
{ env with lenv }
let union (parent_env : env) (env1 : env) (env2 : env) : env =
let (points_to_constraints, lenv) = LEnv.union env1.lenv env2.lenv in
let constraints =
points_to_constraints
@ env1.constraints
@ env2.constraints
@ parent_env.constraints
in
{ parent_env with lenv; constraints }
let drop_cont env cont =
let lenv = LEnv.drop_cont env.lenv cont in
{ env with lenv }
let drop_conts env conts =
let lenv = LEnv.drop_conts env.lenv conts in
{ env with lenv }
let replace_cont env cont_key cont_opt =
let lenv = LEnv.replace_cont env.lenv cont_key cont_opt in
{ env with lenv }
let restore_conts_from env ~from conts : env =
let lenv = LEnv.restore_conts_from env.lenv ~from conts in
{ env with lenv }
let stash_and_do env conts f : env =
let parent_locals = env.lenv in
let env = drop_conts env conts in
let env = f env in
restore_conts_from env ~from:parent_locals conts
let union_cont_opt (constraints : constraint_ list) cont_opt1 cont_opt2 =
match (cont_opt1, cont_opt2) with
| (None, opt)
| (opt, None) ->
(constraints, opt)
| (Some cont1, Some cont2) ->
let (constraints, cont) = union_continuation constraints cont1 cont2 in
(constraints, Some cont)
(* Union a list of continuations *)
let union_conts (env : env) lenv cont_keys =
let union_two (constraints, cont_opt1) cont_key =
let cont_opt2 = Cont.Map.find_opt cont_key lenv in
union_cont_opt constraints cont_opt1 cont_opt2
in
let (constraints, cont_opt) =
List.fold cont_keys ~f:union_two ~init:(env.constraints, None)
in
let env = { env with constraints } in
(env, cont_opt)
(* Union a list of source continuations and store the result in a
* destination continuation. *)
let union_conts_and_update (env : env) ~from_conts ~to_cont =
let lenv = env.lenv in
let (env, unioned_cont) = union_conts env lenv from_conts in
replace_cont env to_cont unioned_cont
let update_next_from_conts env from_conts =
union_conts_and_update env ~from_conts ~to_cont:Cont.Next
let save_and_merge_next_in_cont env to_cont =
union_conts_and_update env ~from_conts:[Cont.Next; to_cont] ~to_cont
let move_and_merge_next_in_cont env cont_key =
let env = save_and_merge_next_in_cont env cont_key in
drop_cont env Cont.Next
let loop_continuation cont_key ~env_before_iteration ~env_after_iteration =
let cont_before_iteration_opt =
Cont.Map.find_opt cont_key env_before_iteration.lenv
in
let cont_after_iteration_opt =
Cont.Map.find_opt cont_key env_after_iteration.lenv
in
let new_constraints =
let combine constraints _key entity_before_opt entity_after_opt =
let new_constraints =
match (entity_before_opt, entity_after_opt) with
| (Some (Some entity_before), Some (Some entity_after)) ->
[Subset (entity_after, entity_before)]
| _ -> []
in
let constraints = new_constraints @ constraints in
(constraints, None)
in
match (cont_before_iteration_opt, cont_after_iteration_opt) with
| (Some cont_before_iteration, Some cont_after_iteration) ->
fst
@@ LMap.merge_env [] cont_before_iteration cont_after_iteration ~combine
| _ -> []
in
{
env_after_iteration with
constraints = new_constraints @ env_after_iteration.constraints;
} |
OCaml Interface | hhvm/hphp/hack/src/refactor_sd/refactor_sd_env.mli | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(*
* 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 Refactor_sd_types
module LMap = Local_id.Map
(** Generates a fresh variable entity *)
val fresh_var : unit -> entity_
(** Initialise shape analysis environment *)
val init : Tast_env.env -> constraint_ list -> entity LMap.t -> env
(** Record a shape analysis constraint *)
val add_constraint : env -> constraint_ -> env
(** Ignore all existing constraints. The intention of this is to prevent
unnecessary duplication of constraints when multiple environments need to
be merged. *)
val reset_constraints : env -> env
(** Find an entity that a local variable points to *)
val get_local : env -> Local_id.t -> entity
(** Set an entity to a local variable *)
val set_local : env -> Local_id.t -> entity -> env
(** The first environment is the parent environment. The others are combined.
This is useful in branching code. *)
val union : env -> env -> env -> env
val stash_and_do : env -> Typing_continuations.t list -> (env -> env) -> env
val update_next_from_conts : env -> Typing_continuations.t list -> env
val drop_cont : env -> Typing_continuations.t -> env
val restore_conts_from : env -> from:lenv -> Typing_continuations.t list -> env
val save_and_merge_next_in_cont : env -> Typing_continuations.t -> env
val move_and_merge_next_in_cont : env -> Typing_continuations.t -> env
val loop_continuation :
Typing_continuations.t ->
env_before_iteration:env ->
env_after_iteration:env ->
env |
OCaml | hhvm/hphp/hack/src/refactor_sd/refactor_sd_options.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 Refactor_sd_types
let parse_analysis_mode = function
| "flag" -> Some FlagTargets
| "dump" -> Some DumpConstraints
| "simplify" -> Some SimplifyConstraints
| "solve" -> Some SolveConstraints
| _ -> None
let parse_refactor_mode = function
| "Class" -> Some Class
| "Function" -> Some Function
| _ -> None
let mk ~analysis_mode ~refactor_mode = { analysis_mode; refactor_mode } |
OCaml Interface | hhvm/hphp/hack/src/refactor_sd/refactor_sd_options.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.
*
*)
open Refactor_sd_types
val parse_analysis_mode : string -> analysis_mode option
val parse_refactor_mode : string -> refactor_mode option
val mk :
analysis_mode:Refactor_sd_types.analysis_mode ->
refactor_mode:Refactor_sd_types.refactor_mode ->
options |
OCaml | hhvm/hphp/hack/src/refactor_sd/refactor_sd_pretty_printer.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 Refactor_sd_types
let show_entity = function
| Literal pos -> Format.asprintf "%a" Pos.pp pos
| Variable var -> Format.sprintf "?%d" var
let show_constraint_ _env = function
| Introduction pos -> Format.asprintf "Introduction at %a" Pos.pp pos
| Upcast (ent, _) -> Format.asprintf "Upcast at %s" (show_entity ent)
| Subset (sub, sup) -> show_entity sub ^ " ⊆ " ^ show_entity sup
| Called pos -> Format.asprintf "Function call at %a" Pos.pp pos
let show_refactor_sd_result _env = function
| Exists_Upcast pos -> Format.asprintf "Upcast exists at %a" Pos.pp pos
| No_Upcast -> Format.asprintf "No upcast" |
OCaml Interface | hhvm/hphp/hack/src/refactor_sd/refactor_sd_pretty_printer.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.
*
*)
open Refactor_sd_types
val show_constraint_ : Typing_env_types.env -> constraint_ -> string
val show_refactor_sd_result :
Typing_env_types.env -> refactor_sd_result -> string |
OCaml | hhvm/hphp/hack/src/refactor_sd/refactor_sd_solver.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 Refactor_sd_types
type constraints = {
introductions: Pos.t list;
subsets: (entity_ * entity_) list;
upcasts: (entity_ * Pos.t) list;
calleds: Pos.t list;
}
let constraints_init =
{ introductions = []; subsets = []; upcasts = []; calleds = [] }
let rec transitive_closure (set : PointsToSet.t) : PointsToSet.t =
let immediate_consequence (x, y) set =
let add (y', z) set =
if equal_entity_ y y' then
PointsToSet.add (x, z) set
else
set
in
PointsToSet.fold add set set
in
let new_set = PointsToSet.fold immediate_consequence set set in
if PointsToSet.cardinal new_set = PointsToSet.cardinal set then
set
else
transitive_closure new_set
let find_pointers (introductions : Pos.t list) (set : PointsToSet.t) :
PointsToSet.t =
let check_if_pointer (has_pointer_set : PointsToSet.t) (pointer_pos : Pos.t) =
let contains_pos ((sub, _) : entity_ * entity_) =
match sub with
| Literal pos -> Pos.compare pointer_pos pos = 0
| _ -> false
in
let new_set = PointsToSet.filter contains_pos set in
PointsToSet.union new_set has_pointer_set
in
List.fold introductions ~init:PointsToSet.empty ~f:check_if_pointer
let find_calls (introductions : Pos.t list) (set : PointsToSet.t) :
PointsToSet.t =
let check_if_called (called_set : PointsToSet.t) (called_pos : Pos.t) =
let was_called ((_, sup) : entity_ * entity_) =
match sup with
| Literal pos -> Pos.compare called_pos pos = 0
| _ -> false
in
let new_set = PointsToSet.filter was_called set in
PointsToSet.union new_set called_set
in
List.fold introductions ~init:PointsToSet.empty ~f:check_if_called
let remove_duplicates
(positions : Pos.t list) ((_entity, pos) : entity_ * Pos.t) =
if List.mem positions pos ~equal:(fun pos1 pos2 -> Pos.compare pos1 pos2 = 0)
then
positions
else
pos :: positions
let partition_constraint constraints = function
| Introduction pos ->
{ constraints with introductions = pos :: constraints.introductions }
| Subset (sub, sup) ->
{ constraints with subsets = (sub, sup) :: constraints.subsets }
| Upcast (entity, pos) ->
{ constraints with upcasts = (entity, pos) :: constraints.upcasts }
| Called pos -> { constraints with calleds = pos :: constraints.calleds }
let subset_lookups subsets =
let update entity entity' =
EntityMap.update entity (function
| None -> Some (EntitySet.singleton entity')
| Some set -> Some (EntitySet.add entity' set))
in
let (subset_map, superset_map) =
let update_maps (e, e') (subset_map, superset_map) =
let subset_map = update e' e subset_map in
let superset_map = update e e' superset_map in
(subset_map, superset_map)
in
PointsToSet.fold update_maps subsets (EntityMap.empty, EntityMap.empty)
in
(* Generate lookup functions. This code is different from shape_analysis. *)
let collect map (entity, pos) =
match EntityMap.find_opt entity map with
| Some entities ->
List.map ~f:(fun ent -> (ent, pos)) (EntitySet.elements entities)
| None -> []
in
(collect subset_map, collect superset_map)
let simplify (_env : Typing_env_types.env) (constraints : constraint_ list) :
refactor_sd_result list =
let { introductions; upcasts; subsets; calleds } =
List.fold ~init:constraints_init ~f:partition_constraint constraints
in
let subsets = PointsToSet.of_list subsets |> transitive_closure in
(* Limit upcasts to functions of interest *)
let subsets_pointers = subsets |> find_pointers introductions in
let (collect_subsets_to_pointers, _collect_supersets_to_pointers) =
subset_lookups subsets_pointers
in
let upcasts = upcasts |> List.concat_map ~f:collect_subsets_to_pointers in
(* Limit upcasts to functions that are later called *)
let subsets_calls = subsets |> find_calls calleds in
let (_collect_subsets_to_calls, collect_supersets_to_calls) =
subset_lookups subsets_calls
in
let upcasts = upcasts |> List.concat_map ~f:collect_supersets_to_calls in
(* Remove duplicates. Duplicates occur when reassigning variables or using a mutable collection. *)
let upcast_pos = upcasts |> List.fold ~init:[] ~f:remove_duplicates in
(* Convert to individual upcast results *)
let exists_upcast_results : refactor_sd_result list =
upcast_pos |> List.map ~f:(fun pos -> Exists_Upcast pos)
in
if List.is_empty exists_upcast_results then
[No_Upcast]
else
exists_upcast_results |
OCaml Interface | hhvm/hphp/hack/src/refactor_sd/refactor_sd_solver.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.
*
*)
open Refactor_sd_types
val simplify :
Typing_env_types.env -> constraint_ list -> refactor_sd_result list |
OCaml | hhvm/hphp/hack/src/refactor_sd/refactor_sd_types.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 LMap = Local_id.Map
module KMap = Typing_continuations.Map
exception Refactor_sd_exn of string
type analysis_mode =
| FlagTargets
| DumpConstraints
| SimplifyConstraints
| SolveConstraints [@deriving eq]
type refactor_mode =
| Class
| Function
| Method
type options = {
analysis_mode: analysis_mode;
refactor_mode: refactor_mode;
}
type element_info = { element_name: string }
type entity_ =
| Literal of Pos.t
| Variable of int
[@@deriving eq, ord]
type entity = entity_ option
type constraint_ =
| Introduction of Pos.t
| Upcast of entity_ * Pos.t
| Subset of entity_ * entity_
| Called of Pos.t
type refactor_sd_result =
| Exists_Upcast of Pos.t
| No_Upcast
type lenv = entity LMap.t KMap.t
type env = {
constraints: constraint_ list;
lenv: lenv;
tast_env: Tast_env.t;
}
module PointsToSet = Set.Make (struct
type t = entity_ * entity_
let compare (a, b) (c, d) =
match compare_entity_ a c with
| 0 -> compare_entity_ b d
| x -> x
end)
module EntityMap = Map.Make (struct
type t = entity_
let compare = compare_entity_
end)
module EntitySet = Set.Make (struct
type t = entity_
let compare = compare_entity_
end) |
OCaml Interface | hhvm/hphp/hack/src/refactor_sd/refactor_sd_types.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.
*
*)
module LMap = Local_id.Map
module KMap = Typing_continuations.Map
(** A generic exception for all refactor sound dynamic specific failures
Relationship with shape_analysis: Shape_analysis_exn *)
exception Refactor_sd_exn of string
type analysis_mode =
| FlagTargets
(** Flag all possible targets without performing any analysis *)
| DumpConstraints (** Dump constraints generated by analysing the program *)
| SimplifyConstraints
(** Partially solve key constraints within functions and methods and
report back whether a function is ever upcasted to dynamic. *)
| SolveConstraints
(** Globally solve the key constraints and report back whether a
function is ever upcasted to dynamic *)
type refactor_mode =
| Class (** Locate upcasts of a specific Class *)
| Function (** Locate upcasts of a specific Function *)
| Method (** Locate upcasts of a specific Method *)
type options = {
analysis_mode: analysis_mode;
refactor_mode: refactor_mode;
}
(** Information about the class or function or method of interest, so that we
can limit our reports to the upcasts of that specific element.
Class name is only used if the refactor mode is Method. *)
type element_info = { element_name: string }
type entity_ =
| Literal of Pos.t
| Variable of int
[@@deriving eq, ord]
type entity = entity_ option
(** Relationship with shape_analysis: constraint_ constructors are different *)
type constraint_ =
| Introduction of Pos.t
(** Records introduction of an instance of function pointer *)
| Upcast of entity_ * Pos.t
(** Records existance and position of upcast dynamic *)
| Subset of entity_ * entity_
(** Records that the first entity is assigned to the second *)
| Called of Pos.t
(** Records that the entity_ was a function pointer that was called *)
(** Relationship with shape_analysis: shape_result *)
type refactor_sd_result =
| Exists_Upcast of Pos.t
| No_Upcast
(** Local variable environment. Its values are `entity`, i.e., `entity_
option`, so that we can avoid pattern matching in constraint extraction. *)
type lenv = entity LMap.t KMap.t
type env = {
constraints: constraint_ list; (** Append-only set of constraints *)
lenv: lenv; (** Local variable information *)
tast_env: Tast_env.env;
(** TAST env associated with the definition being analysed *)
}
module PointsToSet : Set.S with type elt = entity_ * entity_
module EntityMap : Map.S with type key = entity_
module EntitySet : Set.S with type elt = entity_ |
OCaml | hhvm/hphp/hack/src/refactor_sd/refactor_sd_walker.ml | (*
* 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.
*
*)
open Hh_prelude
open Refactor_sd_types
module Cont = Typing_continuations
module A = Aast
module T = Tast
module Env = Refactor_sd_env
module Utils = Aast_names_utils
module SN = Naming_special_names
let failwithpos pos msg =
raise @@ Refactor_sd_exn (Format.asprintf "%a: %s" Pos.pp pos msg)
let redirect (env : env) (entity_ : entity_) : env * entity_ =
let var = Env.fresh_var () in
let env = Env.add_constraint env (Subset (entity_, var)) in
(env, var)
let assign (env : env) ((_, pos, lval) : T.expr) (rhs : entity) : env =
match lval with
| A.Lvar (_, lid) -> Env.set_local env lid rhs
| A.Array_get ((vc_type, _, A.Lvar (_, lid)), _) ->
let entity = Env.get_local env lid in
let (_, ty) = Tast_env.expand_type env.tast_env vc_type in
let (_, ty_) = Typing_defs_core.deref ty in
begin
match (entity, ty_) with
| (Some entity_, Typing_defs_core.Tclass ((_, x), _, _))
when String.equal x SN.Collections.cVec
|| String.equal x SN.Collections.cDict ->
(* Handle copy-on-write by creating a variable indirection *)
let (env, var) = redirect env entity_ in
let env =
match rhs with
| Some rhs -> Env.add_constraint env (Subset (rhs, var))
| _ -> env
in
Env.set_local env lid (Some var)
| (Some entity_, Typing_defs_core.Tclass ((_, x), _, _))
when String.equal x SN.Collections.cVector ->
let env =
match rhs with
| Some rhs -> Env.add_constraint env (Subset (rhs, entity_))
| _ -> env
in
Env.set_local env lid (Some entity_)
| (Some _, _) ->
failwithpos pos ("Unsupported lvalue: " ^ Utils.expr_name lval)
| (None, _) ->
(* We might end up here as a result of deadcode, such as a dictionary
assignment after an unconditional break in a loop. In this
situation, it is not meaningful to report a candidate. *)
env
end
| _ -> failwithpos pos ("Unsupported lvalue: " ^ Utils.expr_name lval)
let join (env : env) (then_entity : entity) (else_entity : entity) =
(* Create a join point entity. It is pretty much Option.marge except that
that function doesn't allow threading state (`env`) through *)
match (then_entity, else_entity) with
| (Some then_entity_, Some else_entity_) ->
let var = Env.fresh_var () in
let env = Env.add_constraint env @@ Subset (then_entity_, var) in
let env = Env.add_constraint env @@ Subset (else_entity_, var) in
(env, Some var)
| (None, Some _) -> (env, else_entity)
| (_, _) -> (env, then_entity)
let rec expr_
(upcasted_info : element_info) (env : env) ((_ty, pos, e) : T.expr) :
env * entity =
match e with
| A.Int _
| A.Float _
| A.String _
| A.Null
| A.True
| A.False ->
(env, None)
| A.Id _ ->
(* Until interprocedural analaysis has been implemented, this is all incomplete. *)
(env, None)
| A.Lvar (_, lid) ->
let entity = Env.get_local env lid in
(env, entity)
| A.Unop
( ( Ast_defs.Utild | Ast_defs.Unot | Ast_defs.Uplus | Ast_defs.Uminus
| Ast_defs.Uincr | Ast_defs.Udecr | Ast_defs.Upincr | Ast_defs.Updecr
| Ast_defs.Usilence ),
e ) ->
(* unary operations won't return function pointrs, so we discard the entity. *)
let (env, _) = expr_ upcasted_info env e in
(env, None)
| A.(Binop { bop = Ast_defs.Eq None; lhs = e1; rhs = e2 }) ->
let (env, entity_rhs) = expr_ upcasted_info env e2 in
let env = assign env e1 entity_rhs in
(env, None)
| A.(Binop { bop = Ast_defs.QuestionQuestion; lhs = e1; rhs = e2 }) ->
let (env, entity1) = expr_ upcasted_info env e1 in
let (env, entity2) = expr_ upcasted_info env e2 in
join env entity1 entity2
| A.(
Binop
{
bop = Ast_defs.Eq (Some Ast_defs.QuestionQuestion);
lhs = e1;
rhs = e2;
}) ->
let (env, entity1) = expr_ upcasted_info env e1 in
let (env, entity2) = expr_ upcasted_info env e2 in
let (env, entity_rhs) = join env entity1 entity2 in
let env = assign env e1 entity_rhs in
(env, None)
| A.(
Binop
{
bop =
( Ast_defs.Plus | Ast_defs.Minus | Ast_defs.Star | Ast_defs.Slash
| Ast_defs.Eqeq | Ast_defs.Eqeqeq | Ast_defs.Starstar
| Ast_defs.Diff | Ast_defs.Diff2 | Ast_defs.Ampamp | Ast_defs.Barbar
| Ast_defs.Lt | Ast_defs.Lte | Ast_defs.Gt | Ast_defs.Gte
| Ast_defs.Dot | Ast_defs.Amp | Ast_defs.Bar | Ast_defs.Ltlt
| Ast_defs.Gtgt | Ast_defs.Percent | Ast_defs.Xor | Ast_defs.Cmp );
lhs = e1;
rhs = e2;
}) ->
(* most binary operations won't return function pointers, so we discard the entity. *)
let (env, _) = expr_ upcasted_info env e1 in
let (env, _) = expr_ upcasted_info env e2 in
(env, None)
| A.KeyValCollection ((_, kvc_kind), _, field_list) -> begin
match kvc_kind with
| A.Dict ->
let var = Env.fresh_var () in
let handle_init (env : env) ((_e_key, e_val) : T.expr * T.expr) =
let (env, entity_rhs) = expr_ upcasted_info env e_val in
match entity_rhs with
| Some entity_rhs_ -> Env.add_constraint env (Subset (entity_rhs_, var))
| _ -> env
in
let env = List.fold ~init:env ~f:handle_init field_list in
(env, Some var)
| _ -> failwithpos pos ("Unsupported expression: " ^ Utils.expr_name e)
end
| A.ValCollection ((_, vc_kind), _, expr_list) -> begin
match vc_kind with
| A.Vector
| A.Vec ->
let var = Env.fresh_var () in
let handle_init (env : env) (e_inner : T.expr) =
let (env, entity_rhs) = expr_ upcasted_info env e_inner in
match entity_rhs with
| Some entity_rhs_ -> Env.add_constraint env (Subset (entity_rhs_, var))
| _ -> env
in
let env = List.fold ~init:env ~f:handle_init expr_list in
(env, Some var)
| _ -> failwithpos pos ("Unsupported expression: " ^ Utils.expr_name e)
end
| A.Array_get (((_, _, A.Lvar (_, _lid)) as base), Some ix) ->
let (env, entity_exp) = expr_ upcasted_info env base in
let (env, _entity_ix) = expr_ upcasted_info env ix in
(env, entity_exp)
| A.Upcast (e, _) ->
let (env, entity) = expr_ upcasted_info env e in
let env =
match entity with
| Some entity -> Env.add_constraint env (Upcast (entity, pos))
| None -> env
in
(env, entity)
| A.(Call { func; args; _ }) ->
(* Until interprocedural analaysis has been implemented, this is all incomplete. *)
let (env, entity) = expr_ upcasted_info env func in
let handle_args env (_, arg) =
let (env, _) = expr_ upcasted_info env arg in
env
in
let env = List.fold ~init:env args ~f:handle_args in
let env =
match entity with
| Some entity ->
let location = Literal pos in
let env = Env.add_constraint env (Subset (entity, location)) in
Env.add_constraint env (Called pos)
| None -> env
in
(env, None)
| A.Obj_get (e_obj, e_meth, _, _) ->
let (env, entity_obj) = expr_ upcasted_info env e_obj in
let (env, _entity_meth) = expr_ upcasted_info env e_meth in
begin
match entity_obj with
| Some _entity ->
let location = Literal pos in
let env = Env.add_constraint env (Subset (_entity, location)) in
let env = Env.add_constraint env (Called pos) in
(env, entity_obj)
| None -> (env, None)
end
| Aast.FunctionPointer (Aast.FP_id (_, id), _) ->
if String.equal upcasted_info.element_name id then
let entity_ = Literal pos in
let env = Env.add_constraint env (Introduction pos) in
(* Handle copy-on-write by creating a variable indirection *)
let (env, var) = redirect env entity_ in
(env, Some var)
else
(env, None)
| A.New ((_, _, A.CI (_, id)), _, expr_list, e, _) ->
if String.equal upcasted_info.element_name id then
let handle_init (env : env) (e : T.expr) =
let (env, _entity_rhs) = expr_ upcasted_info env e in
env
in
let env = List.fold ~init:env ~f:handle_init expr_list in
let env =
match e with
| Some e -> fst (expr_ upcasted_info env e)
| None -> env
in
let entity_ = Literal pos in
let env = Env.add_constraint env (Introduction pos) in
(* Handle copy-on-write by creating a variable indirection *)
let (env, var) = redirect env entity_ in
(env, Some var)
else
(env, None)
| A.Class_const ((_, _, A.CI (_, id)), (_, method_id)) ->
let equals_method_id = String.equal method_id "class" in
if String.equal upcasted_info.element_name id && equals_method_id then
let entity_ = Literal pos in
let env = Env.add_constraint env (Introduction pos) in
(* Handle copy-on-write by creating a variable indirection *)
let (env, var) = redirect env entity_ in
(env, Some var)
else
(env, None)
(* Eventually, we should be able to track method pointers inside a class, i.e.
also track the following expression with A.CIexpr (_, _, This). *)
| A.Class_const ((_, _, A.CIexpr e_obj), _) -> expr_ upcasted_info env e_obj
| A.Eif (cond, Some then_expr, else_expr) ->
let (parent_env, _cond_entity) = expr_ upcasted_info env cond in
let base_env = Env.reset_constraints parent_env in
let (then_env, then_entity) = expr_ upcasted_info base_env then_expr in
let (else_env, else_entity) = expr_ upcasted_info base_env else_expr in
let env = Env.union parent_env then_env else_env in
join env then_entity else_entity
| A.Eif (cond, None, else_expr) ->
let (env, cond_entity) = expr_ upcasted_info env cond in
let (env, else_entity) = expr_ upcasted_info env else_expr in
join env cond_entity else_entity
| A.Await e -> expr_ upcasted_info env e
| A.As (e, _ty, _) -> expr_ upcasted_info env e
| A.Is (e, _ty) ->
(* `is` expressions always evaluate to bools, so we discard the entity. *)
let (env, _) = expr_ upcasted_info env e in
(env, None)
| _ -> failwithpos pos ("Unsupported expression: " ^ Utils.expr_name e)
let expr (upcasted_info : element_info) (env : env) (e : T.expr) : env =
expr_ upcasted_info env e |> fst
let rec switch
(upcasted_info : element_info)
(parent_locals : lenv)
(env : env)
(cases : ('ex, 'en) A.case list)
(dfl : ('ex, 'en) A.default_case option) : env =
let initialize_next_cont env =
let env = Env.restore_conts_from env ~from:parent_locals [Cont.Next] in
let env = Env.update_next_from_conts env [Cont.Next; Cont.Fallthrough] in
Env.drop_cont env Cont.Fallthrough
in
let handle_case env (e, b) =
let env = initialize_next_cont env in
let env = expr upcasted_info env e in
block upcasted_info env b
in
let handle_default_case env dfl =
dfl
|> Option.fold ~init:env ~f:(fun env (_, b) ->
let env = initialize_next_cont env in
block upcasted_info env b)
in
let env = List.fold ~init:env ~f:handle_case cases in
let env = handle_default_case env dfl in
env
and stmt (upcasted_info : element_info) (env : env) ((pos, stmt) : T.stmt) : env
=
match stmt with
| A.Expr e -> expr upcasted_info env e
| A.Return None -> env
| A.Return (Some e) ->
let (env, _expr) = expr_ upcasted_info env e in
env
| A.If (cond, then_bl, else_bl) ->
let parent_env = expr upcasted_info env cond in
let base_env = Env.reset_constraints parent_env in
let then_env = block upcasted_info base_env then_bl in
let else_env = block upcasted_info base_env else_bl in
Env.union parent_env then_env else_env
| A.Switch (cond, cases, dfl) ->
let env = expr upcasted_info env cond in
(* NB: A 'continue' inside a 'switch' block is equivalent to a 'break'.
* See the note in
* http://php.net/manual/en/control-structures.continue.php *)
Env.stash_and_do env [Cont.Continue; Cont.Break] @@ fun env ->
let parent_locals = env.lenv in
let env = switch upcasted_info parent_locals env cases dfl in
Env.update_next_from_conts env [Cont.Continue; Cont.Break; Cont.Next]
| A.Fallthrough -> Env.move_and_merge_next_in_cont env Cont.Fallthrough
| A.Continue -> Env.move_and_merge_next_in_cont env Cont.Continue
| A.Break -> Env.move_and_merge_next_in_cont env Cont.Break
| A.While (cond, bl) ->
Env.stash_and_do env [Cont.Continue; Cont.Break] @@ fun env ->
let env = Env.save_and_merge_next_in_cont env Cont.Continue in
let env_before_iteration = env in
let env_after_iteration =
let env = expr upcasted_info env cond in
let env = block upcasted_info env bl in
env
in
let env =
Env.loop_continuation Cont.Next ~env_before_iteration ~env_after_iteration
in
let env = Env.update_next_from_conts env [Cont.Continue; Cont.Next] in
let env = expr upcasted_info env cond in
let env = Env.update_next_from_conts env [Cont.Break; Cont.Next] in
env
| A.Noop
| A.AssertEnv _
| A.Markup _ ->
env
| _ -> failwithpos pos ("Unsupported statement: " ^ Utils.stmt_name stmt)
and block (upcasted_info : element_info) (env : env) : T.block -> env =
List.fold ~init:env ~f:(stmt upcasted_info)
let init_params _tast_env (params : T.fun_param list) :
constraint_ list * entity LMap.t =
let add_param (constraints, lmap) = function
| _ -> (constraints, lmap)
in
List.fold ~f:add_param ~init:([], LMap.empty) params
let callable upcasted_info tast_env params body : constraint_ list =
let (param_constraints, param_env) = init_params tast_env params in
let env = Env.init tast_env param_constraints param_env in
let env = block upcasted_info env body.A.fb_ast in
env.constraints
let program
(upcasted_info : element_info)
(ctx : Provider_context.t)
(tast : Tast.program) : constraint_ list SMap.t =
let def (def : T.def) : (string * constraint_ list) list =
let tast_env = Tast_env.def_env ctx def in
match def with
| A.Fun fd ->
let (_, id) = fd.A.fd_name in
let A.{ f_body; f_params; _ } = fd.A.fd_fun in
[(id, callable upcasted_info tast_env f_params f_body)]
| A.Class A.{ c_methods; c_name = (_, class_name); _ } ->
let handle_method A.{ m_body; m_name = (_, method_name); m_params; _ } =
let id = class_name ^ "::" ^ method_name in
(id, callable upcasted_info tast_env m_params m_body)
in
List.map ~f:handle_method c_methods
| _ -> failwith "A definition is not yet handled"
in
List.concat_map ~f:def tast |> SMap.of_list |
OCaml Interface | hhvm/hphp/hack/src/refactor_sd/refactor_sd_walker.mli | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Refactor_sd_types
val callable :
element_info ->
Tast_env.t ->
Tast.fun_param list ->
Tast.func_body ->
constraint_ list
val program :
element_info -> Provider_context.t -> Tast.program -> constraint_ list SMap.t |
hhvm/hphp/hack/src/remove_dead_unsafe_casts/dune | (library
(name remove_dead_unsafe_casts)
(wrapped false)
(modules remove_dead_unsafe_casts)
(libraries annotated_ast_utils server_command_types tast_env utils_core)) |
|
OCaml | hhvm/hphp/hack/src/remove_dead_unsafe_casts/remove_dead_unsafe_casts.ml | (*
* 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.
*
*)
open Hh_prelude
type patches = ServerRenameTypes.patch list
type can_be_captured = bool
module PatchHeap = struct
include
SharedMem.Heap
(SharedMem.ImmediateBackend (SharedMem.NonEvictable)) (Relative_path.S)
(struct
type t = can_be_captured * Pos.t * Pos.t
let description =
"Positions needed to generate dead unsafe cast removal patches"
end)
end
let patch_location_collection_handler =
object
inherit Tast_visitor.handler_base
method! at_expr env expr =
let typing_env = Tast_env.tast_env_as_typing_env env in
match expr with
| ( _,
hole_pos,
Aast.Hole
( (expr_ty, expr_pos, expr),
_,
dest_ty,
(Aast.UnsafeCast _ | Aast.UnsafeNonnullCast) ) )
when (not @@ Typing_defs.is_any expr_ty)
&& Typing_subtype.is_sub_type typing_env expr_ty dest_ty ->
let path = Tast_env.get_file env in
(* The following shared memory write will only work when the entry for
`path` is empty. Later updates will be dropped on the floor. This is
the desired behaviour as patches don't compose and we want to apply
them one at a time per file. *)
PatchHeap.add path (Aast_utils.can_be_captured expr, hole_pos, expr_pos)
| _ -> ()
end
let generate_patch content (can_be_captured, hole_pos, expr_pos) =
let text = Pos.get_text_from_pos ~content expr_pos in
(* Enclose with parantheses to prevent accidental capture of the expression
if the expression inside the UNSAFE_CAST can be captured. *)
let text =
if can_be_captured then
"(" ^ text ^ ")"
else
text
in
ServerRenameTypes.Replace
ServerRenameTypes.{ pos = Pos.to_absolute hole_pos; text }
let get_patches ?(is_test = false) ~files_info ~fold =
let get_patches_from_file path _ patches =
match PatchHeap.get path with
| None -> patches
| Some patch_info ->
(* Do not read from the disk in test mode because the file is not written
down between successive applications of the patch. Instead a
replacement is placed in memory through the file provider. *)
let contents =
File_provider.get_contents ~force_read_disk:(not is_test) path
|> Option.value_exn
in
let new_patch = generate_patch contents patch_info in
PatchHeap.remove path;
new_patch :: patches
in
fold files_info ~init:[] ~f:get_patches_from_file |
OCaml Interface | hhvm/hphp/hack/src/remove_dead_unsafe_casts/remove_dead_unsafe_casts.mli | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
type patches = ServerRenameTypes.patch list
val patch_location_collection_handler : Tast_visitor.handler_base
val get_patches :
?is_test:bool ->
files_info:'a ->
fold:
('a ->
init:patches ->
f:(Relative_path.t -> 'c -> patches -> patches) ->
patches) ->
patches |
Rust | hhvm/hphp/hack/src/rust_to_ocaml/attr/rust_to_ocaml_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 proc_macro::TokenStream;
/// This attribute macro is intended to be consumed by the rust_to_ocaml codegen
/// tool, so this proc macro doesn't need to do anything other than return the
/// item (with the rust_to_ocaml attribute stripped by rustc).
///
/// Use of the rust_to_ocaml attribute in positions other than items (like field
/// definitions) are stripped by ocamlrep_derive macros (which is simpler than
/// filtering them from the `item` in this crate).
///
/// We may want to add validation later so that incorrect use of the attribute
/// emits errors at compile time, but stripping is good enough for now.
#[proc_macro_attribute]
pub fn rust_to_ocaml(_attr: TokenStream, item: TokenStream) -> TokenStream {
item
} |
Rust | hhvm/hphp/hack/src/rust_to_ocaml/attr_parser/attr_parser.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 syn::Meta::List;
use syn::Meta::NameValue;
use syn::Meta::Path;
use syn::NestedMeta::Lit;
use syn::NestedMeta::Meta;
static DOC: &str = "doc";
static RUST_TO_OCAML: &str = "rust_to_ocaml";
static PREFIX: &str = "prefix";
static AND: &str = "and";
static ATTR: &str = "attr";
static NAME: &str = "name";
static INLINE_TUPLE: &str = "inline_tuple";
/// The attributes understood by `rust_to_ocaml`.
#[derive(Clone, Debug)]
pub struct Attrs {
/// Doc comments (and their desugared form, the `#[doc]` attribute) are
/// picked up by rust_to_ocaml and included as ocamldoc comments.
///
/// /// Type A
/// pub type A = X;
///
/// is converted to:
///
/// (** Type A *)
/// type a = x
pub doc: Vec<String>,
/// Sometimes OCaml programs use prefixes to distinguish fields of the same
/// name in different records (avoiding OCaml warning 30). The `prefix`
/// attribute (on a declaration of a struct or a struct-like enum variant)
/// indicates the prefix that should be added to each field name.
///
/// #[rust_to_ocaml(prefix = "a_")]
/// pub struct StructA { pub foo: isize, pub bar: isize }
/// #[rust_to_ocaml(prefix = "b_")]
/// pub struct StructB { pub foo: isize, pub bar: isize }
///
/// is converted to:
///
/// type struct_a = { a_foo: int; a_bar: int; }
/// type struct_b = { b_foo: int; b_bar: int; }
pub prefix: Option<String>,
/// OCaml attributes (in OCaml syntax) to annotate a type or field
/// declaration with in the generated OCaml.
///
/// #[rust_to_ocaml(attr = "deriving show")]
/// pub type X = A;
///
/// is converted to:
///
/// type x = a [@@deriving show]
pub attrs: Vec<String>,
/// Mutual recursion in type definitions is opt-in in OCaml; one writes
/// `type x = y list and y = x list` rather than `type x = y list ;; type y
/// = x list` (which is an error because the type name `y` is not bound in
/// the declaration of `x`). Use the `#[rust_to_ocaml(and)]` attribute to
/// indicate when the `and` keyword should be used to continue a mutually
/// recursive type declaration.
///
/// pub struct Foo(pub Bar, pub Bar);
/// #[rust_to_ocaml(and)]
/// pub struct Bar(pub Option<Foo>, pub Option<Foo>);
///
/// is converted to:
///
/// type foo = bar * bar
/// and bar = foo option * foo option
pub mutual_rec: bool,
/// Normally, rust_to_ocaml will convert the names of fields and enum
/// variants by attempting to convert idiomatic Rust casing to idiomatic
/// OCaml casing. Use the `#[rust_to_ocaml(name = "my_name")]` attribute to
/// override this behavior and provide some other name. This attribute takes
/// precedence over the `prefix` attribute (no prefix will be applied to the
/// given name). This attribute cannot be used to rename types (use
/// rust_to_ocaml_config.toml instead).
pub name: Option<String>,
/// In OCaml, a variant declared as `Foo of (a * b)` is a variant with one
/// field which is a pointer to a heap-allocated tuple. A variant declared
/// as `Baz of a * b` is a variant with two fields of type `a` and `b`.
///
/// By default, rust_to_ocaml will produce variants with a single field. But
/// this behavior can be overridden with the `inline_tuple` attribute,
/// converting the fields of a tuple (possibly behind a reference, `Box`, or
/// any other wrapper type declared in the `types.transparent` section in
/// rust_to_ocaml_config.toml) to fields of the OCaml variant.
///
/// pub enum E {
/// Foo((A, B)),
/// Bar(Box<(A, B)>),
/// #[rust_to_ocaml(inline_tuple)]
/// Baz((A, B)),
/// #[rust_to_ocaml(inline_tuple)]
/// Qux(Box<(A, B)>),
/// }
///
/// is converted to:
///
/// type e =
/// | Foo of (a * b)
/// | Bar of (a * b)
/// | Baz of a * b
/// | Qux of a * b
pub inline_tuple: bool,
}
impl Attrs {
pub fn from_type(item: &syn::ItemType) -> Self {
Self::from_attributes(&item.attrs, AttrKind::Container)
}
pub fn from_struct(item: &syn::ItemStruct) -> Self {
Self::from_attributes(&item.attrs, AttrKind::Container)
}
pub fn from_enum(item: &syn::ItemEnum) -> Self {
Self::from_attributes(&item.attrs, AttrKind::Container)
}
pub fn from_variant(variant: &syn::Variant) -> Self {
Self::from_attributes(&variant.attrs, AttrKind::Variant)
}
pub fn from_field(field: &syn::Field) -> Self {
Self::from_attributes(&field.attrs, AttrKind::Field)
}
fn from_attributes(attrs: &[syn::Attribute], kind: AttrKind) -> Self {
let doc = get_doc_comment(attrs);
let mut prefix = None;
let mut ocaml_attrs = vec![];
let mut mutual_rec = false;
let mut name = None;
let mut inline_tuple = false;
for meta_item in attrs
.iter()
.flat_map(get_rust_to_ocaml_meta_items)
.flatten()
{
match &meta_item {
// Parse `#[rust_to_ocaml(prefix = "foo")]`
Meta(NameValue(m)) if m.path.is_ident(PREFIX) => {
// TODO: emit error for AttrKind::Field (should use the
// `name` meta item instead)
if let Ok(s) = get_lit_str(PREFIX, &m.lit) {
prefix = Some(s.value());
}
}
// Parse `#[rust_to_ocaml(attr = "deriving eq")]`
Meta(NameValue(m)) if m.path.is_ident(ATTR) => {
if let Ok(s) = get_lit_str(ATTR, &m.lit) {
ocaml_attrs.push(s.value());
}
}
// Parse `#[rust_to_ocaml(and)]`
Meta(Path(word)) if word.is_ident(AND) => {
// TODO: emit an error instead
assert_eq!(kind, AttrKind::Container);
mutual_rec = true;
}
// Parse `#[rust_to_ocaml(name = "foo")]`
Meta(NameValue(m)) if m.path.is_ident(NAME) => {
// TODO: emit error for AttrKind::Container (should add to
// types.rename config instead)
if let Ok(s) = get_lit_str(NAME, &m.lit) {
name = Some(s.value());
}
}
// Parse `#[rust_to_ocaml(inline_tuple)]`
Meta(Path(word)) if word.is_ident(INLINE_TUPLE) => {
// TODO: emit an error instead
assert_eq!(kind, AttrKind::Variant);
inline_tuple = true;
}
Meta(_meta_item) => {
// let path = meta_item
// .path()
// .into_token_stream()
// .to_string()
// .replace(' ', "");
// cx.error_spanned_by(
// meta_item.path(),
// format!("unknown rust_to_ocaml {} attribute `{}`", kind, path),
// );
}
Lit(_lit) => {
// cx.error_spanned_by(lit, format!("unexpected literal in rust_to_ocaml {} attribute", kind));
}
}
}
Self {
doc,
prefix,
attrs: ocaml_attrs,
mutual_rec,
name,
inline_tuple,
}
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum AttrKind {
Container,
Variant,
Field,
}
impl std::fmt::Display for AttrKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Container => write!(f, "container"),
Self::Variant => write!(f, "variant"),
Self::Field => write!(f, "field"),
}
}
}
pub fn get_doc_comment(attrs: &[syn::Attribute]) -> Vec<String> {
attrs
.iter()
.filter_map(|attr| {
if !attr.path.is_ident(DOC) {
return None;
}
match attr.parse_meta() {
Ok(syn::Meta::NameValue(meta)) => {
if let syn::Lit::Str(s) = meta.lit {
Some(s.value())
} else {
None
}
}
_ => None,
}
})
.collect()
}
fn get_rust_to_ocaml_meta_items(attr: &syn::Attribute) -> Result<Vec<syn::NestedMeta>, ()> {
if !attr.path.is_ident(RUST_TO_OCAML) {
return Ok(vec![]);
}
match attr.parse_meta() {
Ok(List(meta)) => Ok(meta.nested.into_iter().collect()),
Ok(_other) => {
// cx.error_spanned_by(other, "expected #[rust_to_ocaml(...)]");
Err(())
}
Err(_err) => {
// cx.syn_error(err);
Err(())
}
}
}
fn get_lit_str<'a>(_attr_name: &'static str, lit: &'a syn::Lit) -> Result<&'a syn::LitStr, ()> {
if let syn::Lit::Str(lit) = lit {
Ok(lit)
} else {
// cx.error_spanned_by(
// lit,
// format!(
// "expected rust_to_ocaml {} attribute to be a string: `{} = \"...\"`",
// attr_name, attr_name
// ),
// );
Err(())
}
} |
TOML | hhvm/hphp/hack/src/rust_to_ocaml/attr_parser/Cargo.toml | # @generated by autocargo
[package]
name = "attr_parser"
version = "0.0.0"
edition = "2021"
[lib]
path = "attr_parser.rs"
[dependencies]
syn = { version = "1.0.109", features = ["extra-traits", "fold", "full", "visit", "visit-mut"] } |
TOML | hhvm/hphp/hack/src/rust_to_ocaml/rust_to_ocaml/Cargo.toml | # @generated by autocargo
[package]
name = "rust_to_ocaml"
version = "0.0.0"
edition = "2021"
[[bin]]
name = "rust_to_ocaml"
path = "../src/rust_to_ocaml.rs"
[dependencies]
anyhow = "1.0.71"
attr_parser = { version = "0.0.0", path = "../attr_parser" }
clap = { version = "3.2.25", features = ["derive", "env", "regex", "unicode", "wrap_help"] }
convert_case = "0.4.0"
derive_more = "0.99.17"
indexmap = { version = "1.9.2", features = ["arbitrary", "rayon", "serde-1"] }
serde = { version = "1.0.176", features = ["derive", "rc"] }
signed_source = { version = "0.0.0", path = "../../utils/rust/signed_source" }
syn = { version = "1.0.109", features = ["extra-traits", "fold", "full", "visit", "visit-mut"] }
toml = "0.7.3" |
TOML | hhvm/hphp/hack/src/rust_to_ocaml/rust_to_ocaml_attr/Cargo.toml | # @generated by autocargo
[package]
name = "rust_to_ocaml_attr"
version = "0.0.0"
edition = "2021"
[lib]
path = "../attr/rust_to_ocaml_attr.rs"
test = false
doctest = false
proc-macro = true |
Rust | hhvm/hphp/hack/src/rust_to_ocaml/src/config.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::str::FromStr;
use indexmap::indexmap;
use indexmap::indexset;
use indexmap::IndexMap;
use indexmap::IndexSet;
use serde::Deserialize;
use serde::Serialize;
use crate::ir;
use crate::ir::ModuleName;
use crate::ir::TypeName;
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct Config {
#[serde(default)]
modules: ModulesConfig,
#[serde(default)]
types: TypesConfig,
}
#[derive(Debug, Default, Serialize, Deserialize)]
struct ModulesConfig {
#[serde(default, with = "indexmap::serde_seq")]
rename: IndexMap<ModuleName, ModuleName>,
}
#[derive(Debug, Serialize, Deserialize)]
struct TypesConfig {
transparent: IndexSet<RustTypePath>,
#[serde(with = "indexmap::serde_seq")]
rename: IndexMap<RustTypePath, OcamlTypePath>,
}
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct RustTypePath {
pub modules: Vec<ModuleName>,
pub ty: TypeName,
}
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct OcamlTypePath {
pub modules: Vec<ModuleName>,
pub ty: TypeName,
}
impl Config {
pub fn get_renamed_module(&self, name: &ModuleName) -> Option<ModuleName> {
self.modules.rename.get(name).cloned()
}
pub fn is_transparent_type(&self, path: &ir::TypePath) -> bool {
let rust_path = RustTypePath::from(path);
self.types.transparent.contains(&rust_path)
}
pub fn get_renamed_type(&self, path: &ir::TypePath) -> Option<OcamlTypePath> {
let rust_path = RustTypePath::from(path);
self.types.rename.get(&rust_path).cloned()
}
}
impl Default for TypesConfig {
fn default() -> Self {
let r = |s| RustTypePath::from_str(s).unwrap();
let o = |s| OcamlTypePath::from_str(s).unwrap();
Self {
transparent: indexset! {
r("Box"),
r("std::boxed::Box"),
r("Rc"),
r("std::rc::Rc"),
r("Arc"),
r("std::sync::Arc"),
},
rename: indexmap! {
r("Vec") => o("list"),
r("std::vec::Vec") => o("list"),
},
}
}
}
impl From<&ir::TypePath> for RustTypePath {
fn from(path: &ir::TypePath) -> Self {
Self {
modules: path.modules.clone(),
ty: path.ty.clone(),
}
}
}
impl std::fmt::Display for RustTypePath {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for m in self.modules.iter() {
write!(f, "{}", m.as_str())?;
write!(f, "::")?;
}
write!(f, "{}", self.ty.as_str())
}
}
impl std::fmt::Display for OcamlTypePath {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for m in self.modules.iter() {
write!(f, "{}", m.as_str())?;
write!(f, ".")?;
}
write!(f, "{}", self.ty.as_str())
}
}
impl std::fmt::Debug for RustTypePath {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
format!("{self}").fmt(f)
}
}
impl std::fmt::Debug for OcamlTypePath {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
format!("{self}").fmt(f)
}
}
impl FromStr for RustTypePath {
type Err = anyhow::Error;
fn from_str(s: &str) -> anyhow::Result<Self> {
let (modules, ty) = parse_type_path(s, "::")?;
Ok(Self { modules, ty })
}
}
impl FromStr for OcamlTypePath {
type Err = anyhow::Error;
fn from_str(s: &str) -> anyhow::Result<Self> {
let (modules, ty) = parse_type_path(s, ".")?;
Ok(Self { modules, ty })
}
}
fn parse_type_path(s: &str, sep: &str) -> anyhow::Result<(Vec<ModuleName>, TypeName)> {
let mut split = s.rsplit(sep);
let ty = match split.next() {
None | Some("") => anyhow::bail!("Invalid type name: {:?}", s),
Some(ty) => TypeName(ty.to_owned()),
};
let mut modules = split.map(ModuleName::new).collect::<Result<Vec<_>, _>>()?;
modules.reverse();
Ok((modules, ty))
}
serde_from_display!(RustTypePath, "a valid Rust type path string");
serde_from_display!(OcamlTypePath, "a valid OCaml type path string"); |
Rust | hhvm/hphp/hack/src/rust_to_ocaml/src/convert.rs | // Copyright (c) Meta Platforms, Inc. and affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use anyhow::bail;
use anyhow::ensure;
use anyhow::Context;
use anyhow::Result;
use convert_case::Case;
use convert_case::Casing;
use crate::ir;
use crate::ir::Def;
use crate::ir::FieldName;
use crate::ir::File;
use crate::ir::TypeName;
use crate::ir::VariantName;
use crate::Config;
pub fn convert_file(
config: &'static Config,
filename: &std::path::Path,
file: &syn::File,
) -> Result<String> {
let defs = (file.items.iter())
.filter_map(|item| ItemConverter::convert_item(config, item).transpose())
.collect::<Result<_>>()?;
let file_stem = filename.file_stem().context("expected nonempty filename")?;
let module_name = file_stem.to_str().context("non-UTF8 filename")?.to_owned();
let mut file = File {
root: ir::Module {
name: ir::ModuleName::new(module_name)?,
defs,
},
};
crate::rewrite_types::rewrite_file(config, &mut file);
crate::rewrite_module_names::rewrite_file(config, &mut file);
Ok(file.to_string())
}
struct ItemConverter {
config: &'static Config,
tparams: Vec<String>,
}
impl ItemConverter {
fn convert_item(config: &'static Config, item: &syn::Item) -> Result<Option<Def>> {
use syn::Item;
match item {
Item::Type(item) => {
let this = ItemConverter::new(config, &item.generics);
Ok(Some(this.convert_item_type(item).with_context(|| {
format!("Failed to convert type {}", item.ident)
})?))
}
Item::Struct(item) => {
let this = ItemConverter::new(config, &item.generics);
Ok(Some(this.convert_item_struct(item).with_context(|| {
format!("Failed to convert type {}", item.ident)
})?))
}
Item::Enum(item) => {
let this = ItemConverter::new(config, &item.generics);
Ok(Some(this.convert_item_enum(item).with_context(|| {
format!("Failed to convert type {}", item.ident)
})?))
}
Item::Mod(item) => {
if let Some((_brace, items)) = &item.content {
let defs = items
.iter()
.filter_map(|item| Self::convert_item(config, item).transpose())
.collect::<Result<_>>()
.with_context(|| format!("Failed to convert module {}", item.ident))?;
Ok(Some(Def::Module(ir::Module {
name: ir::ModuleName::new(item.ident.to_string())?,
defs,
})))
} else {
Ok(None)
}
}
_ => Ok(None),
}
}
fn new(config: &'static Config, generics: &syn::Generics) -> Self {
let tparams = generics
.type_params()
.map(|tparam| tparam.ident.to_string())
.collect();
Self { config, tparams }
}
fn convert_item_type(self, item: &syn::ItemType) -> Result<Def> {
let name = TypeName(item.ident.to_string().to_case(Case::Snake));
let attrs = attr_parser::Attrs::from_type(item);
let ty = self.convert_type(&item.ty)?;
Ok(Def::Alias {
doc: attrs.doc,
attrs: attrs.attrs,
mutual_rec: attrs.mutual_rec,
tparams: self.tparams,
name,
ty,
})
}
fn convert_item_struct(self, item: &syn::ItemStruct) -> Result<Def> {
let name = TypeName(item.ident.to_string().to_case(Case::Snake));
let container_attrs = attr_parser::Attrs::from_struct(item);
match &item.fields {
syn::Fields::Unit => Ok(Def::Alias {
doc: container_attrs.doc,
attrs: container_attrs.attrs,
mutual_rec: container_attrs.mutual_rec,
tparams: self.tparams,
name,
ty: ir::Type::Path(ir::TypePath::simple("unit")),
}),
syn::Fields::Unnamed(fields) => {
let elems = (fields.unnamed.iter())
.map(|field| self.convert_type(&field.ty))
.collect::<Result<Vec<_>>>()?;
Ok(Def::Alias {
doc: container_attrs.doc,
attrs: container_attrs.attrs,
mutual_rec: container_attrs.mutual_rec,
tparams: self.tparams,
name,
ty: if elems.is_empty() {
ir::Type::Path(ir::TypePath::simple("unit"))
} else {
ir::Type::Tuple(ir::TypeTuple { elems })
},
})
}
syn::Fields::Named(fields) => {
let fields = (fields.named.iter())
.map(|field| {
let field_attrs = attr_parser::Attrs::from_field(field);
let name = if let Some(name) = field_attrs.name {
FieldName(name)
} else {
field_name(field.ident.as_ref(), container_attrs.prefix.as_deref())
};
let ty = self.convert_type(&field.ty)?;
Ok(ir::Field {
name,
ty,
doc: field_attrs.doc,
attrs: field_attrs.attrs,
})
})
.collect::<Result<Vec<_>>>()?;
Ok(Def::Record {
doc: container_attrs.doc,
attrs: container_attrs.attrs,
mutual_rec: container_attrs.mutual_rec,
tparams: self.tparams,
name,
fields,
})
}
}
}
fn convert_item_enum(self, item: &syn::ItemEnum) -> Result<Def> {
let name = TypeName(item.ident.to_string().to_case(Case::Snake));
let container_attrs = attr_parser::Attrs::from_enum(item);
let variants = item
.variants
.iter()
.map(|variant| {
let variant_attrs = attr_parser::Attrs::from_variant(variant);
let name = if let Some(name) = variant_attrs.name {
VariantName(name)
} else {
variant_name(&variant.ident, container_attrs.prefix.as_deref())
};
let fields = match &variant.fields {
syn::Fields::Unit => None,
syn::Fields::Unnamed(fields) => {
let mut fields = (fields.unnamed.iter())
.map(|field| self.convert_type(&field.ty))
.collect::<Result<Vec<_>>>()?;
if variant_attrs.inline_tuple {
assert_eq!(fields.len(), 1);
let field = fields.pop().unwrap();
match field {
ir::Type::Path(mut path) => {
if path.targs.len() == 1
&& self.config.is_transparent_type(&path)
&& matches!(path.targs[0], ir::Type::Tuple(..))
{
if let Some(ir::Type::Tuple(tuple)) = path.targs.pop() {
Some(ir::VariantFields::Unnamed(tuple.elems))
} else {
unreachable!()
}
} else {
anyhow::bail!(
"Variant {} must have a single argument which is a tuple",
variant.ident.to_string()
)
}
}
ir::Type::Tuple(tuple) => {
Some(ir::VariantFields::Unnamed(tuple.elems))
}
}
} else {
Some(ir::VariantFields::Unnamed(fields))
}
}
syn::Fields::Named(fields) => Some(ir::VariantFields::Named(
(fields.named.iter())
.map(|field| {
let field_attrs = attr_parser::Attrs::from_field(field);
let name = if let Some(name) = field_attrs.name {
FieldName(name)
} else {
field_name(
field.ident.as_ref(),
variant_attrs.prefix.as_deref(),
)
};
let ty = self.convert_type(&field.ty)?;
Ok(ir::Field {
name,
ty,
doc: field_attrs.doc,
attrs: field_attrs.attrs,
})
})
.collect::<Result<_>>()?,
)),
};
Ok(ir::Variant {
name,
fields,
doc: variant_attrs.doc,
attrs: variant_attrs.attrs,
})
})
.collect::<Result<Vec<_>>>()?;
Ok(Def::Variant {
doc: container_attrs.doc,
attrs: container_attrs.attrs,
mutual_rec: container_attrs.mutual_rec,
tparams: self.tparams,
name,
variants,
})
}
fn convert_type(&self, ty: &syn::Type) -> Result<ir::Type> {
match ty {
syn::Type::Path(ty) => Ok(ir::Type::Path(self.convert_type_path(ty)?)),
syn::Type::Tuple(ty) => {
if ty.elems.is_empty() {
Ok(ir::Type::Path(ir::TypePath::simple("unit")))
} else {
Ok(ir::Type::Tuple(ir::TypeTuple {
elems: (ty.elems.iter())
.map(|e| self.convert_type(e))
.collect::<Result<_>>()?,
}))
}
}
syn::Type::Reference(ty) => Ok(self.convert_type(&ty.elem)?),
syn::Type::Slice(ty) => Ok(ir::Type::Path(ir::TypePath {
modules: vec![],
targs: vec![self.convert_type(&ty.elem)?],
ty: ir::TypeName(String::from("list")),
})),
_ => bail!("Not supported: {:?}", ty),
}
}
fn convert_type_path(&self, ty: &syn::TypePath) -> Result<ir::TypePath> {
ensure!(ty.qself.is_none(), "Qualified self in paths not supported");
let last_seg = ty.path.segments.last().unwrap();
if ty.path.segments.len() == 1 && last_seg.arguments.is_empty() {
let ident = last_seg.ident.to_string();
if self.tparams.contains(&ident) {
let tparam = format!("'{}", ident.to_case(Case::Snake));
return Ok(ir::TypePath::simple(tparam));
}
}
let segments_except_last = ty.path.segments.iter().rev().skip(1).rev();
Ok(ir::TypePath {
modules: segments_except_last
.map(|seg| {
ensure!(
seg.arguments.is_empty(),
"Type args only supported in last path segment"
);
ir::ModuleName::new(seg.ident.to_string())
})
.collect::<Result<_>>()?,
ty: TypeName(last_seg.ident.to_string()),
targs: match &last_seg.arguments {
syn::PathArguments::AngleBracketed(args) => (args.args.iter())
.filter_map(|arg| match arg {
syn::GenericArgument::Type(arg) => Some(self.convert_type(arg)),
_ => None,
})
.collect::<Result<_>>()?,
_ => vec![],
},
})
}
}
fn field_name(ident: Option<&syn::Ident>, prefix: Option<&str>) -> FieldName {
FieldName(format!("{}{}", prefix.unwrap_or_default(), ident.unwrap()))
}
fn variant_name(ident: &syn::Ident, prefix: Option<&str>) -> VariantName {
VariantName(format!("{}{}", prefix.unwrap_or_default(), ident))
} |
Rust | hhvm/hphp/hack/src/rust_to_ocaml/src/ir.rs | // Copyright (c) Meta Platforms, Inc. and affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
mod display;
use derive_more::Display;
#[derive(Debug)]
pub struct File {
pub root: Module,
}
#[derive(Debug)]
pub struct Module {
pub name: ModuleName,
pub defs: Vec<Def>,
}
#[derive(Debug)]
pub enum Def {
Module(Module),
Alias {
doc: Vec<String>,
attrs: Vec<String>,
mutual_rec: bool,
tparams: Vec<String>,
name: TypeName,
ty: Type,
},
Record {
doc: Vec<String>,
attrs: Vec<String>,
mutual_rec: bool,
tparams: Vec<String>,
name: TypeName,
fields: Vec<Field>,
},
Variant {
doc: Vec<String>,
attrs: Vec<String>,
mutual_rec: bool,
tparams: Vec<String>,
name: TypeName,
variants: Vec<Variant>,
},
}
#[derive(Debug)]
pub struct Variant {
pub name: VariantName,
pub fields: Option<VariantFields>,
pub doc: Vec<String>,
pub attrs: Vec<String>,
}
#[derive(Debug)]
pub enum VariantFields {
Unnamed(Vec<Type>),
Named(Vec<Field>),
}
#[derive(Debug)]
pub struct Field {
pub name: FieldName,
pub ty: Type,
pub doc: Vec<String>,
pub attrs: Vec<String>,
}
#[derive(Debug)]
pub enum Type {
Path(TypePath),
Tuple(TypeTuple),
}
#[derive(Debug)]
pub struct TypePath {
pub targs: Vec<Type>,
pub modules: Vec<ModuleName>,
pub ty: TypeName,
}
impl TypePath {
pub fn simple(id: impl Into<String>) -> Self {
Self {
modules: vec![],
ty: TypeName(id.into()),
targs: vec![],
}
}
}
#[derive(Debug)]
pub struct TypeTuple {
pub elems: Vec<Type>,
}
#[derive(Clone, Hash, PartialEq, Eq)]
pub struct ModuleName(String);
impl ModuleName {
pub fn new(name: impl Into<String>) -> anyhow::Result<Self> {
let name: String = name.into();
anyhow::ensure!(!name.is_empty(), "Module names must not be empty");
let first_char = name.chars().next().unwrap();
anyhow::ensure!(
first_char.is_ascii(),
"Module names must start with an ASCII character: {}",
name
);
anyhow::ensure!(
first_char.to_ascii_uppercase().is_ascii_uppercase(),
"Module names must start with a character which can be converted to uppercase: {}",
name
);
Ok(Self(name))
}
pub fn as_str(&self) -> &str {
self.0.as_str()
}
}
impl std::str::FromStr for ModuleName {
type Err = anyhow::Error;
fn from_str(s: &str) -> anyhow::Result<Self> {
Self::new(s)
}
}
serde_from_display!(ModuleName, "a valid Rust or OCaml module name");
#[derive(Clone, Hash, PartialEq, Eq)]
pub struct TypeName(pub String);
impl TypeName {
pub fn as_str(&self) -> &str {
self.0.as_str()
}
}
#[derive(Clone, Hash, PartialEq, Eq)]
pub struct FieldName(pub String);
#[derive(Clone, Hash, PartialEq, Eq, Display)]
pub struct VariantName(pub String);
impl std::fmt::Debug for ModuleName {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl std::fmt::Debug for TypeName {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl std::fmt::Debug for FieldName {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl std::fmt::Debug for VariantName {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
} |
Rust | hhvm/hphp/hack/src/rust_to_ocaml/src/macros.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.
/// Provide impls of `Serialize` and `Deserialize` which delegate to the impls
/// of `std::fmt::Display` and `std::str::FromStr` respectively.
macro_rules! serde_from_display {
($name:ident, $expecting:expr) => {
impl ::serde::Serialize for $name {
fn serialize<S: ::serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&self.to_string())
}
}
impl<'de> ::serde::Deserialize<'de> for $name {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: ::serde::Deserializer<'de>,
{
struct Visitor;
impl<'de> ::serde::de::Visitor<'de> for Visitor {
type Value = $name;
fn expecting(
&self,
formatter: &mut ::std::fmt::Formatter<'_>,
) -> ::std::fmt::Result {
formatter.write_str($expecting)
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: ::serde::de::Error,
{
value.parse().map_err(|e| {
E::invalid_value(::serde::de::Unexpected::Other(&format!("{e}")), &self)
})
}
}
deserializer.deserialize_str(Visitor)
}
}
};
} |
Rust | hhvm/hphp/hack/src/rust_to_ocaml/src/rewrite_module_names.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::ir;
use crate::Config;
pub fn rewrite_file(config: &'static Config, file: &mut ir::File) {
let rewriter = Rewriter { config };
rewriter.rewrite_module(&mut file.root)
}
struct Rewriter {
config: &'static Config,
}
impl Rewriter {
fn rewrite_module(&self, module: &mut ir::Module) {
module.defs.iter_mut().for_each(|def| self.rewrite_def(def))
}
fn rewrite_def(&self, def: &mut ir::Def) {
match def {
ir::Def::Module(module) => self.rewrite_module(module),
ir::Def::Alias { ty, .. } => self.rewrite_type(ty),
ir::Def::Record { fields, .. } => fields.iter_mut().for_each(|f| self.rewrite_field(f)),
ir::Def::Variant { variants, .. } => {
variants.iter_mut().for_each(|v| self.rewrite_variant(v))
}
}
}
fn rewrite_field(&self, field: &mut ir::Field) {
self.rewrite_type(&mut field.ty)
}
fn rewrite_variant(&self, variant: &mut ir::Variant) {
variant
.fields
.iter_mut()
.for_each(|f| self.rewrite_variant_fields(f))
}
fn rewrite_variant_fields(&self, fields: &mut ir::VariantFields) {
match fields {
ir::VariantFields::Unnamed(tys) => tys.iter_mut().for_each(|ty| self.rewrite_type(ty)),
ir::VariantFields::Named(fields) => {
fields.iter_mut().for_each(|f| self.rewrite_field(f))
}
}
}
fn rewrite_type(&self, ty: &mut ir::Type) {
match ty {
ir::Type::Path(path) => self.rewrite_type_path(path),
ir::Type::Tuple(tuple) => self.rewrite_type_tuple(tuple),
}
}
fn rewrite_type_path(&self, path: &mut ir::TypePath) {
match path.modules.get(0).map(ir::ModuleName::as_str) {
Some("crate" | "super") => {
path.modules.remove(0);
}
_ => {}
}
path.modules.iter_mut().for_each(|m| {
if let Some(name) = self.config.get_renamed_module(m) {
*m = name;
}
});
path.targs.iter_mut().for_each(|ty| self.rewrite_type(ty))
}
fn rewrite_type_tuple(&self, tuple: &mut ir::TypeTuple) {
tuple.elems.iter_mut().for_each(|ty| self.rewrite_type(ty))
}
} |
Rust | hhvm/hphp/hack/src/rust_to_ocaml/src/rewrite_types.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 convert_case::Case;
use convert_case::Casing;
use crate::ir;
use crate::Config;
pub fn rewrite_file(config: &'static Config, file: &mut ir::File) {
Rewriter::rewrite_module(config, &mut file.root)
}
struct Rewriter {
config: &'static Config,
module_name: ir::ModuleName,
}
impl Rewriter {
fn rewrite_module(config: &'static Config, module: &mut ir::Module) {
let this = Self {
config,
module_name: module.name.clone(),
};
module.defs.iter_mut().for_each(|def| this.rewrite_def(def))
}
fn rewrite_def(&self, def: &mut ir::Def) {
let rewrite_name = |name: &mut ir::TypeName| {
if name.as_str() == self.module_name.as_str() {
*name = ir::TypeName(String::from("t"));
}
};
match def {
ir::Def::Module(module) => Self::rewrite_module(self.config, module),
ir::Def::Alias { name, ty, .. } => {
rewrite_name(name);
self.rewrite_type(ty)
}
ir::Def::Record { name, fields, .. } => {
rewrite_name(name);
fields.iter_mut().for_each(|f| self.rewrite_field(f))
}
ir::Def::Variant { name, variants, .. } => {
rewrite_name(name);
variants.iter_mut().for_each(|v| self.rewrite_variant(v))
}
}
}
fn rewrite_field(&self, field: &mut ir::Field) {
self.rewrite_type(&mut field.ty)
}
fn rewrite_variant(&self, variant: &mut ir::Variant) {
variant
.fields
.iter_mut()
.for_each(|f| self.rewrite_variant_fields(f))
}
fn rewrite_variant_fields(&self, fields: &mut ir::VariantFields) {
match fields {
ir::VariantFields::Unnamed(tys) => tys.iter_mut().for_each(|ty| self.rewrite_type(ty)),
ir::VariantFields::Named(fields) => {
fields.iter_mut().for_each(|f| self.rewrite_field(f))
}
}
}
fn rewrite_type(&self, ty: &mut ir::Type) {
match ty {
ir::Type::Path(path) => {
if path.targs.len() == 1 && self.config.is_transparent_type(path) {
*ty = path.targs.pop().unwrap();
self.rewrite_type(ty);
} else {
self.rewrite_type_path(path);
}
}
ir::Type::Tuple(tuple) => self.rewrite_type_tuple(tuple),
}
}
fn rewrite_type_path(&self, path: &mut ir::TypePath) {
// Convert all integer types to `int`. The impls of ToOcamlRep
// and FromOcamlRep for integer types do checked conversions, so
// we'll fail at runtime if our int value doesn't fit into
// OCaml's integer width.
if path.modules.is_empty() && path.targs.is_empty() {
match path.ty.as_str() {
"i8" | "u8" | "i16" | "u16" | "i32" | "u32" | "i64" | "u64" | "i128" | "u128"
| "isize" | "usize" => {
path.ty = ir::TypeName(String::from("int"));
return;
}
_ => {}
}
}
if let Some(renamed_path) = self.config.get_renamed_type(path) {
path.ty = renamed_path.ty;
path.modules = renamed_path.modules;
}
let ty = path.ty.as_str().to_case(Case::Snake);
let ty_matches_last_module_in_path =
(path.modules.last()).map_or(false, |module| ty == module.as_str());
if ty_matches_last_module_in_path || ty == self.module_name.as_str() {
path.ty = ir::TypeName(String::from("t"));
}
path.targs.iter_mut().for_each(|ty| self.rewrite_type(ty))
}
fn rewrite_type_tuple(&self, tuple: &mut ir::TypeTuple) {
tuple.elems.iter_mut().for_each(|ty| self.rewrite_type(ty))
}
} |
Rust | hhvm/hphp/hack/src/rust_to_ocaml/src/rust_to_ocaml.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.
#[macro_use]
mod macros;
mod config;
mod convert;
mod ir;
mod rewrite_module_names;
mod rewrite_types;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use anyhow::Context;
use anyhow::Result;
use crate::config::Config;
#[derive(Debug, clap::Parser)]
struct Opts {
/// The Hack source file to convert.
#[clap(value_name("FILEPATH"))]
filename: PathBuf,
/// The OCaml source file to generate.
#[clap(value_name("OUTPATH"))]
out_path: Option<PathBuf>,
/// Path to a configuration file.
#[clap(long)]
config: Option<PathBuf>,
/// Command to regenerate the output. This text will be included in generated file headers.
#[clap(long)]
regen_cmd: Option<String>,
/// Do not add copyright header and generated tag (for tests).
#[clap(long)]
no_header: bool,
/// Path to an OCaml formatter binary which will be used on the generated output.
#[clap(long)]
formatter: Option<String>,
}
fn main() -> Result<()> {
let opts = <Opts as clap::Parser>::parse();
let config = Box::leak(Box::new(match opts.config {
Some(path) => {
let contents = std::fs::read_to_string(&path)
.with_context(|| format!("Failed to read config file at {}", path.display()))?;
toml::from_str(&contents)
.with_context(|| format!("Failed to parse config file at {}", path.display()))?
}
None => Config::default(),
}));
let src = std::fs::read_to_string(&opts.filename)
.with_context(|| format!("Failed to read input file {}", opts.filename.display()))?;
let file = syn::parse_file(&src)?;
let mut ocaml_src = convert::convert_file(config, &opts.filename, &file)?;
if !opts.no_header {
ocaml_src = attach_header(opts.regen_cmd.as_deref(), &ocaml_src);
}
let absolute_filename = opts.filename.canonicalize()?;
let mut ocaml_src = ocamlformat(
opts.formatter.as_deref(),
opts.out_path
.as_deref()
.and_then(Path::parent)
.or_else(|| absolute_filename.parent()),
ocaml_src.into_bytes(),
)
.context("failed to run ocamlformat")?;
if !opts.no_header {
ocaml_src = signed_source::sign_file(&ocaml_src)?;
}
if let Some(out_path) = &opts.out_path {
write_file(out_path, &ocaml_src)?;
} else {
let mut stdout = std::io::stdout().lock();
stdout.write_all(&ocaml_src)?;
}
Ok(())
}
fn attach_header(regen_cmd: Option<&str>, contents: &str) -> String {
let regen_cmd = regen_cmd.map_or_else(String::new, |regen_cmd| {
format!(" *\n * To regenerate this file, run:\n * {}\n", regen_cmd)
});
format!(
r#"(*
* 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.
*
* {}
{} *)
{}"#,
signed_source::SIGNING_TOKEN,
regen_cmd,
contents
)
}
fn ocamlformat(
formatter: Option<&str>,
out_dir: Option<&Path>,
contents: Vec<u8>,
) -> Result<Vec<u8>> {
let formatter = match formatter {
None => return Ok(contents),
Some(f) => f,
};
// Even if we format the file on disk (i.e., at `opts.out_path`),
// ocamlformat won't look for an .ocamlformat file in the directory
// containing the file. It only looks up from the current working directory.
// There's a --root arg, but it doesn't seem to produce the same behavior.
let prev_dir = std::env::current_dir()?;
if let Some(out_dir) = out_dir {
std::env::set_current_dir(out_dir)?;
}
let mut child = std::process::Command::new(formatter)
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
// In the event that an .ocamlformat file is still not available, tell
// ocamlformat to please format it anyway.
.arg("--enable-outside-detected-project")
.arg("--impl")
.arg("-")
.spawn()?;
let child_stdin = child.stdin.as_mut().unwrap();
child_stdin.write_all(&contents)?;
let output = child.wait_with_output()?;
if !output.status.success() {
anyhow::bail!("Formatter failed:\n{:#?}", output);
}
if out_dir.is_some() {
std::env::set_current_dir(prev_dir)?;
}
Ok(output.stdout)
}
fn write_file(path: &Path, contents: &[u8]) -> Result<()> {
let mut file = std::fs::File::create(path)?;
file.write_all(contents)?;
Ok(())
} |
Rust | hhvm/hphp/hack/src/rust_to_ocaml/src/ir/display.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::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Result;
use convert_case::Case;
use convert_case::Casing;
use crate::ir;
impl Display for ir::File {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
self.root.fmt(f)
}
}
impl Display for ir::Module {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
for def in self.defs.iter() {
def.fmt(f)?
}
Ok(())
}
}
impl Display for ir::Def {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
match self {
Self::Module(module) => {
writeln!(f, "module {} = struct", module.name)?;
module.fmt(f)?;
writeln!(f, "end")?
}
Self::Alias {
doc,
attrs,
mutual_rec,
tparams,
name,
ty,
} => {
write_toplevel_doc_comment(f, doc)?;
if *mutual_rec {
write!(f, "and ")?;
} else {
write!(f, "type ")?;
}
write_type_parameters(f, tparams)?;
write!(f, "{name} = {ty}")?;
for attr in attrs {
write!(f, " [@@{}]", attr)?;
}
writeln!(f)?;
}
Self::Record {
doc,
attrs,
mutual_rec,
tparams,
name,
fields,
} => {
write_toplevel_doc_comment(f, doc)?;
if *mutual_rec {
write!(f, "and ")?;
} else {
write!(f, "type ")?;
}
write_type_parameters(f, tparams)?;
writeln!(f, "{name} = {{")?;
for field in fields {
writeln!(f, " {field}")?;
}
write!(f, "}}")?;
for attr in attrs {
write!(f, " [@@{}]", attr)?;
}
writeln!(f)?;
}
Self::Variant {
doc,
attrs,
mutual_rec,
tparams,
name,
variants,
} => {
write_toplevel_doc_comment(f, doc)?;
if *mutual_rec {
write!(f, "and ")?;
} else {
write!(f, "type ")?;
}
write_type_parameters(f, tparams)?;
writeln!(f, "{name} =")?;
for variant in variants {
writeln!(f, " | {variant}")?;
}
for attr in attrs {
writeln!(f)?;
write!(f, "[@@{}]", attr)?;
}
writeln!(f)?;
}
}
writeln!(f)?;
Ok(())
}
}
impl Display for ir::Variant {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
let Self {
name,
fields,
doc,
attrs,
} = self;
write!(f, "{name}")?;
if let Some(fields) = fields {
write!(f, " of {fields}")?;
}
for attr in attrs {
write!(f, " [@{}]", attr)?;
}
write_field_or_variant_doc_comment(f, doc)?;
Ok(())
}
}
impl Display for ir::VariantFields {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
match self {
Self::Unnamed(fields) => {
let mut iter = fields.iter();
let ty = iter.next().expect("empty VariantFields::Unnamed");
ty.fmt(f)?;
for ty in iter {
write!(f, " * {ty}")?;
}
Ok(())
}
Self::Named(fields) => {
writeln!(f, "{{")?;
for field in fields {
writeln!(f, " {field}")?;
}
write!(f, "}}")
}
}
}
}
impl Display for ir::Field {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
let Self {
name,
ty,
doc,
attrs,
} = self;
write!(f, "{name}: {ty};")?;
for attr in attrs {
write!(f, " [@{}]", attr)?;
}
write_field_or_variant_doc_comment(f, doc)?;
Ok(())
}
}
impl Display for ir::Type {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
match self {
Self::Path(ty) => ty.fmt(f),
Self::Tuple(ty) => ty.fmt(f),
}
}
}
impl Display for ir::TypePath {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
match self.targs.as_slice() {
[] => {}
[targ] => write!(f, "{} ", targ)?,
[first, rest @ ..] => {
write!(f, "({}", first)?;
for targ in rest {
write!(f, ", {}", targ)?;
}
write!(f, ") ")?;
}
}
for module in self.modules.iter() {
write!(f, "{}.", module)?;
}
write!(f, "{}", self.ty)
}
}
impl Display for ir::TypeTuple {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
write!(f, "(")?;
let mut elems = self.elems.iter();
let elem = elems.next().expect("empty TypeTuple");
write!(f, "{elem}")?;
for elem in elems {
write!(f, " * {elem}")?;
}
write!(f, ")")
}
}
impl Display for ir::ModuleName {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
let name = &self.0;
let mut first_char = name.chars().next().unwrap(); // Invariant: self.0 is nonempty
// OCaml modules _must_ start with an uppercase letter (the OCaml parser
// depends on this). We ensure in `ModuleName`'s constructor that the
// first character is ASCII, so we can use `make_ascii_uppercase`.
first_char.make_ascii_uppercase();
assert!(first_char.is_ascii_uppercase());
write!(f, "{}", first_char)?;
write!(f, "{}", &name[1..])
}
}
fn is_ocaml_keyword(name: &str) -> bool {
match name {
"and" | "as" | "assert" | "asr" | "begin" | "class" | "constraint" | "do" | "done"
| "downto" | "else" | "end" | "exception" | "external" | "false" | "for" | "fun"
| "function" | "functor" | "if" | "in" | "include" | "inherit" | "initializer" | "land"
| "lazy" | "let" | "lor" | "lsl" | "lsr" | "lxor" | "match" | "method" | "mod"
| "module" | "mutable" | "new" | "nonrec" | "object" | "of" | "open" | "or" | "private"
| "rec" | "sig" | "struct" | "then" | "to" | "true" | "try" | "type" | "val"
| "virtual" | "when" | "while" | "with" => true,
_ => false,
}
}
impl Display for ir::TypeName {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
let name = self.0.to_case(Case::Snake);
if is_ocaml_keyword(name.as_str()) {
write!(f, "{}_", name)
} else {
name.fmt(f)
}
}
}
impl Display for ir::FieldName {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
let name = self.0.to_case(Case::Snake);
if is_ocaml_keyword(name.as_str()) {
write!(f, "{}_", name)
} else {
name.fmt(f)
}
}
}
fn write_toplevel_doc_comment(
f: &mut std::fmt::Formatter<'_>,
doc: &Vec<String>,
) -> std::fmt::Result {
if doc.is_empty() {
return Ok(());
}
write!(f, "(**{}", doc.join("\n *"))?;
if doc.len() == 1 {
if !doc[0].contains('\n') {
write!(f, " ")?;
}
} else {
write!(f, "\n ")?;
}
writeln!(f, "*)")?;
Ok(())
}
fn write_field_or_variant_doc_comment(
f: &mut std::fmt::Formatter<'_>,
doc: &Vec<String>,
) -> std::fmt::Result {
if doc.is_empty() {
return Ok(());
}
let joined = doc.join("\n *");
write!(f, "(**{}", joined)?;
if !joined.ends_with(' ') {
write!(f, " ")?;
}
writeln!(f, "*)")?;
Ok(())
}
fn write_type_parameters(f: &mut std::fmt::Formatter<'_>, tparams: &[String]) -> std::fmt::Result {
match tparams {
[] => {}
[tparam] => write!(f, "'{} ", tparam.to_case(Case::Snake))?,
[first, rest @ ..] => {
write!(f, "('{}", first.to_case(Case::Snake))?;
for tparam in rest {
write!(f, ", '{} ", tparam.to_case(Case::Snake))?;
}
write!(f, ") ")?;
}
}
Ok(())
} |
hhvm/hphp/hack/src/sdt_analysis/dune | (library
(name sdt_analysis)
(wrapped true)
(flags
(:standard -linkall))
(libraries
core_kernel
disk
file_provider
provider_context
aast_names_utils
full_fidelity
full_fidelity_refactor
relative_path
sdt_analysis_remote_logging
server_command_types
tast_env
typing_ast
typing_defs
typing_env_types
hips2)
(preprocess
(pps lwt_ppx visitors.ppx ppx_deriving.std ppx_sexp_conv ppx_hash))) |
|
OCaml | hhvm/hphp/hack/src/sdt_analysis/sdt_analysis.ml | (*
* 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.
*
*)
open Sdt_analysis_types
open Hh_prelude
module IntraWalker = Sdt_analysis_intra_walker
module InterWalker = Sdt_analysis_inter_walker
module TastHandler = Sdt_analysis_tast_handler
module PP = Sdt_analysis_pretty_printer
module ClientCheck = Sdt_analysis_client_check
let default_db_dir = "/tmp/sdt_analysis_constraints"
let exit_if_incorrect_tcopt ctx : unit =
let tcopt = Provider_context.get_tcopt ctx in
let has_correct_options =
TypecheckerOptions.(enable_sound_dynamic tcopt && everything_sdt tcopt)
in
if not has_correct_options then (
Out_channel.output_string
stderr
{|sdt analysis can only be used with certain options.
If running with hh_single_type_check, pass flags `--implicit-pess.
If running with hh, pass these flags or set the corresponding .hhconfig options:
--config enable_sound_dynamic_type=true \
--config everything_sdt=true \
|};
exit 2
)
let print_intra_constraint = Fn.compose (Format.printf "%s\n") Constraint.show
let print_inter_constraint =
Fn.compose (Format.printf "%s\n") H.show_inter_constraint_
let print_solution reader ~validate_parseable : unit =
let summary = Sdt_analysis_summary.calc reader in
Sdt_analysis_summary_jsonl.of_summary summary
|> Sequence.iter ~f:(fun line ->
(if validate_parseable then
let (_ : Summary.nadable list option) =
Sdt_analysis_summary_jsonl.nadables_of_line_exn line
in
());
Format.printf "%s\n" line)
let patches_of_codemod_line line =
let nadables =
line
|> Sdt_analysis_summary_jsonl.nadables_of_line_exn
|> Option.value ~default:[]
in
let patches =
nadables |> List.bind ~f:Sdt_analysis_codemod.patches_of_nadable
in
let ids =
nadables |> List.map ~f:(fun nadable -> nadable.Summary.id |> H.Id.sid_of_t)
in
let target_kind =
nadables
|> List.hd
|> Option.map
~f:
Summary.(
fun nadable ->
match nadable.kind with
| ClassLike _ -> `ClassLike
| Function -> `Function)
|> Option.value ~default:`ClassLike
in
(patches, ids, target_kind)
module StandaloneApi = struct
let dump_persisted ~db_dir =
let reader = H.debug_dump ~db_dir in
H.Read.get_keys reader
|> Sequence.iter ~f:(fun id ->
Format.printf "Intraprocedural constraints for %s\n" @@ H.Id.show id;
H.Read.get_intras reader id
|> Sequence.iter ~f:print_intra_constraint;
Format.printf "Interprocedural constraints for %s\n" @@ H.Id.show id;
H.Read.get_inters reader id
|> Sequence.iter ~f:print_inter_constraint;
Format.print_newline ())
let solve_persisted ~db_dir =
let reader = H.solve ~db_dir in
print_solution reader ~validate_parseable:false
end
let create_handler ~db_dir ~worker_id ctx : Tast_visitor.handler =
exit_if_incorrect_tcopt ctx;
let (_flush, writer) = H.Write.create ~db_dir ~worker_id in
TastHandler.create_handler ctx writer
let fresh_db_dir () =
(* enables test parallelization *)
Format.sprintf
"/tmp/sdt_analysis-%f-%d-%d"
(Unix.gettimeofday ())
(Unix.getpid ())
(Random.int 999)
let parse_command ~command ~verbosity ~on_bad_command =
let command =
match Sdt_analysis_options.parse_command command with
| Some command -> command
| None ->
on_bad_command "invalid SDT analysis mode";
failwith "unreachable"
in
Sdt_analysis_options.mk ~verbosity ~command
let do_tast
(options : Options.t) (ctx : Provider_context.t) (tast : Tast.program) =
let Options.{ command; verbosity } = options in
exit_if_incorrect_tcopt ctx;
let print_decorated_intra_constraints id decorated_constraints =
Format.printf "Intraprocedural Constraints for %s:\n" (H.Id.show id);
decorated_constraints
|> List.sort ~compare:(fun c1 c2 -> Pos.compare c1.hack_pos c2.hack_pos)
|> List.iter ~f:(fun constr ->
Format.printf
"%s\n"
(PP.decorated ~show:Constraint.show ~verbosity constr));
Format.printf "\n%!"
in
let print_intra_constraints id (intra_constraints : Constraint.t list) =
if not @@ List.is_empty intra_constraints then (
Format.printf "Intraprocedural Constraints for %s:\n" (H.Id.show id);
intra_constraints
|> List.sort ~compare:Constraint.compare
|> List.iter ~f:print_intra_constraint;
Format.printf "\n%!"
)
in
let print_decorated_inter_constraints
id (decorated_inter_constraints : H.inter_constraint_ decorated list) =
if not @@ List.is_empty decorated_inter_constraints then begin
Format.printf "Interprocedural Constraints for %s:\n" (H.Id.show id);
decorated_inter_constraints
|> List.sort ~compare:(compare_decorated H.compare_inter_constraint_)
|> List.iter ~f:(fun constr ->
Format.printf
" %s\n"
(PP.decorated ~show:H.show_inter_constraint_ ~verbosity constr));
Format.printf "\n%!"
end
in
let solve () : H.Read.t =
let worker_id = 0 in
let db_dir = fresh_db_dir () in
let generate_constraints () =
let (flush, writer) = H.Write.create ~db_dir ~worker_id in
let tast_handler = TastHandler.create_handler ctx writer in
(Tast_visitor.iter_with [tast_handler])#go ctx tast;
flush ()
in
generate_constraints ();
H.solve ~db_dir
in
match command with
| Options.DumpConstraints ->
IntraWalker.program ctx tast |> IdMap.iter print_decorated_intra_constraints;
InterWalker.program ctx tast |> IdMap.iter print_decorated_inter_constraints
| Options.SolveConstraints ->
let reader = solve () in
let log_intras reader =
H.Read.get_keys reader
|> Sequence.iter ~f:(fun id ->
let intras = H.Read.get_intras reader id |> Sequence.to_list in
print_intra_constraints id intras)
in
if verbosity > 0 then log_intras reader;
print_solution reader ~validate_parseable:true
| Options.Codemod ->
let apply_all nadable_groups =
let ungroup_nadables nadable_groups =
let compare nadable1 nadable2 =
(nadable1, nadable2)
|> Tuple2.map ~f:(fun Summary.{ id; _ } -> id)
|> Tuple2.uncurry H.Id.compare
in
nadable_groups
|> Sequence.to_list
|> List.concat
|> List.dedup_and_sort ~compare
in
let reverse_patches_to_preserve_positions =
let compare patch1 patch2 =
(patch1, patch2)
|> Tuple2.map ~f:ServerRenameTypes.get_pos
|> Tuple2.uncurry (Pos.compare_pos String.compare)
|> ( * ) (-1)
in
List.sort ~compare
in
let apply_patch (contents_opt : string option) patch : string option =
let contents =
match contents_opt with
| Some contents -> contents
| None -> ServerRenameTypes.get_pos patch |> Pos.filename |> Disk.cat
in
let buf = Buffer.create (String.length contents) in
ServerRenameTypes.write_patches_to_buffer buf contents [patch];
Some (Buffer.contents buf)
in
nadable_groups
|> ungroup_nadables
|> List.bind ~f:Sdt_analysis_codemod.patches_of_nadable
|> reverse_patches_to_preserve_positions
|> List.fold ~f:apply_patch ~init:None
|> Option.iter ~f:Format.print_string
in
let reader = solve () in
let summary = Sdt_analysis_summary.calc reader in
apply_all summary.Summary.nadable_groups
let do_ ~command ~verbosity ~on_bad_command =
let opts = parse_command ~command ~on_bad_command ~verbosity in
(fun () -> do_tast opts) |
OCaml Interface | hhvm/hphp/hack/src/sdt_analysis/sdt_analysis.mli | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
val do_ :
command:string ->
verbosity:int ->
on_bad_command:(string -> 'a) ->
unit ->
Provider_context.t ->
Tast.program ->
unit
val default_db_dir : string
val create_handler :
db_dir:string -> worker_id:int -> Provider_context.t -> Tast_visitor.handler
val patches_of_codemod_line :
string ->
ServerRenameTypes.patch list * string list * [ `ClassLike | `Function ]
module StandaloneApi : sig
(* solve constraints from `db_dir` and log the solution to stdout *)
val solve_persisted : db_dir:string -> unit
(* For debugging: dump the constraints from `db_dir` to stdout *)
val dump_persisted : db_dir:string -> unit
end
module ClientCheck : module type of Sdt_analysis_client_check |
OCaml | hhvm/hphp/hack/src/sdt_analysis/sdt_analysis_client_check.ml | (*
* 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.
*
*)
open Hh_prelude
module RemoteLogging = Sdt_analysis_remote_logging
module Reverts = struct
type revert = {
file: string;
contents: string;
}
type t = revert list
let of_patches patches : t =
let open List.Monad_infix in
patches
>>| ServerRenameTypes.get_pos
>>| Pos.filename
|> List.dedup_and_sort ~compare:compare_string
>>| fun file -> { file; contents = Disk.cat file }
let apply : t -> unit =
List.iter ~f:(fun { file; contents } -> Disk.write_file ~file ~contents)
end
let apply_all
~get_error_count
~get_patches
~apply_patches
~path_to_jsonl
~strategy
~log_remotely
~tag =
let remote_logging = RemoteLogging.create ~strategy ~log_remotely ~tag in
let%lwt (baseline_error_count, init_telemetry) = get_error_count () in
let handle_codemod_group codemod_line ~line_index =
let%lwt ((patches, patched_ids, target_kind), telemetry) =
get_patches codemod_line
in
if List.is_empty patches then
Lwt.return telemetry
else begin
let reverts = Reverts.of_patches patches in
apply_patches patches;
let%lwt (error_count, more_telemetry) = get_error_count () in
let telemetry = Telemetry.add telemetry more_telemetry in
let error_count_diff = error_count - baseline_error_count in
assert (error_count_diff > -1);
let should_revert =
match strategy with
| `CodemodSdtCumulative -> error_count_diff > 0
| `CodemodSdtIndependent -> true
in
RemoteLogging.submit_patch_result
remote_logging
~patched_ids
~target_kind
~error_count:error_count_diff
~line_index;
if should_revert then (
Reverts.apply reverts;
let%lwt (error_count, more_telemetry) = get_error_count () in
assert (error_count = baseline_error_count);
Lwt.return @@ Telemetry.add telemetry more_telemetry
) else
Lwt.return telemetry
end
in
let combine_line_results acc line =
let%lwt (telem_acc, line_index) = acc in
let%lwt telem = handle_codemod_group line ~line_index in
Lwt.return (Telemetry.add telem_acc telem, line_index + 1)
in
let%lwt (telemetry, _) =
let init = Lwt.return (init_telemetry, 0) in
In_channel.with_file
path_to_jsonl
~f:(In_channel.fold_lines ~init ~f:combine_line_results)
in
Lwt.return (Exit_status.No_error, telemetry) |
OCaml Interface | hhvm/hphp/hack/src/sdt_analysis/sdt_analysis_client_check.mli | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree.
*
*)
val apply_all :
get_error_count:(unit -> (int * Telemetry.t) Lwt.t) ->
get_patches:
(string ->
((ServerRenameTypes.patch list * string list * [ `ClassLike | `Function ])
* Telemetry.t)
Lwt.t) ->
apply_patches:(ServerRenameTypes.patch list -> 'a) ->
path_to_jsonl:string ->
strategy:[< `CodemodSdtCumulative | `CodemodSdtIndependent ] ->
log_remotely:bool ->
tag:string ->
(Exit_status.t * Telemetry.t) Lwt.t |
OCaml | hhvm/hphp/hack/src/sdt_analysis/sdt_analysis_codemod.ml | (*
* 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.
*
*)
open Hh_prelude
open Sdt_analysis_types
module PositionedTree =
Full_fidelity_syntax_tree.WithSyntax (Full_fidelity_positioned_syntax)
module Syn = Full_fidelity_editable_positioned_syntax
module Refactor = Full_fidelity_refactor
type 'a direction =
| Continue of 'a
| Stop of 'a
let rec fold_syntax ~f ~init node =
match f init node with
| Continue acc ->
Syn.children node
|> List.fold ~init:acc ~f:(fun acc node -> fold_syntax ~f ~init:acc node)
| Stop acc -> acc
let sid_equal s1 s2 = String.equal (Utils.add_ns s1) (Utils.add_ns s2)
let get_function_name_exn node =
let fold name_opt node =
match Syn.syntax node with
| Syn.FunctionDeclarationHeader { function_name; _ } ->
Stop (Some (Syn.text function_name))
| _ -> Continue name_opt
in
fold_syntax ~f:fold ~init:None node |> Option.value_exn
let patches_of_nadable_id ~source ~path id =
let root =
let source_text = Full_fidelity_source_text.make path source in
let positioned_tree = PositionedTree.make source_text in
Full_fidelity_editable_positioned_syntax.from_positioned_syntax
(PositionedTree.root positioned_tree)
in
let collect_patches patches node =
let nad_patch attributes_node =
Refactor.insert_attribute
path
~attribute:Naming_special_names.UserAttributes.uaNoAutoDynamic
~enclosing_node:(Some node)
~attributes_node
|> Option.to_list
in
match (id, Syn.syntax node) with
| ( H.Id.Function sid,
Syn.FunctionDeclaration
{ function_declaration_header; function_attribute_spec; _ } )
when sid_equal sid (get_function_name_exn function_declaration_header) ->
Stop (nad_patch function_attribute_spec @ patches)
| ( H.Id.ClassLike sid,
Syn.ClassishDeclaration { classish_name; classish_attribute; _ } )
when sid_equal sid (Syn.text classish_name) ->
Stop (nad_patch classish_attribute @ patches)
| (_, Syn.ClassishDeclaration _)
| (_, Syn.FunctionDeclaration _) ->
Stop patches
| _ -> Continue patches
in
fold_syntax ~f:collect_patches ~init:[] root
let patches_of_nadable Summary.{ id; path_opt; _ } :
ServerRenameTypes.patch list =
let open Option.Let_syntax in
Option.value ~default:[]
@@ let* path = path_opt in
let+ source = File_provider.get_contents path in
patches_of_nadable_id ~source ~path id |
OCaml Interface | hhvm/hphp/hack/src/sdt_analysis/sdt_analysis_codemod.mli | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Sdt_analysis_types
val patches_of_nadable : Summary.nadable -> ServerRenameTypes.patch list |
OCaml | hhvm/hphp/hack/src/sdt_analysis/sdt_analysis_inter_walker.ml | (*
* 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.
*
*)
open Hh_prelude
open Sdt_analysis_types
module A = Aast
let create_custom_inter ~classish_kind_opt ~hierarchy_for_final_item ~path =
H.CustomInterConstraint
CustomInterConstraint.
{ classish_kind_opt; hierarchy_for_final_item; path_opt = Some path }
let get_hierarchy_for_final_class ctx A.{ c_name = (_, sid); c_final; _ } =
if not c_final then
None
else
let open Option.Monad_infix in
Decl_provider.get_class ctx sid >>| Decl_provider.Class.all_ancestor_names
let reduce_walk_result =
object
inherit
[H.inter_constraint_ decorated WalkResult.t] Tast_visitor.reduce as super
method zero = WalkResult.empty
method plus = WalkResult.( @ )
method! on_class_
env
(A.
{
c_name = (c_pos, sid);
c_extends;
c_uses;
c_implements;
c_reqs;
c_kind;
_;
} as class_) =
let ctx = Tast_env.get_ctx env in
let id = H.Id.ClassLike sid in
let at_inherits acc (_, hint_) =
match hint_ with
| A.Happly ((hack_pos, parent_sid), _hints) ->
let parent_id = H.Id.ClassLike parent_sid in
let constraint_ = H.Inherits parent_id in
let decorated =
{ origin = __LINE__; hack_pos; decorated_data = constraint_ }
in
WalkResult.add_constraint acc id decorated
| _ -> acc
in
let inherited =
c_uses @ c_extends @ c_implements @ List.map ~f:fst c_reqs
in
let wr = List.fold ~init:WalkResult.empty ~f:at_inherits inherited in
let wr = WalkResult.add_id wr id in
let wr =
let hierarchy_for_final_item =
get_hierarchy_for_final_class ctx class_
in
WalkResult.add_constraint
wr
id
{
origin = __LINE__;
hack_pos = c_pos;
decorated_data =
create_custom_inter
~classish_kind_opt:(Some c_kind)
~hierarchy_for_final_item
~path:(Pos.filename c_pos);
}
in
WalkResult.(wr @ super#on_class_ env class_)
method! on_fun_def env (A.{ fd_name = (f_pos, sid); _ } as fd) =
let id = H.Id.Function sid in
let hierarchy_for_final_item =
Some
(* `Some` because a top-level function is morally "final" (they cannot be extended) *)
[]
(* [] because a top-level function doesn't inherit from anything *)
in
let wr =
WalkResult.singleton
id
{
origin = __LINE__;
hack_pos = f_pos;
decorated_data =
create_custom_inter
~classish_kind_opt:None
~hierarchy_for_final_item
~path:(Pos.filename f_pos);
}
in
let wr = WalkResult.add_id wr id in
WalkResult.(wr @ super#on_fun_def env fd)
end
let program (ctx : Provider_context.t) (tast : Tast.program) :
H.inter_constraint_ decorated WalkResult.t =
let def acc def =
let tast_env = Tast_env.def_env ctx def in
WalkResult.(acc @ reduce_walk_result#on_def tast_env def)
in
List.fold ~init:WalkResult.empty ~f:def tast |
OCaml Interface | hhvm/hphp/hack/src/sdt_analysis/sdt_analysis_inter_walker.mli | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Sdt_analysis_types
val program :
Provider_context.t ->
Tast.program ->
H.inter_constraint_ decorated WalkResult.t |
OCaml | hhvm/hphp/hack/src/sdt_analysis/sdt_analysis_intra_walker.ml | (*
* 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.
*
*)
open Hh_prelude
open Sdt_analysis_types
module A = Aast
module T = Typing_defs
module SN = Naming_special_names
module MakeType = Typing_make_type
module Reason = Typing_reason
module TPEnv = Type_parameter_env
let is_under_dynamic_assumptions env =
Tast.is_under_dynamic_assumptions @@ Tast_env.get_check_status env
let mixed = MakeType.mixed Reason.Rnone
let supportdyn_of_mixed = MakeType.supportdyn Reason.Rnone mixed
let remove_supportdyn_of_mixed_upper_bound_from_tparams env =
let typing_env = Tast_env.tast_env_as_typing_env env in
let tpenv = typing_env.Typing_env_types.tpenv in
let remove_upper_bound tpname tpinfo tpenv =
let open Typing_kinding_defs in
let upper_bounds = TySet.remove supportdyn_of_mixed tpinfo.upper_bounds in
let tpinfo = { tpinfo with upper_bounds } in
TPEnv.add ~def_pos:Pos_or_decl.none tpname tpinfo tpenv
in
let tpenv = TPEnv.fold remove_upper_bound tpenv TPEnv.empty in
let typing_env = Typing_env_types.{ typing_env with tpenv } in
Tast_env.typing_env_as_tast_env typing_env
let remove_supportdyn_from_ty ty =
match T.get_node ty with
| T.Tnewtype (c, [ty], _) when String.equal c SN.Classes.cSupportDyn -> ty
| _ -> ty
(** Reverses like type production found in Typing_make_type.locl_like. Useful
for undoing pessimisation. If the analysis stops working all of a sudden,
it might be due to a change to the aforementioned helper. *)
let remove_like_from_ty ty =
match T.get_node ty with
| T.Tunion [dyn_ty; ty] when Typing_defs.is_dynamic dyn_ty -> ty
| _ -> ty
let signature_check decorated_constraint env id params ret =
if is_under_dynamic_assumptions env then
WalkResult.empty
else
let is_supportdyn_of_mixed ty =
Tast_env.is_sub_type env ty supportdyn_of_mixed
in
let fails_formation =
List.exists params ~f:(fun param ->
not @@ is_supportdyn_of_mixed @@ fst param.A.param_type_hint)
|| (not @@ is_supportdyn_of_mixed ret)
in
if fails_formation then
let constraint_ = Lazy.force decorated_constraint in
WalkResult.singleton id constraint_
else
WalkResult.empty
let collect_sdts_body enclosing_def_id ret_ty =
object
inherit [Constraint.t decorated WalkResult.t] Tast_visitor.reduce as super
method zero = WalkResult.empty
method plus = WalkResult.( @ )
method! on_stmt env ((hack_pos, st_) as st) =
let decorated_constraint ~origin =
{ origin; hack_pos; decorated_data = Constraint.NeedsSDT }
in
let walk_result =
match st_ with
| A.Return (Some (e_ty, _, _))
when (not @@ is_under_dynamic_assumptions env)
&& (not @@ Tast_env.is_sub_type env e_ty ret_ty) ->
let constraint_ = decorated_constraint ~origin:__LINE__ in
WalkResult.singleton enclosing_def_id constraint_
| _ -> WalkResult.empty
in
WalkResult.(walk_result @ super#on_stmt env st)
method! on_expr env ((_, e_pos, e_) as e) =
let decorated_constraint ~origin =
{ origin; hack_pos = e_pos; decorated_data = Constraint.NeedsSDT }
in
let walk_result =
match e_ with
| A.Upcast ((ty, _, _), _) -> begin
match T.get_node ty with
| T.Tclass ((_, sid), _, _) ->
let constraint_ = decorated_constraint ~origin:__LINE__ in
WalkResult.singleton (H.Id.ClassLike sid) constraint_
| _ -> WalkResult.empty
end
| A.(Call { func = (base_ty, _, base_exp); args; _ }) ->
let doesnt_subtype (fp, (_, (arg_ty, _, _))) =
not @@ Tast_env.is_sub_type env arg_ty fp.T.fp_type.T.et_type
in
let constraints_of_id id =
let ty = remove_supportdyn_from_ty base_ty in
match T.get_node ty with
| T.Tfun ft ->
let param_arg_pairs =
let open List.Or_unequal_lengths in
let curtailed_params =
List.take ft.T.ft_params (List.length args)
in
match List.zip curtailed_params args with
| Ok pairs -> pairs
| Unequal_lengths -> []
in
if List.exists ~f:doesnt_subtype param_arg_pairs then
let constraint_ = decorated_constraint ~origin:__LINE__ in
WalkResult.singleton id constraint_
else
WalkResult.empty
| _ -> WalkResult.empty
in
begin
match base_exp with
| A.Id (_, sid) -> constraints_of_id (H.Id.Function sid)
| A.Obj_get ((receiver_ty, _, _), _, _, _) -> begin
match T.get_node receiver_ty with
| T.Tclass ((_, sid), _, _) ->
constraints_of_id (H.Id.ClassLike sid)
| _ -> WalkResult.empty
end
| A.Class_const ((_, _, A.CI (_, sid)), _) ->
constraints_of_id (H.Id.ClassLike sid)
| _ -> WalkResult.empty
end
| _ -> WalkResult.empty
in
WalkResult.(walk_result @ super#on_expr env e)
end
let collect_sdts =
object
inherit [Constraint.t decorated WalkResult.t] Tast_visitor.reduce as super
method zero = WalkResult.empty
method plus = WalkResult.( @ )
method! on_method_ env m =
let decorated_constraint ~origin =
let hack_pos = m.A.m_span in
{ origin; hack_pos; decorated_data = Constraint.NeedsSDT }
in
let sid = Tast_env.get_self_id env |> Option.value_exn in
let id = H.Id.ClassLike sid in
let env = remove_supportdyn_of_mixed_upper_bound_from_tparams env in
(* TODO(T147496278): The following like type removal will be too
conservative when we start introducing like type returns explicitly *)
let vanilla_ret_ty = remove_like_from_ty @@ fst m.A.m_ret in
let from_signature_check =
signature_check
(lazy (decorated_constraint ~origin:__LINE__))
env
id
m.A.m_params
vanilla_ret_ty
in
WalkResult.(
from_signature_check
@ super#on_method_ env m
@ (collect_sdts_body id vanilla_ret_ty)#on_method_ env m)
method! on_fun_def env (A.{ fd_name = (_, sid); fd_fun; _ } as fd) =
let decorated_constraint ~origin =
let hack_pos = fd_fun.A.f_span in
{ origin; hack_pos; decorated_data = Constraint.NeedsSDT }
in
let id = H.Id.Function sid in
let from_dynamically_callable =
let is_dynamically_callable =
List.exists ~f:(fun attr ->
String.equal
(snd attr.A.ua_name)
SN.UserAttributes.uaDynamicallyCallable)
in
if is_dynamically_callable fd_fun.A.f_user_attributes then
let constraint_ = decorated_constraint ~origin:__LINE__ in
WalkResult.singleton id constraint_
else
WalkResult.empty
in
let env = remove_supportdyn_of_mixed_upper_bound_from_tparams env in
(* TODO(T147496278): The following like type removal will be too
conservative when we start introducing like type returns explicitly *)
let vanilla_ret_ty = remove_like_from_ty @@ fst fd_fun.A.f_ret in
let from_signature_check =
signature_check
(lazy (decorated_constraint ~origin:__LINE__))
env
id
fd_fun.A.f_params
vanilla_ret_ty
in
WalkResult.(
from_dynamically_callable
@ from_signature_check
@ super#on_fun_def env fd
@ (collect_sdts_body id vanilla_ret_ty)#on_fun_def env fd)
end
let program (ctx : Provider_context.t) (tast : Tast.program) =
let def acc def =
let tast_env = Tast_env.def_env ctx def in
WalkResult.(acc @ collect_sdts#on_def tast_env def)
in
List.fold ~init:WalkResult.empty ~f:def tast |
OCaml Interface | hhvm/hphp/hack/src/sdt_analysis/sdt_analysis_intra_walker.mli | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Sdt_analysis_types
val program :
Provider_context.t -> Tast.program -> Constraint.t decorated WalkResult.t |
OCaml | hhvm/hphp/hack/src/sdt_analysis/sdt_analysis_options.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 Sdt_analysis_types
let parse_command = function
| "dump" -> Some Options.DumpConstraints
| "solve" -> Some Options.SolveConstraints
| "codemod" -> Some Options.Codemod
| _ -> None
let mk ~command ~verbosity = Options.{ command; verbosity } |
OCaml Interface | hhvm/hphp/hack/src/sdt_analysis/sdt_analysis_options.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.
*
*)
open Sdt_analysis_types
val parse_command : string -> Options.command option
val mk : command:Options.command -> verbosity:int -> Options.t |
OCaml | hhvm/hphp/hack/src/sdt_analysis/sdt_analysis_pretty_printer.ml | (*
* 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.
*
*)
open Sdt_analysis_types
let decorated ~verbosity ~show { origin; hack_pos; decorated_data } =
let line = Pos.line hack_pos in
let constraint_ = show decorated_data in
if verbosity > 0 then
Format.asprintf "%4d: %4d: %s" line origin constraint_
else
Format.asprintf "%4d: %s" line constraint_ |
OCaml Interface | hhvm/hphp/hack/src/sdt_analysis/sdt_analysis_pretty_printer.mli | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Sdt_analysis_types
val decorated : verbosity:int -> show:('a -> string) -> 'a decorated -> string |
OCaml | hhvm/hphp/hack/src/sdt_analysis/sdt_analysis_summary.ml | (*
* 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.
*
*)
open Hh_prelude
open Sdt_analysis_types
let is_syntactically_nadable =
Ast_defs.(
function
| Cclass _
| Cinterface
| Ctrait ->
true
| Cenum
| Cenum_class _ ->
false)
(** if the item (function, class, etc.) has no descendants, return Some (id :: ids_of_ancestors), else None *)
let to_hierarchy_for_final_item = function
| H.CustomInterConstraint
CustomInterConstraint.{ hierarchy_for_final_item; _ } ->
hierarchy_for_final_item
| _ -> None
let calc reader : Summary.t =
let to_nadable_single id =
let (default_kind, create_kind) =
match id with
| H.Id.Function _ -> (Summary.Function, (fun _ -> Summary.Function))
| H.Id.ClassLike _ ->
( Summary.ClassLike None,
(fun classish_kind_opt -> Summary.ClassLike classish_kind_opt) )
in
H.Read.get_inters reader id
|> Sequence.find_map ~f:(function
| H.CustomInterConstraint
CustomInterConstraint.{ classish_kind_opt; path_opt; _ } ->
Some Summary.{ id; kind = create_kind classish_kind_opt; path_opt }
| _ -> None)
(* The default is used when there is no CustomInterConstraint,
which can happen for items defined in .hhi files *)
|> Option.value
~default:Summary.{ id; kind = default_kind; path_opt = None }
in
let to_nadable = Sequence.map ~f:to_nadable_single in
let filter_to_syntactically_nadable =
Sequence.filter
~f:
Summary.(
function
| { kind = Function; _ } -> true
| { kind = ClassLike classish_kind_opt; _ } ->
Option.(
classish_kind_opt
>>| is_syntactically_nadable
|> value ~default:false))
in
let filter_to_no_needs_sdt =
Sequence.filter ~f:(fun Summary.{ id; _ } ->
H.Read.get_intras reader id
|> Sequence.for_all ~f:(function Constraint.NeedsSDT -> false))
in
let to_nadable_groups =
Sequence.bind ~f:(fun nadable ->
H.Read.get_inters reader nadable.Summary.id
|> Sequence.filter_map ~f:to_hierarchy_for_final_item
|> Sequence.map
~f:
(List.map ~f:(fun sid -> to_nadable_single (H.Id.ClassLike sid)))
|> Sequence.map ~f:(fun nadables -> nadable :: nadables))
in
let mk_syntactically_nadable () =
H.Read.get_keys reader |> to_nadable |> filter_to_syntactically_nadable
in
let mk_nadable () = mk_syntactically_nadable () |> filter_to_no_needs_sdt in
let nadable_groups = mk_nadable () |> to_nadable_groups in
Summary.
{
id_cnt = H.Read.get_keys reader |> Sequence.length;
syntactically_nadable_cnt = mk_syntactically_nadable () |> Sequence.length;
nadable_cnt = mk_nadable () |> Sequence.length;
nadable_groups;
} |
OCaml Interface | hhvm/hphp/hack/src/sdt_analysis/sdt_analysis_summary.mli | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Sdt_analysis_types
val calc : H.Read.t -> Summary.t |
OCaml | hhvm/hphp/hack/src/sdt_analysis/sdt_analysis_summary_jsonl.ml | (*
* 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.
*
*)
open Hh_prelude
open Sdt_analysis_types
module J = Hh_json
let entry_kind_label = "entry_kind"
let stats_json_of_summary
Summary.
{ id_cnt; syntactically_nadable_cnt; nadable_cnt; nadable_groups = _ } =
J.JSON_Object
[
(entry_kind_label, J.string_ "stats");
("id_cnt", J.int_ id_cnt);
("syntactically_nadable_cnt", J.int_ syntactically_nadable_cnt);
("nadable_cnt", J.int_ nadable_cnt);
]
module Nad : sig
val json_of_nadables : Summary.nadable list -> J.json
val nadables_of_json_exn : J.json -> Summary.nadable list option
end = struct
module Names = struct
let add_no_auto_dynamic_attr = "add_no_auto_dynamic_attr"
let items = "items"
let sid = "sid"
let kind = "kind"
let function_ = "function"
let path = "path"
end
let extract_exn access_result =
access_result |> Result.ok |> Option.value_exn |> fst
let extract_opt access_result =
access_result |> Result.ok |> Option.map ~f:fst
let json_obj_of_nadable Summary.{ id; kind; path_opt } =
let kind_str =
match kind with
| Summary.Function -> Names.function_
| Summary.ClassLike classish_kind_opt ->
classish_kind_opt
|> Option.sexp_of_t sexp_of_classish_kind
|> Sexp.to_string
in
let j_string_of_path = Fn.compose J.string_ Relative_path.suffix in
J.JSON_Object
[
(Names.sid, J.string_ @@ H.Id.sid_of_t id);
(Names.kind, J.string_ kind_str);
(Names.path, J.opt_ j_string_of_path path_opt);
]
let json_of_nadables nadables =
let nadables_arr = J.array_ json_obj_of_nadable nadables in
J.JSON_Object
[
(entry_kind_label, J.string_ Names.add_no_auto_dynamic_attr);
(Names.items, nadables_arr);
]
let nadable_of_json_obj_exn obj =
let sid = J.Access.get_string Names.sid (obj, []) |> extract_exn in
let path_opt =
J.Access.get_string Names.path (obj, [])
|> extract_opt
|> Option.map ~f:(fun suffix -> Relative_path.from_root ~suffix)
in
let kind_string = J.Access.get_string Names.kind (obj, []) |> extract_exn in
if String.equal kind_string Names.function_ then
let id = H.Id.Function sid in
let kind = Summary.Function in
Summary.{ id; kind; path_opt }
else
let classish_kind_opt =
kind_string |> Sexp.of_string |> Option.t_of_sexp classish_kind_of_sexp
in
let id = H.Id.ClassLike sid in
let kind = Summary.ClassLike classish_kind_opt in
Summary.{ id; kind; path_opt }
let nadables_of_json_exn obj =
match J.Access.get_string entry_kind_label (obj, []) |> extract_exn with
| key when String.equal key Names.add_no_auto_dynamic_attr ->
J.Access.get_array Names.items (obj, [])
|> extract_exn
|> List.map ~f:nadable_of_json_obj_exn
|> Option.some
| _ -> None
end
let of_summary summary : string Sequence.t =
let to_string = J.json_to_string ~sort_keys:true ~pretty:false in
let stats =
stats_json_of_summary summary |> to_string |> Sequence.singleton
in
let groups =
summary.Summary.nadable_groups
|> Sequence.map ~f:Nad.json_of_nadables
|> Sequence.map ~f:to_string
in
Sequence.append stats groups
let nadables_of_line_exn s =
let obj = J.json_of_string ~strict:true s in
Nad.nadables_of_json_exn obj |
OCaml Interface | hhvm/hphp/hack/src/sdt_analysis/sdt_analysis_summary_jsonl.mli | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open Sdt_analysis_types
val of_summary : Summary.t -> string Sequence.t
(**
raises if given an invalid summary json line
returns `None` if valid summary json line that isn't a nadable list (such as `stats`)
otherwise
`Some` lists of items that must have `__NoAutoDynamic` added atomically
for every item in the list
*)
val nadables_of_line_exn : string -> Summary.nadable list option |
OCaml | hhvm/hphp/hack/src/sdt_analysis/sdt_analysis_tast_handler.ml | (*
* 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.
*
*)
open Hh_prelude
open Sdt_analysis_types
module IntraWalker = Sdt_analysis_intra_walker
module InterWalker = Sdt_analysis_inter_walker
let should_visit = Fn.non Tast_env.is_hhi
let strip_constraints { decorated_data; _ } = decorated_data
let create_handler ctx writer =
let write_ids_and_inters id (cs : H.inter_constraint_ decorated list) =
H.Write.add_id writer id;
cs
|> List.map ~f:strip_constraints
|> List.iter ~f:(H.Write.add_inter writer id)
in
let write_intras id decorated_intras =
decorated_intras
|> List.map ~f:strip_constraints
|> List.iter ~f:(H.Write.add_intra writer id)
in
let at_defs defs =
IdMap.iter write_ids_and_inters @@ InterWalker.program ctx defs;
IdMap.iter write_intras @@ IntraWalker.program ctx defs
in
object
inherit Tast_visitor.handler_base
method! at_class_ env def =
if should_visit env then at_defs [Aast_defs.Class def]
method! at_fun_def env def =
if should_visit env then at_defs [Aast_defs.Fun def]
end |
OCaml Interface | hhvm/hphp/hack/src/sdt_analysis/sdt_analysis_tast_handler.mli | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Sdt_analysis_types
val create_handler : Provider_context.t -> H.Write.t -> Tast_visitor.handler |
OCaml | hhvm/hphp/hack/src/sdt_analysis/sdt_analysis_types.ml | (*
* 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.
*
*)
open Hh_prelude
module Options = struct
type command =
| DumpConstraints
| SolveConstraints
| Codemod
type t = {
command: command;
verbosity: int;
}
end
module Constraint = struct
type t = NeedsSDT [@@deriving eq, hash, ord, show { with_path = false }]
end
type abstraction = Ast_defs.abstraction =
| Concrete
| Abstract
[@@deriving eq, hash, ord, sexp, show { with_path = false }]
type classish_kind = Ast_defs.classish_kind =
| Cclass of abstraction (** Kind for `class` and `abstract class` *)
| Cinterface (** Kind for `interface` *)
| Ctrait (** Kind for `trait` *)
| Cenum (** Kind for `enum` *)
| Cenum_class of abstraction
[@@deriving eq, hash, ord, sexp, show { with_path = false }]
module Relative_path = struct
include Relative_path
let hash_fold_t hash_state path =
String.hash_fold_t hash_state (Relative_path.storage_to_string path)
end
module CustomInterConstraint = struct
type t = {
classish_kind_opt: classish_kind option;
hierarchy_for_final_item: string list option;
path_opt: Relative_path.t option;
}
[@@deriving eq, hash, ord, show { with_path = false }]
end
type 'a decorated = {
hack_pos: Pos.t;
origin: int;
decorated_data: 'a;
}
[@@deriving ord]
module H = Hips2.Make (struct
type constraint_ = Constraint.t
[@@deriving eq, hash, show { with_path = false }]
type custom_inter_constraint_ = CustomInterConstraint.t
[@@deriving eq, hash, ord, show { with_path = false }]
end)
module IdMap = Caml.Map.Make (H.Id)
module WalkResult = struct
type 'a t = 'a list IdMap.t
let ( @ ) t1 t2 = IdMap.union (fun _k v1 v2 -> Some (v1 @ v2)) t1 t2
let empty = IdMap.empty
let add_constraint t id constraint_ =
let merge = function
| None -> Some [constraint_]
| Some constraints -> Some (constraint_ :: constraints)
in
IdMap.update id merge t
let add_id t id =
let merge = function
| None -> Some []
| Some _ as some -> some
in
IdMap.update id merge t
let singleton id constraint_ = add_constraint empty id constraint_
end
module Summary = struct
type nadable_kind =
| ClassLike of classish_kind option
| Function
type nadable = {
id: H.Id.t;
kind: nadable_kind;
path_opt: Relative_path.t option;
}
type t = {
id_cnt: int;
syntactically_nadable_cnt: int;
nadable_cnt: int;
nadable_groups: nadable list Sequence.t;
}
end |
OCaml Interface | hhvm/hphp/hack/src/sdt_analysis/sdt_analysis_types.mli | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
module Options : sig
type command =
| DumpConstraints
(** print constraints for a single file without solving *)
| SolveConstraints (** generate and solve constraints for a single file *)
| Codemod
type t = {
command: command;
verbosity: int;
}
end
module Constraint : sig
type t = NeedsSDT [@@deriving ord, show]
end
type abstraction = Ast_defs.abstraction =
| Concrete
| Abstract
[@@deriving eq, ord, sexp, show { with_path = false }]
type classish_kind = Ast_defs.classish_kind =
| Cclass of abstraction (** Kind for `class` and `abstract class` *)
| Cinterface (** Kind for `interface` *)
| Ctrait (** Kind for `trait` *)
| Cenum (** Kind for `enum` *)
| Cenum_class of abstraction
[@@deriving eq, ord, sexp, show { with_path = false }]
module CustomInterConstraint : sig
(** Facts that help us summarize results. *)
type t = {
classish_kind_opt: classish_kind option;
(** In `CustomInterConstraint`s, classish_kind is always `None` for functions *)
hierarchy_for_final_item: string list option;
(**
`Some []` indicates something with no parents or descendents, such as a top-level function or final class with no `extends` or `implements`.
`Some [c1, c2]` indicates a final class that inherits transitively from c1 and c2.
Anything else is `None`
*)
path_opt: Relative_path.t option;
}
end
type 'a decorated = {
hack_pos: Pos.t;
origin: int;
decorated_data: 'a;
}
[@@deriving ord]
module H :
Hips2.T
with type intra_constraint_ = Constraint.t
and type custom_inter_constraint_ = CustomInterConstraint.t
module IdMap : Caml.Map.S with type key := H.Id.t
module WalkResult : sig
type 'a t = 'a list IdMap.t
val ( @ ) : 'a t -> 'a t -> 'a t
val empty : 'a t
val add_constraint : 'a t -> H.Id.t -> 'a -> 'a t
val add_id : 'a t -> H.Id.t -> 'a t
val singleton : H.Id.t -> 'a -> 'a t
end
module Summary : sig
type nadable_kind =
| ClassLike of classish_kind option
(** classish_kind of `None` indicates unknown, which can happen for definitions in hhis *)
| Function
type nadable = {
id: H.Id.t;
kind: nadable_kind;
path_opt: Relative_path.t option;
}
type t = {
id_cnt: int;
(* count of functions and class-like things *)
syntactically_nadable_cnt: int;
(* count of things where the <<__NoAutoDynamic>> attribute is syntactically allowed *)
nadable_cnt: int;
(* count of things the analysis thinks can have <<__NoAutoDynamic>> added *)
nadable_groups: nadable list Sequence.t;
(* Sequence of things the analysis thinks can have <<__NoAutoDynamic>> added. Items in the same list should be modified together. *)
}
end |
hhvm/hphp/hack/src/sdt_analysis/sdt_analysis_exe/dune | (executable
(name sdt_analysis_exe)
(flags
(:standard -linkall))
(link_flags
(:standard
(:include ../../dune_config/ld-opts.sexp)))
(libraries
sdt_analysis
sys_utils
default_injector_config
)
(preprocess
(pps ppx_deriving.std))) |
|
OCaml | hhvm/hphp/hack/src/sdt_analysis/sdt_analysis_exe/sdt_analysis_exe.ml | (*
* 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.
*
*)
open Hh_prelude
let solve_persisted_usage =
"solve the constraints at `Sdt_analysis.default_db_dir` and log them to stdout"
let dump_persisted_usage =
"dump the constraints at `Sdt_analysis.default_db_dir` to stdout"
let usage =
Format.sprintf
{|
"USAGE":
--solve-persisted %s
--dump-persisted %s
|}
solve_persisted_usage
dump_persisted_usage
let exit_with_usage () =
Format.eprintf "incorrect command line arguments\n%s" usage;
Exit.exit Exit_status.Input_error
type mode =
| SolvePersisted
| DumpPersisted
let () =
let mode = ref None in
let set_mode m =
match !mode with
| None -> mode := Some m
| Some _ -> exit_with_usage ()
in
let args =
[
( "--solve-persisted",
Arg.Unit (fun () -> set_mode SolvePersisted),
solve_persisted_usage );
( "--dump-persisted",
Arg.Unit (fun () -> set_mode DumpPersisted),
dump_persisted_usage );
]
in
Arg.parse
args
(fun s ->
Printf.printf "Unrecognized argument: '%s'\n" s;
Exit.exit Exit_status.Input_error)
usage;
match !mode with
| None -> exit_with_usage ()
| Some mode ->
(match mode with
| SolvePersisted ->
Sdt_analysis.StandaloneApi.solve_persisted
~db_dir:Sdt_analysis.default_db_dir
| DumpPersisted ->
Sdt_analysis.StandaloneApi.dump_persisted
~db_dir:Sdt_analysis.default_db_dir) |
OCaml Interface | hhvm/hphp/hack/src/sdt_analysis/sdt_analysis_exe/sdt_analysis_exe.mli | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
(* intentionally blank *) |
hhvm/hphp/hack/src/sdt_analysis/sdt_analysis_remote_logging/dune | (* -*- tuareg -*- *)
let library_entry name suffix =
Printf.sprintf
"(library
(name %s)
(wrapped false)
(modules)
(libraries %s_%s))" name name suffix
let fb_entry name =
library_entry name "fb"
let stubs_entry name =
library_entry name "stubs"
let entry is_fb name =
if is_fb then
fb_entry name
else
stubs_entry name
let () =
(* test presence of fb subfolder *)
let current_dir = Sys.getcwd () in
(* we are in src/sdt_analysis/sdt_analysis_remote_logging, locate src/facebook *)
let src_dir = Filename.dirname @@ Filename.dirname current_dir in
let fb_dir = Filename.concat src_dir "facebook" in
(* locate src/facebook/dune *)
let fb_dune = Filename.concat fb_dir "dune" in
let is_fb = Sys.file_exists fb_dune in
(* un-comment the next line and build to check whether `facebook/dune` is found: *)
(* Format.printf "debug: is_fb? %b" is_fb; *)
let sdt_analysis_remote_logging = entry is_fb "sdt_analysis_remote_logging" in
Jbuild_plugin.V1.send sdt_analysis_remote_logging |
|
OCaml | hhvm/hphp/hack/src/search/classMethodSearch.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
let query_class_methods
(ctx : Provider_context.t) (class_name : string) (method_query : string) :
SearchUtils.result =
Option.Monad_infix.(
let method_query = String.lowercase method_query in
let matches_query method_name =
if String.length method_query > 0 then
let method_name = String.lowercase method_name in
String.is_substring ~substring:method_query method_name
else
true
in
Naming_provider.get_class_path ctx class_name
>>= (fun file ->
Ast_provider.find_class_in_file ctx file class_name ~full:false)
>>| (fun class_ -> class_.Aast.c_methods)
>>| List.filter_map ~f:(fun m ->
let (pos, name) = m.Aast.m_name in
if matches_query name then
Some
SearchUtils.
{
name;
pos = Pos.to_absolute pos;
result_type = SearchTypes.SI_ClassMethod;
}
else
None)
|> Option.value ~default:[]) |
OCaml | hhvm/hphp/hack/src/search/customSearchService.ml | (*
* Copyright (c) 2019, Facebook, Inc.
* All rights reserved.
*)
(* Put any initialization code necessary here *)
let initialize ~sienv = sienv
(* If you have a way of listing namespaces, put it here *)
let fetch_namespaces ~sienv:_ = []
(* Use the custom search service to find symbols by autocomplete context *)
let search_symbols
~sienv_ref:_ ~query_text:_ ~max_results:_ ~context:_ ~kind_filter:_ =
([], SearchTypes.Complete)
let find_refs ~sienv_ref:_ ~action:_ ~max_results:_ = None |
hhvm/hphp/hack/src/search/dune | (library
(name search_core)
(wrapped false)
(modules localSearchService symbolIndexCore)
(libraries
ast
decl_provider
facts
file_info
heap_shared_mem
index_builder
logging
naming_global
parser_options
pos))
(library
(name search)
(wrapped false)
(modules
classMethodSearch
customSearchService
namespaceSearchService
sqliteSearchService
symbolIndex)
(libraries
ast
ast_provider
decl_provider
facts
file_info
full_fidelity
future
glean_options
index_builder
logging
naming
naming_global
procs_procs
pos
search_core
search_utils
sqlite3
state_loader
trie))
(library
(name glean)
(wrapped false)
(modules
glean glean_autocomplete_query)
) |
|
OCaml | hhvm/hphp/hack/src/search/glean.ml | (*
* 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.
*
*)
type handle = unit
let initialize ~reponame:_ ~prev_init_time:_ = failwith "not implemented"
let fetch_namespaces _ = failwith "not implemented"
let query_autocomplete _ ~query_text:_ ~max_results:_ ~context:_ ~kind_filter:_
=
failwith "not implemented"
let query_refs _ ~action:_ ~max_results:_ = failwith "not implemented" |
OCaml | hhvm/hphp/hack/src/search/glean_autocomplete_query.ml | (*
* 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.
*
*)
let make_symbols_query ~prefix:_ ~context:_ ~kind_filter:_ = ""
let make_refs_query ~action:_ = "" |
OCaml | hhvm/hphp/hack/src/search/localSearchService.ml | (*
* Copyright (c) 2019, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open SearchUtils
open SearchTypes
(* How many locally changed files are in this env? *)
let count_local_fileinfos ~(sienv : si_env) : int =
Relative_path.Map.cardinal sienv.lss_fullitems
(* Relative paths sometimes produce doubled-up slashes, as in
* "/path/to/root//subpath/file". When we extract the suffix
* from a relative_path.t, clear out any preceding slash. *)
let strip_first_char char s =
if String.length s = 0 || not (Char.equal s.[0] char) then
s
else
String.sub s ~pos:1 ~len:(String.length s - 1)
(* Determine a tombstone for a file path *)
let get_tombstone (path : Relative_path.t) : int64 =
let rel_path_str = Relative_path.suffix path in
let fixed_path_str = strip_first_char '/' rel_path_str in
let path_hash = SharedMemHash.hash_string fixed_path_str in
path_hash
(* This function is used if fast-facts-parser fails to scan the file *)
let convert_fileinfo_to_contents
~(ctx : Provider_context.t)
~(sienv : SearchUtils.si_env)
~(info : FileInfo.t)
~(filepath : string) : SearchUtils.si_capture =
let append_item
(kind : SearchTypes.si_kind)
(acc : SearchUtils.si_capture)
(name : string) =
let (sif_kind, sif_is_abstract, sif_is_final) =
(* FFP produces more detailed information about classes
* than we can get from FileInfo.t objects. Since this function is only
* called when a file has been modified locally, it's safe to call
* decl_provider - this information has already been cached. *)
if is_si_class kind && sienv.sie_resolve_local_decl then
match Decl_provider.get_class ctx name with
| Some cls ->
let is_final = Decl_provider.Class.final cls in
let is_abstract = Decl_provider.Class.abstract cls in
let real_kind = Decl_provider.Class.kind cls in
let converted_kind =
match real_kind with
| Ast_defs.Cclass _ -> SI_Class
| Ast_defs.Cinterface -> SI_Interface
| Ast_defs.Ctrait -> SI_Trait
| Ast_defs.Cenum_class _
| Ast_defs.Cenum ->
SI_Enum
in
(converted_kind, is_abstract, is_final)
| None -> (kind, false, false)
else
(kind, false, false)
in
let item =
{
(* Only strip Hack namespaces. XHP must have a preceding colon *)
sif_name = Utils.strip_ns name;
sif_kind;
sif_filepath = filepath;
sif_is_abstract;
sif_is_final;
}
in
item :: acc
in
let fold_full
(kind : SearchTypes.si_kind)
(acc : SearchUtils.si_capture)
(list : FileInfo.id list) : SearchUtils.si_capture =
List.fold list ~init:acc ~f:(fun inside_acc (_, name, _) ->
append_item kind inside_acc name)
in
let acc = fold_full SI_Function [] info.FileInfo.funs in
let acc = fold_full SI_Class acc info.FileInfo.classes in
let acc = fold_full SI_Typedef acc info.FileInfo.typedefs in
let acc = fold_full SI_GlobalConstant acc info.FileInfo.consts in
acc
(* Update files when they were discovered *)
let update_file
~(ctx : Provider_context.t)
~(sienv : si_env)
~(path : Relative_path.t)
~(info : FileInfo.t) : si_env =
let tombstone = get_tombstone path in
let filepath = Relative_path.suffix path in
let contents =
try
let full_filename = Relative_path.to_absolute path in
if Sys.file_exists full_filename then
let popt = Provider_context.get_popt ctx in
let namespace_map = ParserOptions.auto_namespace_map popt in
let contents = IndexBuilder.parse_one_file ~namespace_map ~path in
if List.length contents = 0 then
convert_fileinfo_to_contents ~ctx ~sienv ~info ~filepath
else
contents
else
convert_fileinfo_to_contents ~ctx ~sienv ~info ~filepath
with
| _ -> convert_fileinfo_to_contents ~ctx ~sienv ~info ~filepath
in
{
sienv with
lss_fullitems =
Relative_path.Map.add sienv.lss_fullitems ~key:path ~data:contents;
lss_tombstones = Relative_path.Set.add sienv.lss_tombstones path;
lss_tombstone_hashes =
Tombstone_set.add sienv.lss_tombstone_hashes tombstone;
}
let update_file_from_addenda
~(sienv : si_env)
~(path : Relative_path.t)
~(addenda : SearchTypes.si_addendum list) : si_env =
let tombstone = get_tombstone path in
let filepath = Relative_path.suffix path in
let contents : SearchUtils.si_capture =
List.map addenda ~f:(fun addendum ->
{
sif_name = addendum.sia_name;
sif_kind = addendum.sia_kind;
sif_filepath = filepath;
sif_is_abstract = addendum.sia_is_abstract;
sif_is_final = addendum.sia_is_final;
})
in
{
sienv with
lss_fullitems =
Relative_path.Map.add sienv.lss_fullitems ~key:path ~data:contents;
lss_tombstones = Relative_path.Set.add sienv.lss_tombstones path;
lss_tombstone_hashes =
Tombstone_set.add sienv.lss_tombstone_hashes tombstone;
}
(* Remove files from local when they are deleted *)
let remove_file ~(sienv : si_env) ~(path : Relative_path.t) : si_env =
let tombstone = get_tombstone path in
{
sienv with
lss_fullitems = Relative_path.Map.remove sienv.lss_fullitems path;
lss_tombstones = Relative_path.Set.add sienv.lss_tombstones path;
lss_tombstone_hashes =
Tombstone_set.add sienv.lss_tombstone_hashes tombstone;
}
(* Exception we use to short-circuit out of a loop if we find enough results.
* May be worth rewriting this in the future to use `fold_until` rather than
* exceptions *)
exception BreakOutOfScan of si_item list
(* Search local changes for symbols matching this prefix *)
let search_local_symbols
~(sienv : si_env)
~(query_text : string)
~(max_results : int)
~(context : autocomplete_type)
~(kind_filter : si_kind option) : si_item list =
(* case insensitive search, must include namespace, escaped for regex *)
let query_text_regex_case_insensitive =
Str.regexp_case_fold (Str.quote query_text)
in
(* case insensitive search, break out if max results reached *)
let check_symbol_and_add_to_accumulator_and_break_if_max_reached
~(acc : si_item list)
~(symbol : si_fullitem)
~(context : autocomplete_type)
~(kind_filter : si_kind option)
~(path : Relative_path.t) : si_item list =
let is_valid_match =
match (context, kind_filter) with
| (Actype, _) -> SearchTypes.valid_for_actype symbol.SearchUtils.sif_kind
| (Acnew, _) ->
SearchTypes.valid_for_acnew symbol.SearchUtils.sif_kind
&& not symbol.SearchUtils.sif_is_abstract
| (Acid, _) -> SearchTypes.valid_for_acid symbol.SearchUtils.sif_kind
| (Actrait_only, _) -> is_si_trait symbol.sif_kind
| (Ac_workspace_symbol, Some kind_match) ->
equal_si_kind symbol.sif_kind kind_match
| (Ac_workspace_symbol, None) -> true
in
if
is_valid_match
&& Str.string_partial_match
query_text_regex_case_insensitive
symbol.sif_name
0
then
(* Only strip Hack namespaces. XHP must have a preceding colon *)
let fullname = Utils.strip_ns symbol.sif_name in
let acc_new =
{
si_name = fullname;
si_kind = symbol.sif_kind;
si_file = SI_Path path;
si_fullname = fullname;
}
:: acc
in
if List.length acc_new >= max_results then
raise (BreakOutOfScan acc_new)
else
acc_new
else
acc
in
try
let acc =
Relative_path.Map.fold
sienv.lss_fullitems
~init:[]
~f:(fun path fullitems acc ->
let matches =
List.fold fullitems ~init:[] ~f:(fun acc symbol ->
check_symbol_and_add_to_accumulator_and_break_if_max_reached
~acc
~symbol
~context
~kind_filter
~path)
in
List.append acc matches)
in
acc
with
| BreakOutOfScan acc -> acc
(* Filter the results to extract any dead objects *)
let extract_dead_results ~(sienv : SearchUtils.si_env) ~(results : si_item list)
: si_item list =
List.filter results ~f:(fun item ->
match item.si_file with
| SearchTypes.SI_Path path ->
not (Relative_path.Set.mem sienv.lss_tombstones path)
| SearchTypes.SI_Filehash hash_str ->
let hash = Int64.of_string hash_str in
not (Tombstone_set.mem sienv.lss_tombstone_hashes hash)) |
OCaml Interface | hhvm/hphp/hack/src/search/localSearchService.mli | (*
* 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.
*
*)
(* Size of local tracking environment *)
val count_local_fileinfos : sienv:SearchUtils.si_env -> int
(* SLOWER: FileInfo.t objects don't include all the data we need, so this function has to re-parse the file. Use [update_file_from_addenda] when possible. *)
val update_file :
ctx:Provider_context.t ->
sienv:SearchUtils.si_env ->
path:Relative_path.t ->
info:FileInfo.t ->
SearchUtils.si_env
(* FASTER: Updates symbol index from [si_addendum] generated from a previous parse of the file. *)
val update_file_from_addenda :
sienv:SearchUtils.si_env ->
path:Relative_path.t ->
addenda:SearchTypes.si_addendum list ->
SearchUtils.si_env
(* Returns an updated env clearing out tracked information for a file *)
val remove_file :
sienv:SearchUtils.si_env -> path:Relative_path.t -> SearchUtils.si_env
(* Search through locally tracked symbols *)
val search_local_symbols :
sienv:SearchUtils.si_env ->
query_text:string ->
max_results:int ->
context:SearchTypes.autocomplete_type ->
kind_filter:SearchTypes.si_kind option ->
SearchTypes.si_item list
(* Filter out anything that's been removed locally *)
val extract_dead_results :
sienv:SearchUtils.si_env ->
results:SearchTypes.si_item list ->
SearchTypes.si_item list |
OCaml | hhvm/hphp/hack/src/search/namespaceSearchService.ml | (*
* Copyright (c) 2019, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open SearchUtils
open SearchTypes
(* Register a namespace *)
let register_namespace ~(sienv : si_env) ~(namespace : string) : unit =
let elem_list = String.split_on_char '\\' namespace in
let _ =
Core.List.fold
elem_list
~init:sienv.nss_root_namespace
~f:(fun current_node leaf_name ->
(* Ignore extra backslashes *)
if leaf_name <> "" then (
(* Check to see if this leaf exists within the current node *)
let leaf_lc = String.lowercase_ascii leaf_name in
match Hashtbl.find_opt current_node.nss_children leaf_lc with
| Some matching_leaf -> matching_leaf
| None ->
let new_node =
{
nss_name = leaf_name;
nss_full_namespace =
(if current_node.nss_full_namespace = "\\" then
"\\" ^ leaf_name
else
current_node.nss_full_namespace ^ "\\" ^ leaf_name);
nss_children = Hashtbl.create 0;
}
in
Hashtbl.add current_node.nss_children leaf_lc new_node;
new_node
) else
current_node)
in
()
exception Match_not_found
(* Find the namespace that matches this prefix. Might throw {!Match_not_found} *)
let find_exact_match ~(sienv : si_env) ~(namespace : string) : nss_node =
(* If we're at the root namespace the answer is easy *)
if namespace = "" || namespace = "\\" then
sienv.nss_root_namespace
else
let elem_list =
String.split_on_char '\\' (String.lowercase_ascii namespace)
in
Core.List.fold
elem_list
~init:sienv.nss_root_namespace
~f:(fun current_node leaf_name ->
(* Check to see if this leaf exists within the current node *)
if leaf_name <> "" then
match Hashtbl.find_opt current_node.nss_children leaf_name with
| Some matching_leaf -> matching_leaf
| None -> raise Match_not_found
else
current_node)
(* Produce a list of results for the current node *)
let get_matches_for_node (node : nss_node) : si_item list =
Hashtbl.fold
(fun _key value acc ->
{
si_name = value.nss_name;
si_kind = SI_Namespace;
si_file = SI_Filehash "0";
si_fullname = value.nss_name;
}
:: acc)
node.nss_children
[]
(* Find all namespaces that match this prefix *)
let find_matching_namespaces ~(sienv : si_env) ~(query_text : string) :
si_item list =
(* Trivial case *)
if query_text = "" then
[]
(* Special case - just give root namespace only *)
else if query_text = "\\" then
get_matches_for_node sienv.nss_root_namespace
(* Normal case, search for matches *)
else
let elem_list =
String.split_on_char '\\' (String.lowercase_ascii query_text)
in
let current_node = ref sienv.nss_root_namespace in
let reached_end = ref false in
let matches = ref [] in
Core.List.iter elem_list ~f:(fun leaf_name ->
(* If we've already reached the end of matches, offer no more *)
if !reached_end then
matches := []
else if leaf_name <> "" then
(* Check to see if this leaf exists within the current node *)
match Hashtbl.find_opt !current_node.nss_children leaf_name with
| Some matching_leaf ->
current_node := matching_leaf;
matches := get_matches_for_node matching_leaf
| None ->
matches := [];
Hashtbl.iter
(fun key _ ->
if Core.String.is_substring key ~substring:leaf_name then
let node = Hashtbl.find !current_node.nss_children key in
matches :=
{
si_name = node.nss_name;
si_kind = SI_Namespace;
si_file = SI_Filehash "0";
si_fullname = node.nss_name;
}
:: !matches)
!current_node.nss_children;
reached_end := true);
(* Now take those matches and return them as a list *)
!matches
(*
* Register a namespace alias, represented as a shortcut in the tree.
* The alias will share the hashtbl of its target, so future namespaces
* should appear in both places.
*)
let register_alias ~(sienv : si_env) ~(alias : string) ~(target : string) : unit
=
try
(* First find the target and make sure there's only one *)
register_namespace ~sienv ~namespace:target;
let target_node = find_exact_match ~sienv ~namespace:target in
(* Now assert that the alias cannot have a backslash in it *)
let (source_ns, name) = Utils.split_ns_from_name alias in
let source = find_exact_match ~sienv ~namespace:source_ns in
(* Register this alias at the root *)
let new_node =
{
nss_name = name;
nss_full_namespace = target_node.nss_full_namespace;
nss_children = target_node.nss_children;
}
in
Hashtbl.add source.nss_children (String.lowercase_ascii name) new_node
with
| Match_not_found ->
Hh_logger.log
"Unable to register namespace map for [%s] -> [%s]"
alias
target |
OCaml | hhvm/hphp/hack/src/search/sqliteSearchService.ml | (*
* Copyright (c) 2019, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open SearchUtils
open SearchTypes
open Sqlite_utils
(* SQL statements used by the autocomplete system *)
let sql_select_symbols_by_kind =
"SELECT name, kind, filename_hash FROM symbols WHERE name LIKE ? ESCAPE '\\' AND kind = ? LIMIT ?"
let sql_select_acid =
"SELECT name, kind, filename_hash FROM symbols WHERE name LIKE ? ESCAPE '\\' AND valid_for_acid = 1 LIMIT ?"
let sql_select_acnew =
"SELECT name, kind, filename_hash FROM symbols WHERE name LIKE ? ESCAPE '\\' AND valid_for_acnew = 1 LIMIT ?"
let sql_select_actype =
"SELECT name, kind, filename_hash FROM symbols WHERE name LIKE ? ESCAPE '\\' AND valid_for_actype = 1 LIMIT ?"
(* This syntax means that we add back in the root namespace prefix.
* It allows us to use LIKE "%\Foo%" to find both "\FooClass" and "\HH\Lib\FooTrait".
* This feature should be removed if we decide to add back in the original backslash when generating
* symbol indexes.
*
* In SQLite, `||` is the string concatentation operator; it is not the logical OR operator you
* might be expecting.
*)
let sql_select_namespaced_symbols =
"SELECT name, kind, filename_hash FROM symbols WHERE ('\\' || name) LIKE ? ESCAPE '\\' LIMIT ?"
let sql_check_alive = "SELECT name FROM symbols LIMIT 1"
let sql_select_namespaces = "SELECT namespace FROM namespaces"
(* Add escape characters when necessary *)
let sqlite_escape_str (str : string) : string =
String.fold str ~init:"" ~f:(fun acc char ->
match char with
| '%' -> acc ^ "\\%"
| '_' -> acc ^ "\\_"
| '\\' -> acc ^ "\\\\"
| _ -> acc ^ String.make 1 char)
(* Determine the correct filename to use for the db_path or build it *)
let find_or_build_sqlite_file
(workers : MultiWorker.worker list option)
(savedstate_file_opt : string option)
(namespace_map : (string * string) list)
~(silent : bool) : string =
match savedstate_file_opt with
| Some path -> path
| None ->
let repo_path = Relative_path.path_of_prefix Relative_path.Root in
let tempfilename = Caml.Filename.temp_file "symbolindex" ".db" in
if not silent then
Hh_logger.log
"Generating [%s] from repository [%s]"
tempfilename
repo_path;
let ctxt =
{
IndexBuilderTypes.repo_folder = repo_path;
sqlite_filename = Some tempfilename;
hhi_root_folder = Some (Hhi.get_hhi_root ());
namespace_map;
silent;
}
in
IndexBuilder.go ctxt workers;
tempfilename
(*
* Ensure the database is available.
* If the database is stored remotely, this will trigger it being
* pulled local. If no database is specified, this will generate
* it.
*)
let initialize
~(sienv : si_env)
~(workers : MultiWorker.worker list option)
~(savedstate_file_opt : string option)
~(namespace_map : (string * string) list) : si_env =
(* Find the database and open it *)
let db_path =
find_or_build_sqlite_file
~silent:sienv.sie_quiet_mode
workers
savedstate_file_opt
namespace_map
in
let db = Sqlite3.db_open db_path in
(* Report that the database has been loaded *)
if not sienv.sie_quiet_mode then
Hh_logger.log "Initialized symbol index sqlite: [%s]" db_path;
(* Here's the updated environment *)
{ sienv with sql_symbolindex_db = ref (Some db) }
let is_row = function
| Sqlite3.Rc.ROW -> true
| _ -> false
(* Single function for reading results from an executed statement *)
let read_si_results (stmt : Sqlite3.stmt) : si_item list =
let results = ref [] in
while is_row (Sqlite3.step stmt) do
let name = Sqlite3.Data.to_string (Sqlite3.column stmt 0) in
let name = Option.value_exn name in
let kindnum = to_int (Sqlite3.column stmt 1) in
let kind = int_to_kind kindnum in
let filehash = to_int64 (Sqlite3.column stmt 2) in
results :=
{
si_name = name;
si_kind = kind;
si_file = SI_Filehash (Int64.to_string filehash);
si_fullname = name;
}
:: !results
done;
!results
let check_rc (sienv : si_env) =
check_rc (Option.value_exn !(sienv.sql_symbolindex_db))
(* Find all symbols matching a specific kind *)
let search_symbols_by_kind
~(sienv : si_env)
~(query_text : string)
~(max_results : int)
~(kind_filter : si_kind) : si_item list =
let stmt =
prepare_or_reset_statement
sienv.sql_symbolindex_db
sienv.sql_select_symbols_by_kind_stmt
sql_select_symbols_by_kind
in
Sqlite3.bind stmt 1 (Sqlite3.Data.TEXT (query_text ^ "%")) |> check_rc sienv;
Sqlite3.bind
stmt
2
(Sqlite3.Data.INT (Int64.of_int (kind_to_int kind_filter)))
|> check_rc sienv;
Sqlite3.bind stmt 3 (Sqlite3.Data.INT (Int64.of_int max_results))
|> check_rc sienv;
read_si_results stmt
(* Symbol search for symbols containing a string. *)
let search_namespaced_symbols
~(sienv : si_env) ~(query_text : string) ~(max_results : int) : si_item list
=
let stmt =
prepare_or_reset_statement
sienv.sql_symbolindex_db
sienv.sql_select_namespaced_symbols_stmt
sql_select_namespaced_symbols
in
Sqlite3.bind stmt 1 (Sqlite3.Data.TEXT ("%\\\\" ^ query_text ^ "%"))
|> check_rc sienv;
Sqlite3.bind stmt 2 (Sqlite3.Data.INT (Int64.of_int max_results))
|> check_rc sienv;
read_si_results stmt
(* Symbol search for symbols valid in ACID context *)
let search_acid ~(sienv : si_env) ~(query_text : string) ~(max_results : int) :
si_item list =
let stmt =
prepare_or_reset_statement
sienv.sql_symbolindex_db
sienv.sql_select_acid_stmt
sql_select_acid
in
Sqlite3.bind stmt 1 (Sqlite3.Data.TEXT (query_text ^ "%")) |> check_rc sienv;
Sqlite3.bind stmt 2 (Sqlite3.Data.INT (Int64.of_int max_results))
|> check_rc sienv;
read_si_results stmt
(* Symbol search for symbols valid in ACNEW context *)
let search_acnew ~(sienv : si_env) ~(query_text : string) ~(max_results : int) :
si_item list =
let stmt =
prepare_or_reset_statement
sienv.sql_symbolindex_db
sienv.sql_select_acnew_stmt
sql_select_acnew
in
Sqlite3.bind stmt 1 (Sqlite3.Data.TEXT (query_text ^ "%")) |> check_rc sienv;
Sqlite3.bind stmt 2 (Sqlite3.Data.INT (Int64.of_int max_results))
|> check_rc sienv;
read_si_results stmt
(* Symbol search for symbols valid in ACTYPE context *)
let search_actype ~(sienv : si_env) ~(query_text : string) ~(max_results : int)
: si_item list =
let stmt =
prepare_or_reset_statement
sienv.sql_symbolindex_db
sienv.sql_select_actype_stmt
sql_select_actype
in
Sqlite3.bind stmt 1 (Sqlite3.Data.TEXT (query_text ^ "%")) |> check_rc sienv;
Sqlite3.bind stmt 2 (Sqlite3.Data.INT (Int64.of_int max_results))
|> check_rc sienv;
read_si_results stmt
(* Main entry point *)
let sqlite_search
~(sienv : si_env)
~(query_text : string)
~(max_results : int)
~(context : autocomplete_type)
~(kind_filter : SearchTypes.si_kind option) : si_item list =
let query_text = sqlite_escape_str query_text in
match (context, kind_filter) with
| (Acid, _) -> search_acid ~sienv ~query_text ~max_results
| (Acnew, _) -> search_acnew ~sienv ~query_text ~max_results
| (Actype, _) -> search_actype ~sienv ~query_text ~max_results
| (Actrait_only, _) ->
search_symbols_by_kind ~sienv ~query_text ~max_results ~kind_filter:SI_Trait
| (Ac_workspace_symbol, _) ->
search_namespaced_symbols ~sienv ~query_text ~max_results
(* Fetch all known namespaces from the database *)
let fetch_namespaces ~(sienv : si_env) : string list =
let stmt =
prepare_or_reset_statement
sienv.sql_symbolindex_db
sienv.sql_select_namespaces_stmt
sql_select_namespaces
in
let namespace_list = ref [] in
while is_row (Sqlite3.step stmt) do
let name = Sqlite3.Data.to_string (Sqlite3.column stmt 0) in
let name = Option.value_exn name in
namespace_list := name :: !namespace_list
done;
!namespace_list |
OCaml | hhvm/hphp/hack/src/search/symbolIndex.ml | (*
* Copyright (c) 2019, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open SearchUtils
open SearchTypes
(* Set the currently selected search provider *)
let initialize
~(gleanopt : GleanOptions.t)
~(namespace_map : (string * string) list)
~(provider_name : string)
~(quiet : bool)
~(savedstate_file_opt : string option)
~(workers : MultiWorker.worker list option) : si_env =
(* Create the object *)
let sienv =
{
SearchUtils.default_si_env with
sie_provider = SearchUtils.provider_of_string provider_name;
sie_quiet_mode = quiet;
glean_reponame = GleanOptions.reponame gleanopt;
}
in
(* Basic initialization *)
let sienv =
match sienv.sie_provider with
| SqliteIndex ->
SqliteSearchService.initialize
~sienv
~workers
~savedstate_file_opt
~namespace_map
| CustomIndex -> CustomSearchService.initialize ~sienv
| NoIndex
| MockIndex _
| LocalIndex ->
sienv
in
(* Fetch namespaces from provider-specific query *)
let namespace_list =
match sienv.sie_provider with
| SqliteIndex -> SqliteSearchService.fetch_namespaces ~sienv
| CustomIndex -> CustomSearchService.fetch_namespaces ~sienv
| NoIndex
| MockIndex _
| LocalIndex ->
[]
in
(* Register all namespaces *)
List.iter namespace_list ~f:(fun namespace ->
NamespaceSearchService.register_namespace ~sienv ~namespace);
(* Add namespace aliases from the .hhconfig file *)
List.iter namespace_map ~f:(fun (alias, target) ->
NamespaceSearchService.register_alias ~sienv ~alias ~target);
(* Here's the initialized environment *)
if not sienv.sie_quiet_mode then
Hh_logger.log
"Search provider set to [%s] based on configuration value [%s]"
(SearchUtils.descriptive_name_of_provider sienv.sie_provider)
provider_name;
sienv
let mock ~on_find =
{
SearchUtils.default_si_env with
sie_provider = SearchUtils.MockIndex { mock_on_find = on_find };
sie_quiet_mode = true;
}
(*
* Core search function
* - Uses both global and local indexes
* - Can search for specific kinds or all kinds
* - Goal is to route ALL searches through one function for consistency
*)
let find_matching_symbols
~(sienv_ref : si_env ref)
~(query_text : string)
~(max_results : int)
~(context : autocomplete_type)
~(kind_filter : si_kind option) :
SearchTypes.si_item list * SearchTypes.si_complete =
let is_complete = ref SearchTypes.Complete in
(*
* Nuclide often sends this exact request to verify that HH is working.
* Let's capture it and avoid doing unnecessary work.
*)
if String.equal query_text "this_is_just_to_check_liveness_of_hh_server" then
( [
{
si_name = "Yes_hh_server_is_alive";
si_kind = SI_Unknown;
si_file = SI_Filehash "0";
si_fullname = "";
};
],
!is_complete )
else
(* Potential namespace matches always show up first *)
let namespace_results =
match context with
| Ac_workspace_symbol -> []
| Acid
| Acnew
| Actype
| Actrait_only ->
NamespaceSearchService.find_matching_namespaces
~sienv:!sienv_ref
~query_text
in
(* The local index captures symbols in files that have been changed on disk.
* Search it first for matches, then search global and add any elements
* that we haven't seen before *)
let local_results =
match !sienv_ref.sie_provider with
| NoIndex
| MockIndex _ ->
[]
| CustomIndex
| LocalIndex
| SqliteIndex ->
LocalSearchService.search_local_symbols
~sienv:!sienv_ref
~query_text
~max_results
~context
~kind_filter
in
(* Next search globals *)
let global_results =
match !sienv_ref.sie_provider with
| CustomIndex ->
let (r, custom_is_complete) =
CustomSearchService.search_symbols
~sienv_ref
~query_text
~max_results
~context
~kind_filter
in
is_complete := custom_is_complete;
LocalSearchService.extract_dead_results ~sienv:!sienv_ref ~results:r
| SqliteIndex ->
let results =
SqliteSearchService.sqlite_search
~sienv:!sienv_ref
~query_text
~max_results
~context
~kind_filter
in
is_complete :=
if List.length results < max_results then
SearchTypes.Complete
else
SearchTypes.Incomplete;
LocalSearchService.extract_dead_results ~sienv:!sienv_ref ~results
| MockIndex { mock_on_find } ->
mock_on_find ~query_text ~context ~kind_filter
| LocalIndex
| NoIndex ->
[]
in
(* Merge and deduplicate results *)
let all_results = List.append local_results global_results in
let dedup_results =
List.sort
~compare:(fun a b -> String.compare b.si_name a.si_name)
all_results
in
(* Strip namespace already typed from the results *)
let (ns, _) = Utils.split_ns_from_name query_text in
let clean_results =
if String.equal ns "" || String.equal ns "\\" then
dedup_results
else
List.map dedup_results ~f:(fun s ->
{ s with si_name = String_utils.lstrip s.si_name ns })
in
(* Namespaces should always appear first *)
let results = List.append namespace_results clean_results in
(List.take results max_results, !is_complete)
let find_refs
~(sienv_ref : si_env ref)
~(action : SearchTypes.Find_refs.action)
~(max_results : int) : Relative_path.t list option =
match !sienv_ref.sie_provider with
| NoIndex
| LocalIndex
| SqliteIndex
| MockIndex _ ->
None
| CustomIndex -> CustomSearchService.find_refs ~sienv_ref ~action ~max_results |
OCaml Interface | hhvm/hphp/hack/src/search/symbolIndex.mli | (*
* 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.
*
*)
(** Get or set the currently selected search provider *)
val initialize :
gleanopt:GleanOptions.t ->
namespace_map:(string * string) list ->
provider_name:string ->
quiet:bool ->
savedstate_file_opt:string option ->
workers:MultiWorker.worker list option ->
SearchUtils.si_env
(** Constructs+returns a mockable symbol-index *)
val mock :
on_find:
(query_text:string ->
context:SearchTypes.autocomplete_type ->
kind_filter:SearchTypes.si_kind option ->
SearchTypes.si_item list) ->
SearchUtils.si_env
(** This is the proper search function everyone should use *)
val find_matching_symbols :
sienv_ref:SearchUtils.si_env ref ->
query_text:string ->
max_results:int ->
context:SearchTypes.autocomplete_type ->
kind_filter:SearchTypes.si_kind option ->
SearchTypes.si_item list * SearchTypes.si_complete
(** Does an approximate search for find-all-refs candidates.
If it returns None, then this functionality isn't available from this provider,
or isn't working for some reason.
If it returns Some, then these are best-guess candidates to check. *)
val find_refs :
sienv_ref:SearchUtils.si_env ref ->
action:SearchTypes.Find_refs.action ->
max_results:int ->
Relative_path.t list option |
OCaml | hhvm/hphp/hack/src/search/symbolIndexCore.ml | (*
* Copyright (c) 2019, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
open Hh_prelude
open SearchUtils
open SearchTypes
(* Log information about calls to the symbol index service *)
let log_symbol_index_search
~(sienv : si_env)
~(query_text : string)
~(max_results : int)
~(results : int)
~(kind_filter : si_kind option)
~(start_time : float)
~(caller : string) : unit =
(* In quiet mode we don't log anything to either scuba or console *)
if sienv.sie_quiet_mode then
()
else
(* Calculate duration *)
let end_time = Unix.gettimeofday () in
let duration = end_time -. start_time in
(* Clean up strings *)
let kind_filter_str =
match kind_filter with
| None -> "None"
| Some kind -> show_si_kind kind
in
let search_provider = descriptive_name_of_provider sienv.sie_provider in
(* Send information to remote logging system *)
if sienv.sie_log_timings then
Hh_logger.log
"[symbolindex] Search [%s] for [%s] found %d results in [%0.3f]"
search_provider
query_text
results
duration;
HackEventLogger.search_symbol_index
~query_text
~max_results
~results
~kind_filter:kind_filter_str
~duration
~caller
~search_provider
(*
* This method is called when the typechecker has finished re-checking a file,
* or when the saved-state is fully loaded. Any system that needs to cache
* this information should capture it here.
*)
let update_files
~(ctx : Provider_context.t)
~(sienv : si_env)
~(paths : (Relative_path.t * FileInfo.t * file_source) list) : si_env =
match sienv.sie_provider with
| NoIndex
| MockIndex _ ->
sienv
| CustomIndex
| LocalIndex
| SqliteIndex ->
List.fold paths ~init:sienv ~f:(fun sienv (path, info, detector) ->
match detector with
| SearchUtils.TypeChecker ->
LocalSearchService.update_file ~ctx ~sienv ~path ~info
| _ -> sienv)
type paths_with_addenda =
(Relative_path.t * SearchTypes.si_addendum list * SearchUtils.file_source)
list
let update_from_addenda
~(sienv : si_env) ~(paths_with_addenda : paths_with_addenda) : si_env =
match sienv.sie_provider with
| NoIndex
| MockIndex _ ->
sienv
| CustomIndex
| LocalIndex
| SqliteIndex ->
List.fold
paths_with_addenda
~init:sienv
~f:(fun sienv (path, addenda, detector) ->
match detector with
| SearchUtils.TypeChecker ->
LocalSearchService.update_file_from_addenda ~sienv ~path ~addenda
| _ -> sienv)
(*
* This method is called when the typechecker is about to re-check a file.
* Any local caches should be cleared of values for this file.
*)
let remove_files ~(sienv : SearchUtils.si_env) ~(paths : Relative_path.Set.t) :
si_env =
match sienv.sie_provider with
| NoIndex
| MockIndex _ ->
sienv
| CustomIndex
| LocalIndex
| SqliteIndex ->
Relative_path.Set.fold paths ~init:sienv ~f:(fun path sienv ->
LocalSearchService.remove_file ~sienv ~path)
(* Fetch best available position information for a symbol *)
let get_position_for_symbol
(ctx : Provider_context.t) (symbol : string) (kind : si_kind) :
(Relative_path.t * int * int) option =
(* Symbols can only be found if they are properly namespaced.
* Even XHP classes must start with a backslash. *)
let name_with_ns = Utils.add_ns symbol in
let helper get_pos resolve_pos =
(* get_pos only gives us filename+nametype *)
let fileinfo_pos = get_pos ctx name_with_ns in
(* we have to resolve that into a proper position *)
Option.map fileinfo_pos ~f:(fun fileinfo_pos ->
let (pos, _) = resolve_pos ctx (fileinfo_pos, name_with_ns) in
let relpath = FileInfo.get_pos_filename fileinfo_pos in
let (line, col, _) = Pos.info_pos pos in
(relpath, line, col))
in
match kind with
| SI_XHP
| SI_Interface
| SI_Trait
| SI_Enum
| SI_Typedef
| SI_Class
| SI_Constructor ->
helper Naming_provider.get_type_pos Naming_global.GEnv.get_type_full_pos
| SI_Function ->
helper Naming_provider.get_fun_pos Naming_global.GEnv.get_fun_full_pos
| SI_GlobalConstant ->
helper Naming_provider.get_const_pos Naming_global.GEnv.get_const_full_pos
(* Items below this are not global symbols and cannot be 'position'ed *)
| SI_Unknown
| SI_Namespace
| SI_ClassMethod
| SI_Literal
| SI_ClassConstant
| SI_Property
| SI_LocalVariable
| SI_Keyword
| SI_Mixed ->
None
let absolute_none = Pos.none |> Pos.to_absolute
(* Shortcut to use the above method to get an absolute pos *)
let get_pos_for_item_opt (ctx : Provider_context.t) (item : si_item) :
Pos.absolute option =
let result = get_position_for_symbol ctx item.si_fullname item.si_kind in
match result with
| None -> None
| Some (relpath, line, col) ->
let symbol_len = String.length item.si_fullname in
let pos =
Pos.make_from_lnum_bol_offset
~pos_file:relpath
~pos_start:(line, 1, col)
~pos_end:(line, 1, col + symbol_len)
in
Some (Pos.to_absolute pos)
(* Shortcut to use the above method to get an absolute pos *)
let get_pos_for_item (ctx : Provider_context.t) (item : si_item) : Pos.absolute
=
let result = get_pos_for_item_opt ctx item in
match result with
| None -> absolute_none
| Some pos -> pos |
OCaml Interface | hhvm/hphp/hack/src/search/symbolIndexCore.mli | (*
* 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.
*
*)
(* Log diagnostics for usage of autocomplete and symbol search *)
val log_symbol_index_search :
sienv:SearchUtils.si_env ->
query_text:string ->
max_results:int ->
results:int ->
kind_filter:SearchTypes.si_kind option ->
start_time:float ->
caller:string ->
unit
(* SLOWER: Update from a FileInfo.t object. May need to do extra work to parse
* into a usable format. *)
val update_files :
ctx:Provider_context.t ->
sienv:SearchUtils.si_env ->
paths:(Relative_path.t * FileInfo.t * SearchUtils.file_source) list ->
SearchUtils.si_env
type paths_with_addenda =
(Relative_path.t * SearchTypes.si_addendum list * SearchUtils.file_source)
list
(* FASTER: update from addenda directly *)
val update_from_addenda :
sienv:SearchUtils.si_env ->
paths_with_addenda:paths_with_addenda ->
SearchUtils.si_env
(* Notify the search service that certain files have been removed locally *)
val remove_files :
sienv:SearchUtils.si_env -> paths:Relative_path.Set.t -> SearchUtils.si_env
(* Identify the position of an item *)
val get_position_for_symbol :
Provider_context.t ->
string ->
SearchTypes.si_kind ->
(Relative_path.t * int * int) option
(* Take an item and produce a position, or none if it cannot be found *)
val get_pos_for_item_opt :
Provider_context.t -> SearchTypes.si_item -> Pos.absolute option
(* Take an item and produce a position, or a fake one if it cannot be found *)
val get_pos_for_item : Provider_context.t -> SearchTypes.si_item -> Pos.absolute |
hhvm/hphp/hack/src/search/utils/dune | (library
(name search_utils)
(modules searchUtils)
(wrapped false)
(libraries ast file_info glean pos search_types sqlite3)
(preprocess
(pps ppx_deriving.std)))
(library
(name search_types)
(modules searchTypes)
(wrapped false)
(libraries relative_path)
(preprocess
(pps ppx_deriving.std))) |
|
OCaml | hhvm/hphp/hack/src/search/utils/searchTypes.ml | (*
* 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.
*
*)
type si_kind =
| SI_Class
| SI_Interface
| SI_Enum
| SI_Trait
| SI_Unknown
| SI_Mixed
| SI_Function
| SI_Typedef
| SI_GlobalConstant
| SI_XHP
| SI_Namespace
| SI_ClassMethod
| SI_Literal
| SI_ClassConstant
| SI_Property
| SI_LocalVariable
| SI_Keyword
| SI_Constructor
[@@deriving eq, show { with_path = false }]
type si_addendum = {
sia_name: string;
(** This is expected not to contain the leading namespace backslash! See [Utils.strip_ns]. *)
sia_kind: si_kind;
sia_is_abstract: bool;
sia_is_final: bool;
}
[@@deriving show]
(** This is used as a filter on top-level symbol searches, for both autocomplete and symbol-search. *)
type autocomplete_type =
| Acid
(** satisfies [valid_for_acid], e.g. in autocomplete contexts like `|` at the start of a statement *)
| Acnew
(** satisfies [valid_for_acnew] AND isn't an abstract class, e.g. in autocomplete contexts like `$x = new |` *)
| Actype
(** satisfies [valid_for_actype], e.g. in autocomplete contexts like `Foo<|` *)
| Actrait_only
(** is [SI_Trait], e.g. in autocomplete contexts like `uses |` *)
| Ac_workspace_symbol (** isn't [SI_Namespace]; repo-wide symbol search *)
[@@deriving eq, show { with_path = false }]
type si_file =
| SI_Filehash of string (** string represent Int64 *)
| SI_Path of Relative_path.t
type si_item = {
si_name: string;
si_kind: si_kind;
si_file: si_file;
(** needed so that local file deletes can "tombstone" the item *)
si_fullname: string;
}
type si_complete =
| Complete
| Incomplete
[@@deriving eq]
(**
* Convert the enum to an integer whose value will not change accidentally.
*
* Although [@@deriving] would be a very ocaml-ish way to solve this same
* problem, we would run the risk that anyone who edits the code to reorder
* list of si_kinds, perhaps by adding something new in its correct
* alphabetic order, would cause unexpected autocomplete behavior due to
* mismatches between the [@@deriving] ordinal values and the integers
* stored in sqlite.
*)
let kind_to_int (kind : si_kind) : int =
match kind with
| SI_Class -> 1
| SI_Interface -> 2
| SI_Enum -> 3
| SI_Trait -> 4
| SI_Unknown -> 5
| SI_Mixed -> 6
| SI_Function -> 7
| SI_Typedef -> 8
| SI_GlobalConstant -> 9
| SI_XHP -> 10
| SI_Namespace -> 11
| SI_ClassMethod -> 12
| SI_Literal -> 13
| SI_ClassConstant -> 14
| SI_Property -> 15
| SI_LocalVariable -> 16
| SI_Keyword -> 17
| SI_Constructor -> 18
(** Convert an integer back to an enum *)
let int_to_kind (kind_num : int) : si_kind =
match kind_num with
| 1 -> SI_Class
| 2 -> SI_Interface
| 3 -> SI_Enum
| 4 -> SI_Trait
| 5 -> SI_Unknown
| 6 -> SI_Mixed
| 7 -> SI_Function
| 8 -> SI_Typedef
| 9 -> SI_GlobalConstant
| 10 -> SI_XHP
| 11 -> SI_Namespace
| 12 -> SI_ClassMethod
| 13 -> SI_Literal
| 14 -> SI_ClassConstant
| 15 -> SI_Property
| 16 -> SI_LocalVariable
| 17 -> SI_Keyword
| 18 -> SI_Constructor
| _ -> SI_Unknown
(** ACID represents a statement. Everything other than interfaces are valid *)
let valid_for_acid (kind : si_kind) : bool =
match kind with
| SI_Mixed
| SI_Unknown
| SI_Interface ->
false
| _ -> true
(** ACTYPE represents a type definition that can be passed as a parameter *)
let valid_for_actype (kind : si_kind) : bool =
match kind with
| SI_Mixed
| SI_Unknown
| SI_Trait
| SI_Function
| SI_GlobalConstant ->
false
| _ -> true
(** ACNEW represents instantiation of an object. (Caller should also verify that it's not abstract.) *)
let valid_for_acnew (kind : si_kind) : bool =
match kind with
| SI_Class
| SI_Typedef
| SI_XHP ->
true
| _ -> false
module Find_refs = struct
type member =
| Method of string
| Property of string
| Class_const of string
| Typeconst of string
[@@deriving show]
type action =
| Class of string
(** When user does find-all-refs on Foo::f or self::f or parent::f, it produces `Class "Foo"`
and passes this to serverFindRefs. As expected, it will find all references to the class Foo,
including self:: and parent:: references.
Class is used for all typelikes -- typedefs, enums, enum classes, classes, interfaces, traits *)
| ExplicitClass of string
(** When user does rename of Foo to Bar, then serverRename produces `ExplicitClass "Foo"`
and passes this to serverFindRefs. This will only find the explicit references to the class Foo,
not including self:: and parent::, since they shouldn't be renamed. *)
| Member of string * member
| Function of string
| GConst of string
| LocalVar of {
filename: Relative_path.t;
file_content: string;
line: int;
char: int;
}
[@@deriving show]
end |
OCaml | hhvm/hphp/hack/src/search/utils/searchUtils.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 Reordered_argument_collections
open SearchTypes
type mock_on_find =
query_text:string ->
context:SearchTypes.autocomplete_type ->
kind_filter:SearchTypes.si_kind option ->
SearchTypes.si_item list
(* Known search providers *)
type search_provider =
| CustomIndex
| NoIndex
| MockIndex of { mock_on_find: mock_on_find [@opaque] }
(** used in testing and debugging *)
| SqliteIndex
| LocalIndex
[@@deriving show]
(* Convert a string to a provider *)
let provider_of_string (provider_str : string) : search_provider =
match provider_str with
| "SqliteIndex" -> SqliteIndex
| "NoIndex" -> NoIndex
| "MockIndex" -> failwith ("unsupported provider " ^ provider_str)
| "CustomIndex" -> CustomIndex
| "LocalIndex" -> LocalIndex
| _ -> SqliteIndex
(* Convert a string to a human readable description of the provider *)
let descriptive_name_of_provider (provider : search_provider) : string =
match provider with
| CustomIndex -> "Custom symbol index"
| NoIndex -> "Symbol index disabled"
| MockIndex _ -> "Mock index"
| SqliteIndex -> "Sqlite"
| LocalIndex -> "Local file index only"
(* Shared Search code between Fuzzy and Trie based searches *)
module type Searchable = sig
type t
val fuzzy_types : t list
val compare_result_type : t -> t -> int
end
(* The results we'll return to the client *)
type ('a, 'b) term = {
name: string;
pos: 'a;
result_type: 'b;
}
let to_absolute t = { t with pos = Pos.to_absolute t.pos }
let is_si_class = function
| SI_Class -> true
| _ -> false
let is_si_trait = function
| SI_Trait -> true
| _ -> false
(* Individual result object as known by the autocomplete system *)
type symbol = (Pos.absolute, si_kind) term
(* Used by some legacy APIs *)
type legacy_symbol = (FileInfo.pos, si_kind) term
(* Collected results as known by the autocomplete system *)
type result = symbol list
(* Determine the best "ty" string for an item *)
let kind_to_string (kind : si_kind) : string =
match kind with
| SI_Class -> "class"
| SI_Interface -> "interface"
| SI_Enum -> "enum"
| SI_Trait -> "trait"
| SI_Unknown -> "unknown"
| SI_Mixed -> "mixed"
| SI_Function -> "function"
| SI_Typedef -> "type alias"
| SI_GlobalConstant -> "constant"
| SI_XHP -> "XHP class"
| SI_Namespace -> "namespace"
| SI_ClassMethod -> "class method"
| SI_Literal -> "literal"
| SI_ClassConstant -> "class constant"
| SI_Property -> "class property"
| SI_LocalVariable -> "local variable"
| SI_Keyword -> "keyword"
| SI_Constructor -> "constructor"
(* Sigh, yet another string to enum conversion *)
let string_to_kind (type_ : string) : si_kind option =
match type_ with
| "class" -> Some SI_Class
| "interface" -> Some SI_Interface
| "enum" -> Some SI_Enum
| "trait" -> Some SI_Trait
| "unknown" -> Some SI_Unknown
| "mixed" -> Some SI_Mixed
| "function" -> Some SI_Function
(* Compatibility with strings used by Hack Search Service as well as ty_string *)
| "typedef"
| "type alias" ->
Some SI_Typedef
| "constant" -> Some SI_GlobalConstant
| "xhp" -> Some SI_XHP
| "namespace" -> Some SI_Namespace
| "class method" -> Some SI_ClassMethod
| "literal" -> Some SI_Literal
| "class constant" -> Some SI_ClassConstant
| "property"
| "class property" ->
Some SI_Property
| "local variable" -> Some SI_LocalVariable
| "keyword" -> Some SI_Keyword
| "constructor" -> Some SI_Constructor
| _ -> None
(* More complete representation of a symbol index item *)
type si_fullitem = {
(* NOTE: this is expected to have its leading backslash stripped. See [Utils.strip_ns] *)
sif_name: string;
sif_kind: si_kind;
sif_filepath: string;
sif_is_abstract: bool;
sif_is_final: bool;
}
(* Fully captured information from a scan of WWW *)
type si_capture = si_fullitem list
(* Which system notified us of a file changed? *)
type file_source =
| Init
| TypeChecker
(* Keep track of file hash tombstones *)
module Tombstone = struct
type t = int64
let compare = Int64.compare
let to_string = Int64.to_string
end
module Tombstone_set = struct
include Reordered_argument_set (Set.Make (Tombstone))
end
(* Information about one leaf in the namespace tree *)
type nss_node = {
(* The name of just this leaf *)
nss_name: string;
(* The full name including all parent trunks above this leaf *)
nss_full_namespace: string;
(* A hashtable of all leaf elements below this branch *)
nss_children: (string, nss_node) Hashtbl.t;
}
(* Context information for the current symbol index *)
type si_env = {
sie_provider: search_provider;
sie_quiet_mode: bool;
sie_fuzzy_search_mode: bool ref;
sie_log_timings: bool;
(*
* Setting the "resolve" parameters to true slows down autocomplete
* but increases precision for answers.
*
* sie_resolve_signatures: When a result appears in autocomplete,
* look up the full declaration and include parameters. Uses extra
* memory.
*
* sie_resolve_positions: When a result appears in autocomplete,
* look up the exact position of the symbol from the naming table.
* Slows down autocomplete.
*
* sie_resolve_local_decl: When a file changes on disk, the local
* search index digs through its decls and saves exact class
* information. Uses more memory and slows down processing of
* changed files.
*)
sie_resolve_signatures: bool;
sie_resolve_positions: bool;
sie_resolve_local_decl: bool;
(* MockIndex *)
mock_on_find: mock_on_find;
(* LocalSearchService *)
lss_fullitems: si_capture Relative_path.Map.t;
lss_tombstones: Relative_path.Set.t;
(** files that have been locally modified *)
lss_tombstone_hashes: Tombstone_set.t;
(** hashes of suffixes of files that have been locally modified -
this only exists for compatibility with stores (sql, www.autocomplete)
that use filehashes, and won't be needed once we move solely
to stures that use paths (local, www.hack.light). *)
(* SqliteSearchService *)
sql_symbolindex_db: Sqlite3.db option ref;
sql_select_symbols_stmt: Sqlite3.stmt option ref;
sql_select_symbols_by_kind_stmt: Sqlite3.stmt option ref;
sql_select_acid_stmt: Sqlite3.stmt option ref;
sql_select_acnew_stmt: Sqlite3.stmt option ref;
sql_select_actype_stmt: Sqlite3.stmt option ref;
sql_select_namespaces_stmt: Sqlite3.stmt option ref;
sql_select_namespaced_symbols_stmt: Sqlite3.stmt option ref;
(* NamespaceSearchService *)
nss_root_namespace: nss_node;
(* CustomSearchService *)
glean_reponame: string;
glean_handle: Glean.handle option;
}
(* Default provider with no functionality *)
let default_si_env =
{
sie_provider = NoIndex;
sie_quiet_mode = false;
sie_fuzzy_search_mode = ref false;
sie_log_timings = false;
sie_resolve_signatures = false;
sie_resolve_positions = false;
sie_resolve_local_decl = false;
(* MockIndex *)
mock_on_find = (fun ~query_text:_ ~context:_ ~kind_filter:_ -> []);
(* LocalSearchService *)
lss_fullitems = Relative_path.Map.empty;
lss_tombstones = Relative_path.Set.empty;
lss_tombstone_hashes = Tombstone_set.empty;
(* SqliteSearchService *)
sql_symbolindex_db = ref None;
sql_select_symbols_stmt = ref None;
sql_select_symbols_by_kind_stmt = ref None;
sql_select_acid_stmt = ref None;
sql_select_acnew_stmt = ref None;
sql_select_actype_stmt = ref None;
sql_select_namespaces_stmt = ref None;
sql_select_namespaced_symbols_stmt = ref None;
(* NamespaceSearchService *)
nss_root_namespace =
{
nss_name = "\\";
nss_full_namespace = "\\";
nss_children = Hashtbl.create 0;
};
(* CustomSearchService *)
glean_reponame = "";
glean_handle = None;
}
(* Default provider, but no logging *)
let quiet_si_env =
{ default_si_env with sie_quiet_mode = true; sie_log_timings = false } |
OCaml | hhvm/hphp/hack/src/server/autocompleteService.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
open Typing_defs
open Typing_defs_core
open Utils
open String_utils
open SearchUtils
open SearchTypes
include AutocompleteTypes
open Tast
module Phase = Typing_phase
module Cls = Decl_provider.Class
module Syntax = Full_fidelity_positioned_syntax
module Trivia = Full_fidelity_positioned_trivia
(* When autocompletion is called, we insert an autocomplete token
"AUTO332" at the position of the cursor. For example, if the user
has this in their IDE, with | showing their cursor:
$x = new Fo|
We see the following TAST:
$x = new FoAUTO332
This allows us to walk the syntax tree and identify the position
of the cursor by looking for names containing "AUTO332". *)
let autocomplete_items : autocomplete_item list ref = ref []
let autocomplete_is_complete : bool ref = ref true
(*
* Take the results, look them up, and add file position information.
*)
let add_position_to_results
(ctx : Provider_context.t) (raw_results : SearchTypes.si_item list) :
SearchUtils.result =
SearchUtils.(
List.filter_map raw_results ~f:(fun r ->
match SymbolIndexCore.get_pos_for_item_opt ctx r with
| Some pos ->
Some { name = r.si_fullname; pos; result_type = r.si_kind }
| None -> None))
let max_results = 100
let auto_complete_for_global = ref ""
let strip_suffix s =
String.sub
s
~pos:0
~len:(String.length s - AutocompleteTypes.autocomplete_token_length)
let strip_supportdyn_decl ty =
match Typing_defs.get_node ty with
| Tapply ((_, n), [ty])
when String.equal n Naming_special_names.Classes.cSupportDyn ->
ty
| _ -> ty
let strip_like_decl ty =
match get_node ty with
| Tlike ty -> ty
| _ -> ty
(* We strip off ~ from types before matching on the underlying structure of the type.
* Note that we only do this for matching, not pretty-printing of types, as we
* want to retain ~ when showing types in suggestions
*)
let expand_and_strip_dynamic env ty =
let (_, ty) = Tast_env.expand_type env ty in
let ty =
Typing_utils.strip_dynamic (Tast_env.tast_env_as_typing_env env) ty
in
Tast_env.expand_type env ty
let expand_and_strip_supportdyn env ty =
let (env, ty) = expand_and_strip_dynamic env ty in
let (_, _, ty) =
Typing_utils.strip_supportdyn (Tast_env.tast_env_as_typing_env env) ty
in
ty
let expand_and_strip_dynamic env ty =
let (_, ty) = expand_and_strip_dynamic env ty in
ty
let matches_auto_complete_suffix x =
String.length x >= AutocompleteTypes.autocomplete_token_length
&&
let suffix =
String.sub
x
~pos:(String.length x - AutocompleteTypes.autocomplete_token_length)
~len:AutocompleteTypes.autocomplete_token_length
in
String.equal suffix AutocompleteTypes.autocomplete_token
(* Does [str] look like something we should offer code completion on? *)
let is_auto_complete str : bool =
let results_without_keywords =
List.filter !autocomplete_items ~f:(fun res ->
match res.res_kind with
| SI_Keyword -> false
| _ -> true)
in
if List.is_empty results_without_keywords then
matches_auto_complete_suffix str
else
false
let replace_pos_of_id ?(strip_xhp_colon = false) (pos, text) :
Ide_api_types.range =
let (_, name) = Utils.split_ns_from_name text in
let name =
if matches_auto_complete_suffix name then
strip_suffix name
else
name
in
let name =
if strip_xhp_colon then
Utils.strip_xhp_ns name
else
name
in
Ide_api_types.(
let range = pos_to_range pos in
let ed =
{
range.ed with
column = range.ed.column - AutocompleteTypes.autocomplete_token_length;
}
in
let st = { range.st with column = ed.column - String.length name } in
{ st; ed })
let autocomplete_result_to_json res =
let name = res.res_label in
let pos = res.res_decl_pos in
let ty = res.res_detail in
Hh_json.JSON_Object
[
("name", Hh_json.JSON_String name);
("type", Hh_json.JSON_String ty);
("pos", Pos.json pos);
("expected_ty", Hh_json.JSON_Bool false);
(* legacy field, left here in case clients need it *)
]
let add_res (res : autocomplete_item) : unit =
autocomplete_items := res :: !autocomplete_items
let autocomplete_id (id : Aast.sid) : unit =
if is_auto_complete (snd id) then auto_complete_for_global := snd id
let get_class_elt_types ~is_method env class_ cid elts =
let is_visible (_, elt) =
Tast_env.is_visible
~is_method
env
(elt.ce_visibility, get_ce_lsb elt)
cid
class_
in
elts
|> List.filter ~f:is_visible
|> List.map ~f:(fun (id, { ce_type = (lazy ty); _ }) -> (id, ty))
let get_class_req_attrs env pctx classname cid =
let req_attrs cls =
Cls.props cls
|> List.filter ~f:(fun (_, ce) ->
Tast_env.is_visible
~is_method:false
env
(ce.ce_visibility, get_ce_lsb ce)
cid
cls)
|> List.filter ~f:(fun (_, ce) ->
Xhp_attribute.opt_is_required (Typing_defs.get_ce_xhp_attr ce))
|> List.map ~f:(fun (name, _) -> Utils.strip_xhp_ns name)
in
Decl_provider.get_class pctx classname
|> Option.value_map ~default:[] ~f:req_attrs
let get_class_is_child_empty pctx classname =
Decl_provider.get_class pctx classname
|> Option.value_map ~default:false ~f:Cls.xhp_marked_empty
let get_pos_for (env : Tast_env.env) (ty : Typing_defs.phase_ty) : Pos.absolute
=
(match ty with
| LoclTy loclt -> loclt |> Typing_defs.get_pos
| DeclTy declt -> declt |> Typing_defs.get_pos)
|> ServerPos.resolve env
|> Pos.to_absolute
let snippet_for_params (params : 'a Typing_defs.fun_param list) : string =
(* A function call snippet looks like this:
fun_name(${1:\$first_arg}, ${2:\$second_arg})
The syntax for snippets is described here:
https://code.visualstudio.com/docs/editor/userdefinedsnippets#_variables *)
let param_templates =
List.mapi params ~f:(fun i param ->
match param.fp_name with
| Some param_name -> Printf.sprintf "${%d:\\%s}" (i + 1) param_name
| None -> Printf.sprintf "${%d}" (i + 1))
in
String.concat ~sep:", " param_templates
let get_snippet_for_xhp_req_attrs tag attrs has_children =
let content =
if List.length attrs > 0 then
let attr_content =
List.mapi attrs ~f:(fun i name ->
Format.sprintf "%s={${%d}}" name (i + 1))
|> String.concat ~sep:" "
in
tag ^ " " ^ attr_content
else
tag
in
if has_children then
Format.sprintf "%s>$0</%s>" content tag
else
content ^ " />"
let insert_text_for_xhp_req_attrs tag attrs has_children =
let content = get_snippet_for_xhp_req_attrs tag attrs has_children in
let insert_type = List.length attrs > 0 && has_children in
if insert_type then
InsertAsSnippet { snippet = content; fallback = tag }
else
InsertLiterally content
let get_snippet_for_xhp_classname cls ctx env =
(* This is used to check if the class exists or not *)
let class_ = Decl_provider.get_class ctx cls in
match class_ with
| None -> None
| Some class_ ->
if Cls.is_xhp class_ then
let cls = Utils.add_ns cls in
let attrs = get_class_req_attrs env ctx cls None in
let has_children = not (get_class_is_child_empty ctx cls) in
Option.some
(get_snippet_for_xhp_req_attrs
(Utils.strip_both_ns cls)
attrs
has_children)
else
None
(* If we're autocompleting a call (function or method), insert a
template for the arguments as well as function name. *)
let insert_text_for_fun_call
env
(autocomplete_context : legacy_autocomplete_context)
(fun_name : string)
(ft : Typing_defs.locl_fun_type) : insert_text =
if Char.equal autocomplete_context.char_at_pos '(' then
(* Arguments are present already, e.g. the user has ->AUTO332(1, 2).
We don't want to insert params when we complete the name, or we
end up with ->methName()(1, 2). *)
InsertLiterally fun_name
else
let arity =
if Tast_env.is_in_expr_tree env then
(* Helper functions in expression trees don't have relevant
parameter names on their decl, so don't autofill
parameters.*)
0
else
arity_min ft
in
let fallback = Printf.sprintf "%s()" fun_name in
if arity = 0 then
InsertLiterally fallback
else
let params = List.take ft.ft_params arity in
let snippet =
Printf.sprintf "%s(%s)" fun_name (snippet_for_params params)
in
InsertAsSnippet { snippet; fallback }
let insert_text_for_ty
env
(autocomplete_context : legacy_autocomplete_context)
(label : string)
(ty : phase_ty) : insert_text =
let (env, ty) =
match ty with
| LoclTy locl_ty -> (env, locl_ty)
| DeclTy decl_ty ->
Tast_env.localize_no_subst env ~ignore_errors:true decl_ty
in
(* Functions that support dynamic will be wrapped by supportdyn<_> *)
let ty = expand_and_strip_supportdyn env ty in
match Typing_defs.get_node ty with
| Tfun ft -> insert_text_for_fun_call env autocomplete_context label ft
| _ -> InsertLiterally label
let autocomplete_shape_key autocomplete_context env fields id =
if is_auto_complete (snd id) then
(* not the same as `prefix == ""` in namespaces *)
let have_prefix =
Pos.length (fst id) > AutocompleteTypes.autocomplete_token_length
in
let prefix = strip_suffix (snd id) in
let add (name : Typing_defs.tshape_field_name) =
let (code, kind, ty) =
match name with
| Typing_defs.TSFlit_int (pos, str) ->
let reason = Typing_reason.Rwitness_from_decl pos in
let ty = Typing_defs.Tprim Aast_defs.Tint in
(str, SI_Literal, Typing_defs.mk (reason, ty))
| Typing_defs.TSFlit_str (pos, str) ->
let reason = Typing_reason.Rwitness_from_decl pos in
let ty = Typing_defs.Tprim Aast_defs.Tstring in
let quote =
if have_prefix then
Str.first_chars prefix 1
else
"'"
in
(quote ^ str ^ quote, SI_Literal, Typing_defs.mk (reason, ty))
| Typing_defs.TSFclass_const ((pos, cid), (_, mid)) ->
( Printf.sprintf "%s::%s" cid mid,
SI_ClassConstant,
Typing_defs.mk
(Reason.Rwitness_from_decl pos, Typing_defs.make_tany ()) )
in
if (not have_prefix) || String.is_prefix code ~prefix then
let ty = Phase.decl ty in
let pos = get_pos_for env ty in
let res_insert_text =
if autocomplete_context.is_before_apostrophe then
rstrip code "'"
else
code
in
let complete =
{
res_decl_pos = pos;
res_replace_pos = replace_pos_of_id id;
res_base_class = None;
res_detail = kind_to_string kind;
res_insert_text = InsertLiterally res_insert_text;
res_label = res_insert_text;
res_fullname = code;
res_kind = kind;
res_documentation = None;
res_filter_text = None;
res_additional_edits = [];
}
in
add_res complete
in
List.iter (TShapeMap.keys fields) ~f:add
let autocomplete_member ~is_static autocomplete_context env class_ cid id =
(* This is used for instance "$x->|" and static "Class1::|" members. *)
if is_auto_complete (snd id) then (
(* Detect usage of "parent::|" which can use both static and instance *)
let parent_receiver =
match cid with
| Some Aast.CIparent -> true
| _ -> false
in
let add kind (name, ty) =
(* Functions that support dynamic will be wrapped by supportdyn<_> *)
let ty = strip_supportdyn_decl ty in
let res_detail =
match Typing_defs.get_node ty with
| Tfun _ ->
String_utils.rstrip
(String_utils.lstrip (Tast_env.print_decl_ty env ty) "(")
")"
| _ -> Tast_env.print_decl_ty env ty
in
let ty = Phase.decl ty in
let complete =
{
res_decl_pos = get_pos_for env ty;
res_replace_pos = replace_pos_of_id id;
res_base_class = Some (Cls.name class_);
res_detail;
res_label = name;
res_insert_text = insert_text_for_ty env autocomplete_context name ty;
res_fullname = name;
res_kind = kind;
res_documentation = None;
res_filter_text = None;
res_additional_edits = [];
}
in
add_res complete
in
let sort : 'a. (string * 'a) list -> (string * 'a) list =
fun list ->
List.sort ~compare:(fun (a, _) (b, _) -> String.compare a b) list
in
(* There's no reason for us to sort -- we can expect our client to do its
own sorting of our results -- but having a sorted list here makes our tests
more stable. *)
if is_static || parent_receiver then (
List.iter
(get_class_elt_types
~is_method:true
env
class_
cid
(Cls.smethods class_ |> sort))
~f:(add SearchTypes.SI_ClassMethod);
List.iter
(get_class_elt_types
~is_method:false
env
class_
cid
(Cls.sprops class_ |> sort))
~f:(add SearchTypes.SI_Property);
List.iter
(Cls.consts class_ |> sort)
~f:(fun (name, cc) ->
add SearchTypes.SI_ClassConstant (name, cc.cc_type))
);
if (not is_static) || parent_receiver then (
List.iter
(get_class_elt_types
~is_method:true
env
class_
cid
(Cls.methods class_ |> sort))
~f:(add SearchTypes.SI_ClassMethod);
List.iter
(get_class_elt_types
~is_method:false
env
class_
cid
(Cls.props class_ |> sort))
~f:(add SearchTypes.SI_Property)
);
(* Only complete __construct() when we see parent::, as we don't
allow __construct to be called as e.g. $foo->__construct(). *)
if parent_receiver then
let (constructor, _) = Cls.construct class_ in
let constructor =
Option.map constructor ~f:(fun elt ->
(Naming_special_names.Members.__construct, elt))
in
List.iter
(get_class_elt_types
~is_method:true
env
class_
cid
(Option.to_list constructor))
~f:(add SearchTypes.SI_ClassMethod)
)
(*
Autocompletion for XHP attribute names in an XHP literal.
*)
let autocomplete_xhp_attributes env class_ cid id attrs =
(* This is used for "<nt:fb:text |" XHP attributes, in which case *)
(* class_ is ":nt:fb:text" and its attributes are in tc_props. *)
if is_auto_complete (snd id) && Cls.is_xhp class_ then
let existing_attr_names : SSet.t =
attrs
|> List.filter_map ~f:(fun attr ->
match attr with
| Aast.Xhp_simple { Aast.xs_name = id; _ } -> Some (snd id)
| Aast.Xhp_spread _ -> None)
|> List.filter ~f:(fun name -> not (matches_auto_complete_suffix name))
|> SSet.of_list
in
List.iter
(get_class_elt_types ~is_method:false env class_ cid (Cls.props class_))
~f:(fun (name, ty) ->
if
not
(SSet.exists
(fun key -> String.equal (":" ^ key) name)
existing_attr_names)
then
let kind = SearchTypes.SI_Property in
let res_detail = Tast_env.print_decl_ty env ty in
let ty = Phase.decl ty in
let complete =
{
res_decl_pos = get_pos_for env ty;
res_replace_pos = replace_pos_of_id id;
res_base_class = Some (Cls.name class_);
res_detail;
res_label = lstrip name ":";
res_insert_text = InsertLiterally (lstrip name ":");
res_fullname = name;
res_kind = kind;
res_documentation = None;
res_filter_text = None;
res_additional_edits = [];
}
in
add_res complete)
let autocomplete_xhp_bool_value attr_ty id_id env =
if is_auto_complete (snd id_id) then begin
let is_bool_or_bool_option ty : bool =
let is_bool = function
| Tprim Tbool -> true
| _ -> false
in
let ty = expand_and_strip_dynamic env ty in
let (_, ty_) = Typing_defs_core.deref ty in
match ty_ with
| Toption ty -> is_bool (get_node (expand_and_strip_dynamic env ty))
| _ -> is_bool ty_
in
if is_bool_or_bool_option attr_ty then (
let kind = SearchTypes.SI_Literal in
let ty = Phase.locl attr_ty in
let complete =
{
res_decl_pos = get_pos_for env ty;
res_replace_pos = replace_pos_of_id id_id;
res_base_class = None;
res_detail = kind_to_string kind;
res_label = "true";
res_insert_text = InsertLiterally "true";
res_fullname = "true";
res_kind = kind;
res_documentation = None;
res_filter_text = None;
res_additional_edits = [];
}
in
add_res complete;
add_res
{
complete with
res_label = "false";
res_insert_text = InsertLiterally "false";
res_fullname = "false";
}
)
end
(*
Autocompletion for the value of an attribute in an XHP literals with the enum type,
defined with the following syntax:
attribute enum {"some value", "some other value"} my-attribute;
*)
let autocomplete_xhp_enum_attribute_value attr_name ty id_id env cls =
if is_auto_complete (snd id_id) then begin
let attr_origin =
Cls.props cls
|> List.find ~f:(fun (name, _) -> String.equal (":" ^ attr_name) name)
|> Option.map ~f:(fun (_, { ce_origin = n; _ }) -> n)
|> Option.bind ~f:(fun cls_name ->
Decl_provider.get_class (Tast_env.get_ctx env) cls_name)
in
let enum_values =
match attr_origin with
| Some cls -> Cls.xhp_enum_values cls
| None -> SMap.empty
in
let add_enum_value_result xev =
let suggestion = function
| Ast_defs.XEV_Int value -> string_of_int value
| Ast_defs.XEV_String value -> "\"" ^ value ^ "\""
in
let name = suggestion xev in
let kind = SearchTypes.SI_Enum in
let ty = Phase.locl ty in
let complete =
{
res_decl_pos = get_pos_for env ty;
res_replace_pos = replace_pos_of_id id_id;
res_base_class = None;
res_detail = kind_to_string kind;
res_label = name;
res_insert_text = InsertLiterally name;
res_fullname = name;
res_kind = kind;
res_documentation = None;
res_filter_text = None;
res_additional_edits = [];
}
in
add_res complete
in
match SMap.find_opt (":" ^ attr_name) enum_values with
| Some enum_values -> List.iter enum_values ~f:add_enum_value_result
| None -> ()
end
(*
Autocompletion for the value of an attribute in an XHP literals
with type that is an enum class. i.e.
enum MyEnum {}
class :foo {
attribute MyEnum my-attribute;
}
*)
let autocomplete_xhp_enum_class_value attr_ty id_id env =
if is_auto_complete (snd id_id) then begin
let rec get_class_name_decl ty : string option =
let ty = strip_like_decl ty in
match get_node ty with
| Toption ty -> get_class_name_decl ty
| Tapply ((_, name), _) -> Some name
| _ -> None
in
let rec get_class_name ty : string option =
let ty = expand_and_strip_dynamic env ty in
match get_node ty with
| Toption ty -> get_class_name ty
| Tnewtype (name, _, _) -> Some name
| _ -> None
in
let get_enum_constants (class_decl : Decl_provider.class_decl) :
(string * Typing_defs.class_const) list =
let all_consts = Cls.consts class_decl in
let is_correct_class = function
| Some name -> String.equal name (Cls.name class_decl)
| None -> false
in
all_consts
|> List.filter ~f:(fun (_, class_const) ->
is_correct_class (get_class_name_decl class_const.cc_type))
in
let attr_type_name = get_class_name attr_ty in
attr_type_name
|> Option.iter ~f:(fun class_name ->
let enum_class = Tast_env.get_enum env class_name in
let enum_constants =
Option.value
~default:[]
(Option.map enum_class ~f:get_enum_constants)
in
enum_constants
|> List.iter ~f:(fun (const_name, ty) ->
let dty = Phase.decl ty.cc_type in
let name = Utils.strip_ns class_name ^ "::" ^ const_name in
let kind = SearchTypes.SI_Enum in
let res_base_class = Option.map ~f:Cls.name enum_class in
let complete =
{
res_decl_pos = get_pos_for env dty;
res_replace_pos = replace_pos_of_id id_id;
res_base_class;
res_detail = kind_to_string kind;
res_label = name;
res_insert_text = InsertLiterally name;
res_fullname = name;
res_kind = kind;
res_documentation = None;
res_filter_text = None;
res_additional_edits = [];
}
in
add_res complete))
end
(** Return all the paths of .hhi files. *)
let hhi_paths () : Relative_path.t list =
let hhi_root = Path.make (Relative_path.path_of_prefix Relative_path.Hhi) in
let as_abs_path hhi_path : Path.t = Path.concat hhi_root hhi_path in
Hhi.get_raw_hhi_contents ()
|> Array.to_list
|> List.map ~f:(fun (fn, _) ->
Relative_path.create
Relative_path.Hhi
(Path.to_string (as_abs_path fn)))
(** Return the fully qualified names of all functions in .hhi files, sorted
alphabetically. *)
let hhi_funs (naming_table : Naming_table.t) : string list =
hhi_paths ()
|> List.map ~f:(fun fn ->
match Naming_table.get_file_info naming_table fn with
| Some info ->
List.map info.FileInfo.funs ~f:(fun (_, name, _) -> name)
| None -> [])
|> List.concat
|> List.sort ~compare:String.compare
|> List.rev
(** Filter function names to those in namespaces can be used with value types. *)
let filter_fake_arrow_namespaces (fun_names : string list) : string list =
let in_relevant_ns name : bool =
let name = Utils.strip_hh_lib_ns name in
String.is_prefix ~prefix:"C\\" name
|| String.is_prefix ~prefix:"Vec\\" name
|| String.is_prefix ~prefix:"Dict\\" name
|| String.is_prefix ~prefix:"Keyset\\" name
|| String.is_prefix ~prefix:"Str\\" name
in
List.filter fun_names ~f:in_relevant_ns
(** Create a fresh type variable for every item in [tparams]. *)
let fresh_tyvars (env : Tast_env.env) (tparams : 'a list) :
Tast_env.env * locl_ty list =
List.fold tparams ~init:(env, []) ~f:(fun (env, tvars) _ ->
let (env, tvar) = Tast_env.fresh_type env Pos.none in
(env, tvar :: tvars))
let fresh_expand_env
(env : Tast_env.env) (tparams : decl_ty Typing_defs.tparam list) :
Tast_env.env * expand_env =
let (env, tyvars) = fresh_tyvars env tparams in
let substs = Decl_subst.make_locl tparams tyvars in
(env, { Typing_defs.empty_expand_env with substs })
(** Does Hack function [f] accept [arg_ty] as its first argument? *)
let fun_accepts_first_arg (env : Tast_env.env) (f : fun_elt) (arg_ty : locl_ty)
: bool =
(* Functions that support dynamic will be wrapped by supportdyn<_> *)
let ty = strip_supportdyn_decl f.fe_type in
match Typing_defs.get_node ty with
| Tfun ft ->
let params = ft.ft_params in
(match List.hd params with
| Some first_param ->
let (env, ety_env) = fresh_expand_env env ft.ft_tparams in
let (env, first_param) =
Tast_env.localize env ety_env first_param.fp_type.et_type
in
(match get_node first_param with
| Tvar _ ->
(* Kludge: If inference found a type variable that it couldn't solve,
we've probably violated a where constraint and shouldn't consider
this function to be compatible. *)
false
| _ ->
let arg_ty = expand_and_strip_dynamic env arg_ty in
let first_param = expand_and_strip_dynamic env first_param in
Tast_env.can_subtype env arg_ty first_param)
| _ -> false)
| _ -> false
(** Fetch decls for all the [fun_names] and filter to those where the first argument
is compatible with [arg_ty]. *)
let compatible_fun_decls
(env : Tast_env.env) (arg_ty : locl_ty) (fun_names : string list) :
(string * fun_elt) list =
List.filter_map fun_names ~f:(fun fun_name ->
match Decl_provider.get_fun (Tast_env.get_ctx env) fun_name with
| Some f when fun_accepts_first_arg env f arg_ty -> Some (fun_name, f)
| _ -> None)
(** Is [ty] a value type where we want to allow -> to complete to a HSL function? *)
let is_fake_arrow_ty (env : Tast_env.env) (ty : locl_ty) : bool =
let ty = expand_and_strip_dynamic env ty in
let (_, ty_) = Typing_defs_core.deref ty in
match ty_ with
| Tclass ((_, name), _, _) ->
String.equal Naming_special_names.Collections.cVec name
|| String.equal Naming_special_names.Collections.cDict name
|| String.equal Naming_special_names.Collections.cKeyset name
| Tprim Tstring -> true
| _ -> false
(** If the user is completing $v-> and $v is a vec/keyset/dict/string,
offer HSL functions like C\count(). *)
let autocomplete_hack_fake_arrow
(env : Tast_env.env)
(recv : expr)
(prop_name : sid)
(naming_table : Naming_table.t) : unit =
let prop_replace_pos = replace_pos_of_id prop_name in
let prop_start = prop_replace_pos.Ide_api_types.st in
let replace_pos =
Ide_api_types.
{
prop_replace_pos with
st = { prop_start with column = prop_start.column - 2 };
}
in
let (recv_ty, recv_pos, _) = recv in
if is_fake_arrow_ty env recv_ty && is_auto_complete (snd prop_name) then
let recv_start_pos = Pos.shrink_to_start recv_pos in
let fake_arrow_funs =
filter_fake_arrow_namespaces (hhi_funs naming_table)
in
let compatible_funs = compatible_fun_decls env recv_ty fake_arrow_funs in
List.iter compatible_funs ~f:(fun (fun_name, fun_decl) ->
let name = Utils.strip_hh_lib_ns fun_name in
let kind = SI_Function in
(* We want to transform $some_vec-> to e.g.
C\contains(some_vec, ${1:\$value})
This requires an additional insertion "C\contains(" before
the expression. *)
let res_additional_edits =
[
( Printf.sprintf "%s(" name,
Ide_api_types.pos_to_range recv_start_pos );
]
in
(* Construct a snippet with placeholders for any additional
required arguments for this function. For the C\contains()
example, this is ", ${1:\$value})". *)
let required_params =
match Typing_defs.get_node fun_decl.fe_type with
| Tfun ft -> List.take ft.ft_params (arity_min ft)
| _ -> []
in
let params = List.drop required_params 1 in
let res_insert_text =
match params with
| [] -> InsertLiterally ")"
| params ->
let snippet = Printf.sprintf ", %s)" (snippet_for_params params) in
InsertAsSnippet { snippet; fallback = ")" }
in
let complete =
{
res_decl_pos =
Pos.to_absolute (ServerPos.resolve env fun_decl.fe_pos);
res_replace_pos = replace_pos;
res_base_class = None;
res_detail = Tast_env.print_decl_ty env fun_decl.fe_type;
res_insert_text;
(* VS Code uses filter text to decide which items match the current
prefix. However, "C\contains" does not start with "->", so VS
Code would normally ignore this completion item.
We set the filter text to "->contains" so we offer C\contains if
the user types e.g. "->" or "->co". *)
res_filter_text =
Some (Printf.sprintf "->%s" (Utils.strip_all_ns fun_name));
res_label = name;
res_fullname = name;
res_kind = kind;
res_documentation = None;
res_additional_edits;
}
in
add_res complete)
let autocomplete_typed_member
~is_static autocomplete_context env class_ty cid mid =
Tast_env.get_class_ids env class_ty
|> List.iter ~f:(fun cname ->
Decl_provider.get_class (Tast_env.get_ctx env) cname
|> Option.iter ~f:(fun class_ ->
let cid = Option.map cid ~f:to_nast_class_id_ in
autocomplete_member
~is_static
autocomplete_context
env
class_
cid
mid))
let autocomplete_static_member autocomplete_context env (ty, _, cid) mid =
autocomplete_typed_member
~is_static:true
autocomplete_context
env
ty
(Some cid)
mid
let compatible_enum_class_consts env cls (expected_ty : locl_ty option) =
(* Ignore ::class, as it's not a normal enum constant. *)
let consts =
List.filter (Cls.consts cls) ~f:(fun (name, _) ->
String.(name <> Naming_special_names.Members.mClass))
in
(* All the constants that are compatible with [expected_ty]. *)
let compatible_consts =
List.filter consts ~f:(fun (_, cc) ->
let (env, cc_ty) =
Tast_env.localize_no_subst env ~ignore_errors:true cc.cc_type
in
match expected_ty with
| Some expected_ty ->
Tast_env.is_sub_type
env
cc_ty
(Typing_make_type.locl_like Reason.Rnone expected_ty)
| None -> true)
in
match compatible_consts with
| [] ->
(* If we couldn't find any constants that match the expected
type, show all constants. We sometimes infer [nothing] for
generics when a user hasn't passed all the arguments to a
function yet. *)
consts
| _ -> compatible_consts
(* If [ty] is a MemberOf, unwrap the inner type, otherwise return the
argument unchanged.
MemberOf<SomeEnum, X> -> X
Y -> Y *)
let unwrap_enum_memberof (ty : Typing_defs.decl_ty) : Typing_defs.decl_ty =
let ty = strip_like_decl ty in
match get_node ty with
| Tapply ((_, name), [_; arg])
when String.equal name Naming_special_names.Classes.cMemberOf ->
arg
| _ -> ty
let autocomplete_enum_class_label env opt_cname pos_labelname expected_ty =
let suggest_members cls =
List.iter
(compatible_enum_class_consts env cls expected_ty)
~f:(fun (name, cc) ->
let res_detail =
Tast_env.print_decl_ty env (unwrap_enum_memberof cc.cc_type)
in
let ty = Phase.decl cc.cc_type in
let kind = SearchTypes.SI_ClassConstant in
let complete =
{
res_decl_pos = get_pos_for env ty;
res_replace_pos = replace_pos_of_id pos_labelname;
res_base_class = Some (Cls.name cls);
res_detail;
res_label = name;
res_insert_text = InsertLiterally name;
res_fullname = name;
res_kind = kind;
res_documentation = None;
res_filter_text = None;
res_additional_edits = [];
}
in
add_res complete)
in
let open Option in
Option.iter
~f:suggest_members
(opt_cname >>= fun (_, id) -> Tast_env.get_class env id)
(* Zip two lists together. If the two lists have different lengths,
take the shortest. *)
let rec zip_truncate (xs : 'a list) (ys : 'b list) : ('a * 'b) list =
match (xs, ys) with
| (x :: xs, y :: ys) -> (x, y) :: zip_truncate xs ys
| _ -> []
(* Auto complete for short labels `#Foo` inside a function call.
* Leverage function type information to infer the right enum class.
*)
let autocomplete_enum_class_label_call env f args =
let suggest_members_from_ty env ty pos_labelname expected_ty =
let ty = expand_and_strip_dynamic env ty in
match get_node ty with
| Tclass ((p, enum_name), _, _) when Tast_env.is_enum_class env enum_name ->
autocomplete_enum_class_label
env
(Some (p, enum_name))
pos_labelname
expected_ty
| _ -> ()
in
let is_enum_class_label_ty_name name =
String.equal Naming_special_names.Classes.cEnumClassLabel name
in
let (fty, _, _) = f in
(* Functions that support dynamic will be wrapped by supportdyn<_> *)
let fty = expand_and_strip_supportdyn env fty in
match get_node fty with
| Tfun { ft_params; _ } ->
let ty_args = zip_truncate args ft_params in
List.iter
~f:(fun (arg, arg_ty) ->
match
(arg, get_node (expand_and_strip_dynamic env arg_ty.fp_type.et_type))
with
| ( (_, (_, p, Aast.EnumClassLabel (None, n))),
Typing_defs.Tnewtype (ty_name, [enum_ty; member_ty], _) )
when is_enum_class_label_ty_name ty_name && is_auto_complete n ->
suggest_members_from_ty env enum_ty (p, n) (Some member_ty)
| (_, _) -> ())
ty_args
| _ -> ()
(* Best-effort to find a class associated with this type constant. *)
let typeconst_class_name (typeconst : typeconst_type) : string option =
let decl_ty =
match typeconst.ttc_kind with
| TCAbstract { atc_as_constraint; _ } -> atc_as_constraint
| TCConcrete { tc_type } -> Some tc_type
in
match decl_ty with
| Some decl_ty ->
let decl_ty = strip_like_decl decl_ty in
let (_, ty_) = Typing_defs_core.deref decl_ty in
(match ty_ with
| Tapply ((_, name), _) -> Some name
| _ -> None)
| None -> None
(* Given a typeconstant `Foo::TBar::TBaz`, if TBaz is a classish,
return its decl. *)
let rec typeconst_decl env (ids : sid list) (cls_name : string) : Cls.t option =
let open Option in
match Tast_env.get_class env cls_name with
| Some cls_decl ->
(match ids with
| [] -> Some cls_decl
| (_, id) :: ids ->
Cls.get_typeconst cls_decl id
>>= typeconst_class_name
>>= typeconst_decl env ids)
| None -> None
(* Autocomplete type constants, which look like `MyClass::AUTO332`. *)
let autocomplete_class_type_const env ((_, h) : Aast.hint) (ids : sid list) :
unit =
match List.last ids with
| Some ((_, id) as sid) when is_auto_complete id ->
let prefix = strip_suffix id in
let class_name =
match h with
| Happly ((_, name), _) -> Some name
| Hthis -> Tast_env.get_self_id env
| _ -> None
in
let class_decl =
match class_name with
| Some class_name ->
typeconst_decl env (List.drop_last_exn ids) class_name
| None -> None
in
(match class_decl with
| Some class_decl ->
let consts = Cls.consts class_decl in
List.iter consts ~f:(fun (name, cc) ->
if String.is_prefix ~prefix name then
let complete =
{
res_decl_pos = Pos.to_absolute Pos.none;
res_replace_pos = replace_pos_of_id sid;
res_base_class = Some cc.cc_origin;
res_detail = "const type";
res_label = name;
res_insert_text = InsertLiterally name;
res_fullname = name;
res_kind = SI_ClassConstant;
res_documentation = None;
res_filter_text = None;
res_additional_edits = [];
}
in
add_res complete)
| None -> ())
| _ -> ()
(* Get the names of string literal keys in this shape type. *)
let shape_string_keys (sm : 'a TShapeMap.t) : string list =
let fields = TShapeMap.keys sm in
List.filter_map fields ~f:(fun field ->
match field with
| TSFlit_str (_, s) -> Some s
| _ -> None)
let unwrap_holes ((_, _, e_) as e : Tast.expr) : Tast.expr =
match e_ with
| Aast.Hole (e, _, _, _)
| Aast.Invalid (Some e) ->
e
| _ -> e
(* If we see a call to a function that takes a shape argument, offer
completions for field names in shape literals.
takes_shape(shape('x' => 123, '|'));
*)
let autocomplete_shape_literal_in_call
env
(ft : Typing_defs.locl_fun_type)
(args : (Ast_defs.param_kind * Tast.expr) list) : unit =
let add_shape_key_result pos key =
let ty = Tprim Aast_defs.Tstring in
let reason = Typing_reason.Rwitness pos in
let ty = mk (reason, ty) in
let kind = SI_Literal in
let lty = Phase.locl ty in
let complete =
{
res_decl_pos = get_pos_for env lty;
res_replace_pos = replace_pos_of_id (pos, key);
res_base_class = None;
res_detail = kind_to_string kind;
res_label = key;
res_insert_text = InsertLiterally key;
res_fullname = key;
res_kind = kind;
res_documentation = None;
res_filter_text = None;
res_additional_edits = [];
}
in
add_res complete
in
(* If this shape field name is of the form "fooAUTO332", return "foo". *)
let shape_field_autocomplete_prefix (sfn : Ast_defs.shape_field_name) :
string option =
match sfn with
| Ast_defs.SFlit_str (_, name) when is_auto_complete name ->
Some (strip_suffix name)
| _ -> None
in
let args = List.map args ~f:(fun (_, e) -> unwrap_holes e) in
List.iter
~f:(fun (arg, expected_ty) ->
match arg with
| (_, pos, Aast.Shape kvs) ->
(* We're passing a shape literal as this function argument. *)
List.iter kvs ~f:(fun (name, _val) ->
match shape_field_autocomplete_prefix name with
| Some prefix ->
(* This shape key is being autocompleted. *)
let (_, ty_) =
Typing_defs_core.deref expected_ty.fp_type.et_type
in
(match ty_ with
| Tshape { s_fields = fields; _ } ->
(* This parameter is known to be a concrete shape type. *)
let keys = shape_string_keys fields in
let matching_keys =
List.filter keys ~f:(String.is_prefix ~prefix)
in
List.iter matching_keys ~f:(add_shape_key_result pos)
| _ -> ())
| _ -> ())
| _ -> ())
(zip_truncate args ft.ft_params)
let add_builtin_attribute_result replace_pos ~doc ~name : unit =
let complete =
{
res_decl_pos = Pos.to_absolute Pos.none;
res_replace_pos = replace_pos;
res_base_class = None;
res_detail = "built-in attribute";
res_label = name;
res_insert_text = InsertLiterally name;
res_fullname = name;
res_kind = SI_Class;
res_documentation = Some doc;
res_filter_text = None;
res_additional_edits = [];
}
in
add_res complete
let enclosing_class_decl (env : Tast_env.env) : Cls.t option =
match Tast_env.get_self_id env with
| Some id -> Tast_env.get_class env id
| None -> None
(** Return the inherited class methods whose name starts with [prefix]
and haven't already been overridden. *)
let methods_could_override (cls : Cls.t) ~(is_static : bool) (prefix : string) :
(string * class_elt) list =
let c_name = Cls.name cls in
let methods =
if is_static then
Cls.smethods cls
else
Cls.methods cls
in
List.filter methods ~f:(fun (n, ce) ->
(* We're only interested in methods that start with this prefix,
and aren't already defined in the current class. *)
String.is_prefix n ~prefix && not (String.equal ce.ce_origin c_name))
(** Autocomplete a partially written override method definition.
<<__Override>>
public static function xAUTO332
*)
let autocomplete_overriding_method env m : unit =
let open Aast in
let name = snd m.m_name in
if is_auto_complete name then
let prefix = strip_suffix name in
let has_override =
List.exists m.m_user_attributes ~f:(fun { ua_name = (_, attr_name); _ } ->
String.equal attr_name Naming_special_names.UserAttributes.uaOverride)
in
match enclosing_class_decl env with
| Some cls when has_override ->
List.iter
(methods_could_override cls ~is_static:m.m_static prefix)
~f:(fun (name, ce) ->
let complete =
{
res_decl_pos = Pos.to_absolute Pos.none;
res_replace_pos = replace_pos_of_id m.m_name;
res_base_class = Some ce.ce_origin;
res_detail = "method name";
res_label = name;
res_insert_text = InsertLiterally name;
res_fullname = name;
res_kind = SI_ClassMethod;
res_documentation = None;
res_filter_text = None;
res_additional_edits = [];
}
in
add_res complete)
| _ -> ()
let autocomplete_builtin_attribute
((pos, name) : Pos.t * string) (attr_kind : string) : unit =
let module UA = Naming_special_names.UserAttributes in
let stripped_name = Utils.strip_ns name in
if is_auto_complete name && String.is_prefix stripped_name ~prefix:"_" then
let replace_pos = replace_pos_of_id (pos, name) in
let prefix = strip_suffix stripped_name in
(* Built-in attributes that match the prefix the user has typed. *)
let possible_attrs =
SMap.filter
(fun name attr_info ->
String.is_prefix name ~prefix
&& attr_info.UA.autocomplete
&& List.mem attr_info.UA.contexts attr_kind ~equal:String.equal)
UA.as_map
in
(* Sort by attribute name. This isn't necessary in the IDE, which
does its own sorting, but helps tests. *)
let sorted_attrs =
List.sort (SMap.elements possible_attrs) ~compare:(fun (x, _) (y, _) ->
String.compare x y)
|> List.rev
in
List.iter
~f:(fun (name, attr_info) ->
let doc = attr_info.UA.doc in
add_builtin_attribute_result replace_pos ~name ~doc)
sorted_attrs
(* If [name] is an enum, return the list of the constants it defines. *)
let enum_consts env name : string list option =
match Decl_provider.get_class (Tast_env.get_ctx env) name with
| Some cls ->
(match Cls.kind cls with
| Ast_defs.Cenum ->
let consts =
Cls.consts cls
|> List.map ~f:fst
|> List.filter ~f:(fun name ->
String.(name <> Naming_special_names.Members.mClass))
in
Some consts
| _ -> None)
| None -> None
let add_enum_const_result env pos replace_pos prefix const_name =
let ty = Tprim Aast_defs.Tstring in
let reason = Typing_reason.Rwitness pos in
let ty = mk (reason, ty) in
let kind = SI_ClassConstant in
let lty = Phase.locl ty in
let key = prefix ^ const_name in
let complete =
{
res_decl_pos = get_pos_for env lty;
res_replace_pos = replace_pos;
res_base_class = None;
res_detail = kind_to_string kind;
res_label = key;
res_insert_text = InsertLiterally key;
res_fullname = key;
res_kind = kind;
res_documentation = None;
res_filter_text = None;
res_additional_edits = [];
}
in
add_res complete
let case_names (expected_enum : string) (cases : Tast.case list) : SSet.t =
let case_name case =
match fst case with
| ( _,
_,
Aast.Class_const ((_, _, Aast.CI (_, enum_name)), (_, variant_name)) )
when String.equal expected_enum enum_name ->
Some variant_name
| _ -> None
in
SSet.of_list (List.filter_map cases ~f:case_name)
(* Autocomplete enum values in case statements.
switch ($enum_value) {
case AUTO332
} *)
let autocomplete_enum_case env (expr : Tast.expr) (cases : Tast.case list) =
List.iter cases ~f:(fun (e, _) ->
match e with
| (_, _, Aast.Id (pos, id)) when is_auto_complete id ->
let (recv_ty, _, _) = expr in
let ty = expand_and_strip_dynamic env recv_ty in
let (_, ty_) = Typing_defs_core.deref ty in
let replace_pos = replace_pos_of_id (pos, id) in
(match ty_ with
| Tnewtype (name, _, _) ->
(match enum_consts env name with
| Some consts ->
let used_consts = case_names name cases in
let unused_consts =
List.filter consts ~f:(fun const ->
not (SSet.mem const used_consts))
in
let prefix = Utils.strip_ns name ^ "::" in
List.iter
unused_consts
~f:(add_enum_const_result env pos replace_pos prefix)
| None -> ())
| _ -> ())
| _ -> ())
(* Autocomplete enum values in function arguments that are known to be enums.
takes_enum(AUTO332); *)
let autocomplete_enum_value_in_call env (ft : Typing_defs.locl_fun_type) args :
unit =
let args = List.map args ~f:(fun (_, e) -> unwrap_holes e) in
List.iter
~f:(fun (arg, expected_ty) ->
match arg with
| (_, _, Aast.Id (pos, id)) when matches_auto_complete_suffix id ->
let ty = expand_and_strip_dynamic env expected_ty.fp_type.et_type in
let (_, ty_) = Typing_defs_core.deref ty in
let replace_pos = replace_pos_of_id (pos, id) in
(match ty_ with
| Tnewtype (name, _, _) ->
(match enum_consts env name with
| Some consts ->
let prefix = Utils.strip_ns name ^ "::" in
List.iter
consts
~f:(add_enum_const_result env pos replace_pos prefix)
| None -> ())
| _ -> ())
| (_, _, Aast.Class_const ((_, _, Aast.CI _name), (pos, id)))
when matches_auto_complete_suffix id ->
let ty = expand_and_strip_dynamic env expected_ty.fp_type.et_type in
let (_, ty_) = Typing_defs_core.deref ty in
let replace_pos = replace_pos_of_id (pos, id) in
(match ty_ with
| Tnewtype (name, _, _) ->
(match enum_consts env name with
| Some consts ->
List.iter consts ~f:(add_enum_const_result env pos replace_pos "")
| None -> ())
| _ -> ())
| _ -> ())
(zip_truncate args ft.ft_params)
let builtin_type_hints =
[
(SymbolOccurrence.BImixed, "mixed");
(SymbolOccurrence.BIdynamic, "dynamic");
(SymbolOccurrence.BInothing, "nothing");
(SymbolOccurrence.BInonnull, "nonnull");
(SymbolOccurrence.BIshape, "shape");
(SymbolOccurrence.BIprimitive Aast_defs.Tnull, "null");
(* TODO: only offer void in return positions. *)
(SymbolOccurrence.BIprimitive Aast_defs.Tvoid, "void");
(SymbolOccurrence.BIprimitive Aast_defs.Tint, "int");
(SymbolOccurrence.BIprimitive Aast_defs.Tbool, "bool");
(SymbolOccurrence.BIprimitive Aast_defs.Tfloat, "float");
(SymbolOccurrence.BIprimitive Aast_defs.Tstring, "string");
(SymbolOccurrence.BIprimitive Aast_defs.Tresource, "resource");
(SymbolOccurrence.BIprimitive Aast_defs.Tnum, "num");
(SymbolOccurrence.BIprimitive Aast_defs.Tarraykey, "arraykey");
(SymbolOccurrence.BIprimitive Aast_defs.Tnoreturn, "noreturn");
]
(* Find global autocomplete results *)
let find_global_results
~(env : Tast_env.env)
~(id : Pos.t * string)
~(completion_type : SearchTypes.autocomplete_type)
~(autocomplete_context : AutocompleteTypes.legacy_autocomplete_context)
~(sienv_ref : SearchUtils.si_env ref)
~(pctx : Provider_context.t) : unit =
(* First step: Check obvious cases where autocomplete is not warranted. *)
(* *)
(* is_after_single_colon : XHP vs switch statements *)
(* is_after_open_square_bracket : shape field names vs container keys *)
(* is_after_quote: shape field names vs arbitrary strings *)
(* *)
(* We can recognize these cases by whether the prefix is empty. *)
(* We do this by checking the identifier length, as the string will *)
(* include the current namespace. *)
let have_user_prefix =
Pos.length (fst id) > AutocompleteTypes.autocomplete_token_length
in
let tast_env = Tast_env.empty pctx in
let ctx = autocomplete_context in
if
(not ctx.is_manually_invoked)
&& (not have_user_prefix)
&& (ctx.is_after_single_colon
|| ctx.is_after_open_square_bracket
|| ctx.is_after_quote)
then
()
else if ctx.is_after_double_right_angle_bracket then
(* <<__Override>>AUTO332 *)
()
else if ctx.is_open_curly_without_equals then
(* In the case that we trigger autocompletion with an open curly brace,
we only want to perform autocompletion if it is preceded by an equal sign.
i.e. if (true) {
--> Do not autocomplete
i.e. <foo:bar my-attribute={
--> Allow autocompletion
*)
()
else
let query_text = strip_suffix (snd id) in
let query_text = Utils.strip_ns query_text in
auto_complete_for_global := query_text;
let (ns, _) = Utils.split_ns_from_name query_text in
let absolute_none = Pos.none |> Pos.to_absolute in
let kind_filter =
match completion_type with
| Acnew -> Some SI_Class
| Actrait_only -> Some SI_Trait
| Acid
| Actype
| Ac_workspace_symbol ->
None
in
let (results, is_complete) =
SymbolIndex.find_matching_symbols
~sienv_ref
~query_text
~max_results
~kind_filter
~context:completion_type
in
autocomplete_is_complete :=
SearchTypes.equal_si_complete is_complete SearchTypes.Complete;
(* Looking up a function signature using Tast_env.get_fun consumes ~67KB
* and can cause complex typechecking which can take from 2-100 milliseconds
* per result. When tested in summer 2019 it was possible to load 1.4GB of data
* if get_fun was called on every function in the WWW codebase.
*
* Therefore, this feature is only available via the option sie_resolve_signatures
* - and please be careful not to turn it on unless you really want to consume
* memory and performance.
*)
List.iter results ~f:(fun r ->
let (res_label, res_fullname) = (r.si_name, r.si_fullname) in
(* Only load func details if the flag sie_resolve_signatures is true *)
let (res_detail, res_insert_text) =
if
!sienv_ref.sie_resolve_signatures
&& equal_si_kind r.si_kind SI_Function
then
let fixed_name = ns ^ r.si_name in
match Tast_env.get_fun tast_env fixed_name with
| None -> (kind_to_string r.si_kind, InsertLiterally res_label)
| Some fe ->
let ty = fe.fe_type in
let res_detail = Tast_env.print_decl_ty tast_env ty in
( res_detail,
insert_text_for_ty
env
autocomplete_context
res_label
(Phase.decl ty) )
else
(kind_to_string r.si_kind, InsertLiterally res_label)
in
(* Only load exact positions if specially requested *)
let res_decl_pos =
if !sienv_ref.sie_resolve_positions then
let fixed_name = ns ^ r.si_name in
match Tast_env.get_fun tast_env fixed_name with
| None -> absolute_none
| Some fe ->
Typing_defs.get_pos fe.fe_type
|> ServerPos.resolve tast_env
|> Pos.to_absolute
else
absolute_none
in
(* Figure out how to display them *)
let complete =
{
res_decl_pos;
res_replace_pos = replace_pos_of_id id;
res_base_class = None;
res_detail;
res_label;
res_insert_text;
res_fullname;
res_kind = r.si_kind;
res_documentation = None;
res_filter_text = None;
res_additional_edits = [];
}
in
add_res complete);
(* Add any builtins that match *)
match completion_type with
| Acid
| Actrait_only
| Ac_workspace_symbol
| Acnew ->
()
| Actype ->
builtin_type_hints
|> List.filter ~f:(fun (_, name) ->
String.is_prefix name ~prefix:query_text)
|> List.iter ~f:(fun (hint, name) ->
let kind = SI_Typedef in
let documentation = SymbolOccurrence.built_in_type_hover hint in
add_res
{
res_decl_pos = absolute_none;
res_replace_pos = replace_pos_of_id id;
res_base_class = None;
res_detail = "builtin";
res_label = name;
res_insert_text = InsertLiterally name;
res_fullname = name;
res_kind = kind;
res_documentation = Some documentation;
res_filter_text = None;
res_additional_edits = [];
})
let complete_xhp_tag
~(id : Pos.t * string)
~(does_autocomplete_snippet : bool)
~(sienv_ref : SearchUtils.si_env ref)
~(pctx : Provider_context.t) : unit =
let tast_env = Tast_env.empty pctx in
let query_text = strip_suffix (snd id) in
let query_text = Utils.strip_ns query_text in
auto_complete_for_global := query_text;
let absolute_none = Pos.none |> Pos.to_absolute in
let (results, _is_complete) =
SymbolIndex.find_matching_symbols
~sienv_ref
~query_text
~max_results
~kind_filter:None
~context:Acid
in
List.iter results ~f:(fun r ->
let (res_label, res_fullname) =
(Utils.strip_xhp_ns r.si_name, Utils.add_xhp_ns r.si_fullname)
in
let (res_detail, res_insert_text) =
(kind_to_string r.si_kind, InsertLiterally res_label)
in
let res_insert_text =
match r.si_kind with
| SI_XHP
| SI_Class
when does_autocomplete_snippet ->
let classname = Utils.add_ns res_fullname in
let attrs =
get_class_req_attrs tast_env pctx classname (Some (Aast.CI id))
in
let has_children = not (get_class_is_child_empty pctx classname) in
insert_text_for_xhp_req_attrs res_label attrs has_children
| _ -> res_insert_text
in
(* Figure out how to display them *)
let complete =
{
res_decl_pos = absolute_none;
res_replace_pos = replace_pos_of_id ~strip_xhp_colon:true id;
res_base_class = None;
res_detail;
res_label;
res_insert_text;
res_fullname;
res_kind = r.si_kind;
res_documentation = None;
res_filter_text = None;
res_additional_edits = [];
}
in
add_res complete);
autocomplete_is_complete := List.length !autocomplete_items < max_results
let auto_complete_suffix_finder =
object
inherit [_] Aast.reduce
method zero = false
method plus = ( || )
method! on_Lvar () (_, id) =
matches_auto_complete_suffix (Local_id.get_name id)
end
let method_contains_cursor = auto_complete_suffix_finder#on_method_ ()
let fun_contains_cursor = auto_complete_suffix_finder#on_fun_ ()
(* Find all the local variables before the cursor, so we can offer them as completion candidates. *)
class local_vars =
object (self)
inherit Tast_visitor.iter as super
val mutable results = Local_id.Map.empty
val mutable id_at_cursor = None
method get_locals ctx tast =
self#go ctx tast;
(results, id_at_cursor)
method add id ty =
(* If we already have a position for this identifier, don't overwrite it with
results from after the cursor position. *)
if not (Local_id.Map.mem id results && Option.is_some id_at_cursor) then
results <- Local_id.Map.add id ty results
method! on_fun_ env f = if fun_contains_cursor f then super#on_fun_ env f
method! on_method_ env m =
if method_contains_cursor m then (
if not m.Aast.m_static then
self#add Typing_defs.this (Tast_env.get_self_ty_exn env);
super#on_method_ env m
)
method! on_expr env e =
let (ty, _, e_) = e in
match e_ with
| Aast.Lvar (pos, id) ->
let name = Local_id.get_name id in
if matches_auto_complete_suffix name then
id_at_cursor <- Some (pos, name)
else
self#add id ty
| Aast.(Binop { bop = Ast_defs.Eq _; lhs = e1; rhs = e2 }) ->
(* Process the rvalue before the lvalue, since the lvalue is annotated
with its type after the assignment. *)
self#on_expr env e2;
self#on_expr env e1
| _ -> super#on_expr env e
method! on_fun_param _env fp =
let id = Local_id.make_unscoped fp.Aast.param_name in
let ty = fp.Aast.param_annotation in
self#add id ty
end
let compute_complete_local env ctx tast =
let (locals, id_at_cursor) = (new local_vars)#get_locals ctx tast in
let id_at_cursor = Option.value id_at_cursor ~default:(Pos.none, "") in
let replace_pos = replace_pos_of_id id_at_cursor in
let id_prefix =
if is_auto_complete (snd id_at_cursor) then
strip_suffix (snd id_at_cursor)
else
""
in
Local_id.Map.iter
(fun id ty ->
let kind = SearchTypes.SI_LocalVariable in
let name = Local_id.get_name id in
if String.is_prefix name ~prefix:id_prefix then
let complete =
{
res_decl_pos = get_pos_for env (LoclTy ty);
res_replace_pos = replace_pos;
res_base_class = None;
res_detail = Tast_env.print_ty env ty;
res_label = name;
res_insert_text = InsertLiterally name;
res_fullname = name;
res_kind = kind;
res_documentation = None;
res_filter_text = None;
res_additional_edits = [];
}
in
add_res complete)
locals
(* Walk the TAST and append autocomplete results for
any syntax that contains AUTO332 in its name. *)
let visitor
(ctx : Provider_context.t)
(autocomplete_context : legacy_autocomplete_context)
(sienv_ref : si_env ref)
(naming_table : Naming_table.t)
(toplevel_tast : Tast.def list) =
object (self)
inherit Tast_visitor.iter as super
method complete_global
(env : Tast_env.env) (id : sid) (completion_type : autocomplete_type)
: unit =
if is_auto_complete (snd id) then
find_global_results
~env
~id
~completion_type
~autocomplete_context
~sienv_ref
~pctx:ctx
method complete_id env (id : Ast_defs.id) : unit =
self#complete_global env id Acid
method! on_def env d =
match d with
| Aast.Stmt _ ->
(* Don't try to complete top-level statements. If we see
'fAUTO332' the user will be expecting us to complete
'function', not a top-level expression
'foo_type::method()`. *)
()
| _ -> super#on_def env d
method! on_Id env id =
autocomplete_id id;
self#complete_id env id;
super#on_Id env id
method! on_Call env call =
let Aast.{ func; args; _ } = call in
autocomplete_enum_class_label_call env func args;
super#on_Call env call
method! on_New env ((_, _, cid_) as cid) el unpacked_element =
(match cid_ with
| Aast.CI id -> self#complete_global env id Acnew
| _ -> ());
super#on_New env cid el unpacked_element
method! on_Happly env sid hl =
self#complete_global env sid Actype;
super#on_Happly env sid hl
method! on_Haccess env h ids =
autocomplete_class_type_const env h ids;
super#on_Haccess env h ids
method! on_Lvar env ((_, name) as lid) =
if is_auto_complete (Local_id.get_name name) then
compute_complete_local env ctx toplevel_tast;
super#on_Lvar env lid
method! on_Class_get env cid mid prop_or_method =
match mid with
| Aast.CGstring p ->
autocomplete_static_member autocomplete_context env cid p
| Aast.CGexpr _ -> super#on_Class_get env cid mid prop_or_method
method! on_Class_const env cid mid =
autocomplete_static_member autocomplete_context env cid mid;
super#on_Class_const env cid mid
method! on_Obj_get env obj mid ognf =
(match mid with
| (_, _, Aast.Id mid) ->
autocomplete_hack_fake_arrow env obj mid naming_table;
autocomplete_typed_member
~is_static:false
autocomplete_context
env
(get_type obj)
None
mid
| _ -> ());
super#on_Obj_get env obj mid ognf
method! on_expr env expr =
(match expr with
| (_, _, Aast.Array_get (arr, Some (_, pos, key))) ->
let ty = get_type arr in
let ty = expand_and_strip_dynamic env ty in
begin
match get_node ty with
| Tshape { s_fields = fields; _ } ->
(match key with
| Aast.Id (_, mid) ->
autocomplete_shape_key autocomplete_context env fields (pos, mid)
| Aast.String mid ->
(* autocomplete generally assumes that there's a token ending with the suffix; *)
(* This isn't the case for `$shape['a`, unless it's at the end of the file *)
let offset =
String_utils.substring_index
AutocompleteTypes.autocomplete_token
mid
in
if Int.equal offset (-1) then
autocomplete_shape_key autocomplete_context env fields (pos, mid)
else
let mid =
Str.string_before
mid
(offset + AutocompleteTypes.autocomplete_token_length)
in
let (line, bol, start_offset) = Pos.line_beg_offset pos in
let pos =
Pos.make_from_lnum_bol_offset
~pos_file:(Pos.filename pos)
~pos_start:(line, bol, start_offset)
~pos_end:
( line,
bol,
start_offset
+ offset
+ AutocompleteTypes.autocomplete_token_length )
in
autocomplete_shape_key autocomplete_context env fields (pos, mid)
| _ -> ())
| _ -> ()
end
| (_, _, Aast.(Call { func = (recv_ty, _, _); args; _ })) ->
(* Functions that support dynamic will be wrapped by supportdyn<_> *)
let recv_ty = expand_and_strip_supportdyn env recv_ty in
(match deref recv_ty with
| (_r, Tfun ft) ->
autocomplete_shape_literal_in_call env ft args;
autocomplete_enum_value_in_call env ft args
| _ -> ())
| (_, p, Aast.EnumClassLabel (opt_cname, n)) when is_auto_complete n ->
autocomplete_enum_class_label env opt_cname (p, n) None
| (_, _, Aast.Efun { Aast.ef_fun = f; _ })
| (_, _, Aast.Lfun (f, _)) ->
List.iter f.Aast.f_user_attributes ~f:(fun ua ->
autocomplete_builtin_attribute
ua.Aast.ua_name
Naming_special_names.AttributeKinds.lambda)
| _ -> ());
super#on_expr env expr
method! on_Xml env sid attrs el =
autocomplete_id sid;
if is_auto_complete (snd sid) then
complete_xhp_tag
~id:sid
~does_autocomplete_snippet:(List.length attrs <= 0)
~sienv_ref
~pctx:ctx;
let cid = Aast.CI sid in
Decl_provider.get_class (Tast_env.get_ctx env) (snd sid)
|> Option.iter ~f:(fun (c : Cls.t) ->
List.iter attrs ~f:(function
| Aast.Xhp_simple
{ Aast.xs_name = id; xs_expr = value; xs_type = ty } ->
(match value with
| (_, _, Aast.Id id_id) ->
(* This handles the situation
<foo:bar my-attribute={AUTO332}
*)
autocomplete_xhp_enum_attribute_value
(snd id)
ty
id_id
env
c;
autocomplete_xhp_enum_class_value ty id_id env;
autocomplete_xhp_bool_value ty id_id env
| _ -> ());
if Cls.is_xhp c then
autocomplete_xhp_attributes env c (Some cid) id attrs
else
autocomplete_member
~is_static:false
autocomplete_context
env
c
(Some cid)
id
| Aast.Xhp_spread _ -> ()));
super#on_Xml env sid attrs el
method! on_typedef env t =
List.iter t.Aast.t_user_attributes ~f:(fun ua ->
autocomplete_builtin_attribute
ua.Aast.ua_name
Naming_special_names.AttributeKinds.typealias);
super#on_typedef env t
method! on_fun_def env fd =
List.iter fd.Aast.fd_fun.Aast.f_user_attributes ~f:(fun ua ->
autocomplete_builtin_attribute
ua.Aast.ua_name
Naming_special_names.AttributeKinds.fn);
super#on_fun_def env fd
method! on_fun_param env fp =
List.iter fp.Aast.param_user_attributes ~f:(fun ua ->
autocomplete_builtin_attribute
ua.Aast.ua_name
Naming_special_names.AttributeKinds.parameter);
super#on_fun_param env fp
method! on_tparam env tp =
List.iter tp.Aast.tp_user_attributes ~f:(fun ua ->
autocomplete_builtin_attribute
ua.Aast.ua_name
Naming_special_names.AttributeKinds.typeparam);
super#on_tparam env tp
method! on_method_ env m =
autocomplete_overriding_method env m;
List.iter m.Aast.m_user_attributes ~f:(fun ua ->
autocomplete_builtin_attribute
ua.Aast.ua_name
Naming_special_names.AttributeKinds.mthd);
super#on_method_ env m
method! on_class_var env cv =
List.iter cv.Aast.cv_user_attributes ~f:(fun ua ->
autocomplete_builtin_attribute
ua.Aast.ua_name
(if cv.Aast.cv_is_static then
Naming_special_names.AttributeKinds.staticProperty
else
Naming_special_names.AttributeKinds.instProperty));
super#on_class_var env cv
method! on_class_typeconst_def env ctd =
List.iter ctd.Aast.c_tconst_user_attributes ~f:(fun ua ->
autocomplete_builtin_attribute
ua.Aast.ua_name
Naming_special_names.AttributeKinds.typeconst);
super#on_class_typeconst_def env ctd
method! on_class_ env cls =
List.iter cls.Aast.c_user_attributes ~f:(fun ua ->
autocomplete_builtin_attribute
ua.Aast.ua_name
Naming_special_names.AttributeKinds.cls);
List.iter cls.Aast.c_uses ~f:(fun hint ->
match snd hint with
| Aast.Happly (id, params) ->
self#complete_global env id Actrait_only;
List.iter params ~f:(self#on_hint env)
| _ -> ());
(* Ignore properties on interfaces. They're not legal syntax, but
they can occur when we parse partial method definitions. *)
let cls =
match cls.Aast.c_kind with
| Ast_defs.Cinterface -> { cls with Aast.c_vars = [] }
| _ -> cls
in
(* If we don't clear out c_uses we'll end up overwriting the trait
completion as soon as we get to on_Happly. *)
super#on_class_ env { cls with Aast.c_uses = [] }
method! on_Switch env expr cases default_case =
autocomplete_enum_case env expr cases;
super#on_Switch env expr cases default_case
end
let reset () =
auto_complete_for_global := "";
autocomplete_items := [];
autocomplete_is_complete := true
let complete_keywords_at possible_keywords text pos : unit =
if is_auto_complete text then
let prefix = strip_suffix text in
possible_keywords
|> List.filter ~f:(fun possible_keyword ->
String.is_prefix possible_keyword ~prefix)
|> List.iter ~f:(fun keyword ->
let kind = SI_Keyword in
let complete =
{
res_decl_pos = Pos.none |> Pos.to_absolute;
res_replace_pos = replace_pos_of_id (pos, text);
res_base_class = None;
res_detail = kind_to_string kind;
res_label = keyword;
res_insert_text = InsertLiterally keyword;
res_fullname = keyword;
res_kind = kind;
res_documentation = None;
res_filter_text = None;
res_additional_edits = [];
}
in
add_res complete)
let complete_keywords_at_token possible_keywords filename (s : Syntax.t) : unit
=
let token_str = Syntax.text s in
match s.Syntax.syntax with
| Syntax.Token t ->
let start_offset = t.Syntax.Token.offset + t.Syntax.Token.leading_width in
let end_offset = start_offset + t.Syntax.Token.width in
let source_text = t.Syntax.Token.source_text in
let pos =
Full_fidelity_source_text.relative_pos
filename
source_text
start_offset
end_offset
in
complete_keywords_at possible_keywords token_str pos
| _ -> ()
let complete_keywords_at_trivia possible_keywords filename (t : Trivia.t) : unit
=
let trivia_str = Trivia.text t in
match Trivia.kind t with
| Trivia.TriviaKind.ExtraTokenError when is_auto_complete trivia_str ->
let start_offset = t.Trivia.offset in
let end_offset = start_offset + t.Trivia.width in
let source_text = t.Trivia.source_text in
let pos =
Full_fidelity_source_text.relative_pos
filename
source_text
start_offset
end_offset
in
complete_keywords_at possible_keywords trivia_str pos
| _ -> ()
let def_start_keywords filename s : unit =
let possible_keywords =
[
"function";
(* `async` at the top level can occur for functions. *)
"async";
"class";
"trait";
"interface";
"type";
"newtype";
"enum";
]
in
complete_keywords_at_token possible_keywords filename s
let class_member_start_keywords filename s (ctx : Ast_defs.classish_kind option)
: unit =
let visibility_keywords = ["public"; "protected"] in
let const_type_keywords = ["const"; "abstract"] in
(* Keywords allowed on class and trait methods, but not allowed on interface methods. *)
let concrete_method_keywords = ["private"; "final"] in
let trait_member_keywords =
["require extends"; "require implements"; "require class"]
in
let inclusion_keywords = ["use"] in
let possible_keywords =
match ctx with
| Some (Ast_defs.Cclass _) ->
visibility_keywords
@ const_type_keywords
@ concrete_method_keywords
@ inclusion_keywords
| Some Ast_defs.Cinterface -> visibility_keywords @ const_type_keywords
| Some Ast_defs.Ctrait ->
visibility_keywords
@ const_type_keywords
@ concrete_method_keywords
@ trait_member_keywords
@ inclusion_keywords
| _ -> []
in
complete_keywords_at_token possible_keywords filename s
(* Drop the items from [possible_keywords] if they're already in
[existing_modifiers], and drop visibility keywords if we already
have any visibility keyword. *)
let available_keywords existing_modifiers possible_keywords : string list =
let current_modifiers =
Syntax.syntax_node_to_list existing_modifiers
|> List.filter_map ~f:(fun s ->
match s.Syntax.syntax with
| Syntax.Token _ -> Some (Syntax.text s)
| _ -> None)
in
let visibility_modifiers = SSet.of_list ["public"; "protected"; "private"] in
let has_visibility =
List.exists current_modifiers ~f:(fun kw ->
SSet.mem kw visibility_modifiers)
in
List.filter possible_keywords ~f:(fun kw ->
(not (List.mem current_modifiers kw ~equal:String.equal))
&& not (SSet.mem kw visibility_modifiers && has_visibility))
let class_keywords filename existing_modifiers s : unit =
let possible_keywords =
available_keywords existing_modifiers ["final"; "abstract"; "class"]
in
complete_keywords_at_token possible_keywords filename s
let method_keywords filename trivia =
complete_keywords_at_trivia
["public"; "protected"; "private"; "static"; "abstract"; "final"; "async"]
filename
trivia
let classish_after_name_keywords filename ctx ~has_extends trivia =
let possible_keywords =
match ctx with
| Some (Ast_defs.Cclass _) ->
if has_extends then
["implements"]
else
["implements"; "extends"]
| Some Ast_defs.Cinterface -> ["extends"]
| Some Ast_defs.Ctrait -> ["implements"]
| _ -> []
in
complete_keywords_at_trivia possible_keywords filename trivia
let interface_method_keywords filename existing_modifiers s : unit =
let possible_keywords =
available_keywords
existing_modifiers
["public"; "protected"; "private"; "static"; "function"]
in
complete_keywords_at_token possible_keywords filename s
let property_or_method_keywords filename existing_modifiers s : unit =
let possible_keywords =
available_keywords
existing_modifiers
[
"public";
"protected";
"private";
"static";
"abstract";
"final";
"async";
"function";
]
in
complete_keywords_at_token possible_keywords filename s
let keywords filename tree : unit =
let open Syntax in
let rec aux (ctx : Ast_defs.classish_kind option) s =
let inner_ctx = ref ctx in
(match s.syntax with
| Script sd ->
List.iter (syntax_node_to_list sd.script_declarations) ~f:(fun d ->
(* If we see AUTO332 at the top-level it's parsed as an
expression, but the user is about to write a top-level
definition (function, class etc). *)
match d.syntax with
| ExpressionStatement es ->
def_start_keywords filename es.expression_statement_expression
| _ -> ())
| NamespaceBody nb ->
List.iter (syntax_node_to_list nb.namespace_declarations) ~f:(fun d ->
match d.syntax with
(* Treat expressions in namespaces consistently with
top-level expressions. *)
| ExpressionStatement es ->
def_start_keywords filename es.expression_statement_expression
| _ -> ())
| FunctionDeclarationHeader fdh ->
(match fdh.function_keyword.syntax with
| Missing ->
(* The user has written `async AUTO332`, so we're expecting `function`. *)
complete_keywords_at_token ["function"] filename fdh.function_name
| _ -> ())
| ClassishDeclaration cd ->
(match cd.classish_keyword.syntax with
| Missing ->
(* The user has written `final AUTO332` or `abstract AUTO332`,
so we're expecting a class, not an interface or trait. *)
class_keywords filename cd.classish_modifiers cd.classish_name
| Token _ ->
(match Syntax.text cd.classish_keyword with
| "interface" -> inner_ctx := Some Ast_defs.Cinterface
| "class" ->
(* We're only interested if the context is a class or not,
so arbitrarily consider this a concrete class. *)
inner_ctx := Some (Ast_defs.Cclass Ast_defs.Concrete)
| "trait" -> inner_ctx := Some Ast_defs.Ctrait
| "enum" -> inner_ctx := Some Ast_defs.Cenum
| _ -> ())
| _ -> ());
(match cd.classish_body.syntax with
| ClassishBody cb ->
let has_extends =
match cd.classish_extends_keyword.syntax with
| Token _ -> true
| _ -> false
in
(match cb.classish_body_left_brace.syntax with
| Token t ->
(* The user has written `class Foo AUTO332`, so we're
expecting `extends` or `implements`.*)
List.iter
(Syntax.Token.leading t)
~f:(classish_after_name_keywords filename !inner_ctx ~has_extends)
| _ -> ())
| _ -> ())
| ClassishBody cb ->
List.iter (syntax_node_to_list cb.classish_body_elements) ~f:(fun d ->
match d.syntax with
| ErrorSyntax { error_error } ->
(match
( Syntax.leading_width error_error,
Syntax.trailing_width error_error )
with
| (0, 0) ->
(* If there's no leading or trailing whitespace, the
user has their cursor between the curly braces.
class Foo {AUTO332}
We don't want to offer completion here, because it
interferes with pressing enter to insert a
newline. *)
()
| _ -> class_member_start_keywords filename error_error !inner_ctx)
| _ -> ())
| MethodishDeclaration md ->
let header = md.methodish_function_decl_header in
(match header.syntax with
| FunctionDeclarationHeader fdh ->
(match fdh.function_keyword.syntax with
| Token t ->
(* The user has written `public AUTO332 function`, so we're expecting
method modifiers like `static`. *)
List.iter (Syntax.Token.leading t) ~f:(method_keywords filename)
| _ -> ())
| _ -> ())
| PropertyDeclaration pd ->
(match (pd.property_type.syntax, ctx) with
| (SimpleTypeSpecifier sts, Some Ast_defs.Cinterface) ->
(* Interfaces cannot contain properties, and have fewer
modifiers available on methods. *)
interface_method_keywords
filename
pd.property_modifiers
sts.simple_type_specifier
| (SimpleTypeSpecifier sts, _) ->
(* The user has written `public AUTO332`. This could be a method
`public function foo(): void {}` or a property
`public int $x = 1;`. *)
property_or_method_keywords
filename
pd.property_modifiers
sts.simple_type_specifier
| _ -> ())
| _ -> ());
List.iter (children s) ~f:(aux !inner_ctx)
in
aux None tree
(* Main entry point for autocomplete *)
let go_ctx
~(ctx : Provider_context.t)
~(entry : Provider_context.entry)
~(autocomplete_context : AutocompleteTypes.legacy_autocomplete_context)
~(sienv_ref : SearchUtils.si_env ref)
~(naming_table : Naming_table.t) =
reset ();
let cst = Ast_provider.compute_cst ~ctx ~entry in
let tree = Provider_context.PositionedSyntaxTree.root cst in
keywords entry.Provider_context.path tree;
let { Tast_provider.Compute_tast.tast; _ } =
Tast_provider.compute_tast_quarantined ~ctx ~entry
in
let tast = tast.Tast_with_dynamic.under_normal_assumptions in
(visitor ctx autocomplete_context sienv_ref naming_table tast)#go ctx tast;
Errors.ignore_ (fun () ->
let start_time = Unix.gettimeofday () in
let autocomplete_items = !autocomplete_items in
let results =
{
With_complete_flag.is_complete = !autocomplete_is_complete;
value = autocomplete_items;
}
in
SymbolIndexCore.log_symbol_index_search
~sienv:!sienv_ref
~start_time
~query_text:!auto_complete_for_global
~max_results
~kind_filter:None
~results:(List.length results.With_complete_flag.value)
~caller:"AutocompleteService.go";
results) |
OCaml Interface | hhvm/hphp/hack/src/server/autocompleteService.mli | (*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
val add_position_to_results :
Provider_context.t -> SearchTypes.si_item list -> SearchUtils.result
val autocomplete_result_to_json :
AutocompleteTypes.autocomplete_item -> Hh_json.json
val go_ctx :
ctx:Provider_context.t ->
entry:Provider_context.entry ->
autocomplete_context:AutocompleteTypes.legacy_autocomplete_context ->
sienv_ref:SearchUtils.si_env ref ->
naming_table:Naming_table.t ->
AutocompleteTypes.autocomplete_item list Utils.With_complete_flag.t
val get_snippet_for_xhp_classname :
Decl_provider.type_key -> Provider_context.t -> Tast_env.env -> string option |
OCaml | hhvm/hphp/hack/src/server/autocompleteTypes.ml | (*
* Copyright (c) 2017, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
type snippet_with_fallback = {
snippet: string;
fallback: string;
}
type insert_text =
| InsertLiterally of string
| InsertAsSnippet of snippet_with_fallback
type autocomplete_item = {
res_decl_pos: Pos.absolute;
res_replace_pos: Ide_api_types.range;
res_base_class: string option;
res_label: string;
res_insert_text: insert_text;
res_detail: string;
res_filter_text: string option;
res_additional_edits: (string * Ide_api_types.range) list;
res_fullname: string;
res_kind: SearchTypes.si_kind;
res_documentation: string option;
}
(* The type returned to the client *)
type ide_result = {
completions: autocomplete_item list;
char_at_pos: char;
is_complete: bool;
}
type result = autocomplete_item list
type legacy_autocomplete_context = {
is_manually_invoked: bool;
is_after_single_colon: bool;
is_after_double_right_angle_bracket: bool;
is_after_open_square_bracket: bool;
is_after_quote: bool;
is_before_apostrophe: bool;
is_open_curly_without_equals: bool;
char_at_pos: char;
}
(* Autocomplete token *)
let autocomplete_token = "AUTO332"
(* Autocomplete token length *)
let autocomplete_token_length = 7 |
OCaml Interface | hhvm/hphp/hack/src/server/autocompleteTypes.mli | (*
* Copyright (c) 2017, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
type snippet_with_fallback = {
snippet: string;
fallback: string;
}
(** Whether the inserted text should be treated as literal text or a template with placeholders.
https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#insertTextFormat *)
type insert_text =
| InsertLiterally of string
| InsertAsSnippet of snippet_with_fallback
type autocomplete_item = {
(* The position of the declaration we're returning. *)
res_decl_pos: Pos.absolute;
(* The position in the opened file that we're replacing with res_insert_text. *)
res_replace_pos: Ide_api_types.range;
(* If we're autocompleting a method, store the class name of the variable
we're calling the method on (for doc block fallback in autocomplete
resolution). *)
res_base_class: string option;
(* These strings correspond to the LSP fields in CompletionItem. *)
res_label: string;
res_insert_text: insert_text;
res_detail: string;
res_filter_text: string option;
res_additional_edits: (string * Ide_api_types.range) list;
(* res_fullname is res_label without trimming the namespace. *)
res_fullname: string;
res_kind: SearchTypes.si_kind;
(* documentation (in markdown); if absent, then it will be resolved on-demand later *)
res_documentation: string option;
}
(* The type returned to the client *)
type ide_result = {
completions: autocomplete_item list;
char_at_pos: char;
is_complete: bool;
}
type result = autocomplete_item list
type legacy_autocomplete_context = {
is_manually_invoked: bool;
is_after_single_colon: bool;
is_after_double_right_angle_bracket: bool;
is_after_open_square_bracket: bool;
is_after_quote: bool;
is_before_apostrophe: bool;
is_open_curly_without_equals: bool;
char_at_pos: char;
}
(* The standard autocomplete token, which is currently "AUTO332" *)
val autocomplete_token : string
(* The length of the standard autocomplete token *)
val autocomplete_token_length : int |
OCaml | hhvm/hphp/hack/src/server/clientProvider.ml | include
(val if Injector_config.use_test_stubbing then
(module TestClientProvider : ClientProvider_sig.S)
else
(module ServerClientProvider : ClientProvider_sig.S)) |
OCaml | hhvm/hphp/hack/src/server/clientProvider_sig.ml | (*
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
module type S = sig
type t
type client
type handoff = {
client: client;
m2s_sequence_number: int;
(** A unique number incremented for each client socket handoff from monitor to server.
Useful to correlate monitor and server logs. *)
}
(** Outcome of the POSIX [select] system call. *)
type select_outcome =
| Select_persistent
| Select_new of handoff
| Select_nothing
| Select_exception of Exception.t
| Not_selecting_hg_updating
exception Client_went_away
val provider_from_file_descriptors :
Unix.file_descr * Unix.file_descr * Unix.file_descr -> t
val provider_for_test : unit -> t
(** Wait up to 0.1 seconds and checks for new connection attempts.
Select what client to serve next and retrieve channels to
client from monitor process (connection hand-off). *)
val sleep_and_check :
t ->
(* Optional persistent client. *)
client option ->
ide_idle:
(* Whether the most recent message received from persistent client
* was IDE_IDLE *)
bool ->
idle_gc_slice:int ->
[ `Any | `Priority | `Force_dormant_start_only ] ->
select_outcome
val has_persistent_connection_request : client -> bool
val priority_fd : t -> Unix.file_descr option
val get_client_fd : client -> Unix.file_descr option
(** See explanation in Connection_tracker.track *)
val track :
key:Connection_tracker.key ->
?time:float ->
?log:bool ->
?msg:string ->
?long_delay_okay:bool ->
client ->
unit
val read_connection_type : client -> ServerCommandTypes.connection_type
val send_response_to_client : client -> 'a -> unit
val send_push_message_to_client : client -> ServerCommandTypes.push -> unit
val client_has_message : client -> bool
val read_client_msg : client -> 'a ServerCommandTypes.command
val make_persistent : client -> client
val is_persistent : client -> bool
val priority_to_string : client -> string
(** Shutdown socket connection to client *)
val shutdown_client : client -> unit
val ping : client -> unit
(* TODO: temporary way to break the module abstraction. Remove after
* converting all the callsites to use methods on this module instead of
* directly using channels. *)
val get_channels : client -> Timeout.in_channel * out_channel
end |
OCaml | hhvm/hphp/hack/src/server/client_command_handler.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.
*
*)
(* Warning 52 warns about using Sys_error.
* We have no alternative but to depend on Sys_error strings though. *)
[@@@warning "-52"]
let shutdown_persistent_client client env =
ClientProvider.shutdown_client client;
let env =
{
env with
ServerEnv.pending_command_needs_writes = None;
persistent_client_pending_command_needs_full_check = None;
}
in
ServerFileSync.clear_sync_data env
module Persistent : sig
val handle_client_command :
ServerEnv.genv ->
ServerEnv.env ->
ClientProvider.client ->
ServerEnv.env ServerUtils.handle_command_result
end = struct
let handle_persistent_client_command_exception
~(client : ClientProvider.client) ~(is_fatal : bool) (e : Exception.t) :
unit =
let open Marshal_tools in
let remote_e =
{
message = Exception.get_ctor_string e;
stack = Exception.get_backtrace_string e |> Exception.clean_stack;
}
in
let push =
if is_fatal then
ServerCommandTypes.FATAL_EXCEPTION remote_e
else
ServerCommandTypes.NONFATAL_EXCEPTION remote_e
in
begin
try ClientProvider.send_push_message_to_client client push with
| _ -> ()
end;
HackEventLogger.handle_persistent_connection_exception "inner" ~is_fatal e;
Hh_logger.error
"HANDLE_PERSISTENT_CONNECTION_EXCEPTION(inner) %s"
(Exception.to_string e);
()
(* Warning 52 warns about using Sys_error.
* We have no alternative but to depend on Sys_error strings though. *)
[@@@warning "-52"]
(* Same as handle_client_command_try, but for persistent clients *)
let handle_persistent_client_command_try
(type result)
~(return :
ServerEnv.env ->
finish_command_handling:_ ->
needs_writes:string option ->
result)
client
env
(command : unit -> result) : result =
try command () with
(* TODO: Make sure the pipe exception is really about this client. *)
| Unix.Unix_error (Unix.EPIPE, _, _)
| Sys_error "Connection reset by peer"
| Sys_error "Broken pipe"
| ServerCommandTypes.Read_command_timeout
| ServerClientProvider.Client_went_away ->
return
env
~finish_command_handling:(shutdown_persistent_client client)
~needs_writes:(Some "Client_went_away")
| ServerCommand.Nonfatal_rpc_exception (e, env) ->
handle_persistent_client_command_exception ~client ~is_fatal:false e;
return env ~finish_command_handling:(fun env -> env) ~needs_writes:None
| exn ->
let e = Exception.wrap exn in
handle_persistent_client_command_exception ~client ~is_fatal:true e;
let needs_writes = Some (Exception.to_string e) in
return
env
~finish_command_handling:(shutdown_persistent_client client)
~needs_writes
[@@@warning "+52"]
(* CARE! scope of suppression should be only handle_persistent_client_command_try *)
let handle_persistent_client_command_ genv env client :
ServerEnv.env ServerUtils.handle_command_result =
let return env ~finish_command_handling ~needs_writes =
match needs_writes with
| Some reason ->
ServerUtils.Needs_writes
{
env;
finish_command_handling;
recheck_restart_is_needed = true;
reason;
}
| None -> ServerUtils.Done (finish_command_handling env)
in
handle_persistent_client_command_try ~return client env @@ fun () ->
let env = { env with ServerEnv.ide_idle = false } in
ServerCommand.handle genv env client
let handle_client_command genv env client =
(* This "return" is guaranteed to be run as part of the main loop, when workers
* are not busy, so we can ignore whether it needs writes or not - it's always
* safe for it to write. *)
let return env ~finish_command_handling ~needs_writes:_ =
finish_command_handling env
in
handle_persistent_client_command_ genv env client
(* We wrap in handle_persistent_client_command_try a second time here.
The first time was within [handle_persistent_client_command_],
and was in order to handle exceptions when receiving the client message.
This second time is in order to handle exceptions during
executing the command and sending the response. *)
|> ServerUtils.wrap
~try_:(handle_persistent_client_command_try ~return client)
end
module NonPersistent : sig
val handle_client_command_or_persistent_connection :
ServerEnv.genv ->
ServerEnv.env ->
ClientProvider.client ->
ServerEnv.env ServerUtils.handle_command_result
end = struct
let handle_client_command_exception
~(env : ServerEnv.env) ~(client : ClientProvider.client) (e : Exception.t)
: ServerEnv.env =
match Exception.to_exn e with
| ClientProvider.Client_went_away
| ServerCommandTypes.Read_command_timeout ->
Hh_logger.log
"Client went away or server took too long to read command. Shutting down client socket.";
ClientProvider.shutdown_client client;
env
(* Connection dropped off. Its unforunate that we don't actually know
* which connection went bad (could be any write to any connection to
* child processes/daemons), we just assume at this top-level that
* since it's not caught elsewhere, it's the connection to the client.
*
* TODO: Make sure the pipe exception is really about this client.*)
| Unix.Unix_error (Unix.EPIPE, _, _)
| Sys_error "Broken pipe"
| Sys_error "Connection reset by peer" ->
Hh_logger.log "Client channel went bad. Shutting down client socket";
ClientProvider.shutdown_client client;
env
| exn ->
let e = Exception.wrap exn in
HackEventLogger.handle_connection_exception "inner" e;
Hh_logger.log
"HANDLE_CONNECTION_EXCEPTION(inner) %s"
(Exception.to_string e);
ClientProvider.shutdown_client client;
env
[@@@warning "+52"]
(* CARE! scope of suppression should be only handle_client_command_exception *)
(* [command] represents a non-persistent command coming from client. If executing [command]
* throws, we need to dispose of this client (possibly recovering updated
* environment from Nonfatal_rpc_exception). "return" is a constructor
* wrapping the return value to make it match return type of [command] *)
let handle_client_command_try return client env command =
try command () with
| ServerCommand.Nonfatal_rpc_exception (e, env) ->
return (handle_client_command_exception ~env ~client e)
| exn ->
let e = Exception.wrap exn in
return (handle_client_command_exception ~env ~client e)
let handle_client_command_or_persistent_connection_ genv env client =
ClientProvider.track
client
~key:Connection_tracker.Server_start_handle_connection;
handle_client_command_try (fun x -> ServerUtils.Done x) client env
@@ fun () ->
match ClientProvider.read_connection_type client with
| ServerCommandTypes.Persistent ->
Hh_logger.log "Handling persistent client connection.";
let handle_persistent_client_connection env =
let env =
match Ide_info_store.get_client () with
| Some old_client ->
ClientProvider.send_push_message_to_client
old_client
ServerCommandTypes.NEW_CLIENT_CONNECTED;
shutdown_persistent_client old_client env
| None -> env
in
ClientProvider.track client ~key:Connection_tracker.Server_start_handle;
ClientProvider.send_response_to_client
client
ServerCommandTypes.Connected;
Ide_info_store.new_ client;
(* If the client connected in the middle of recheck, let them know it's
* happening. *)
(if ServerEnv.is_full_check_started env.ServerEnv.full_check_status then
let (_ : ServerEnv.seconds option) =
ServerBusyStatus.send
(ServerCommandTypes.Doing_global_typecheck
(ServerCheckUtils.global_typecheck_kind genv env))
in
());
env
in
if
Option.is_some @@ Ide_info_store.get_client ()
(* Cleaning up after existing client (in shutdown_persistent_client)
* will attempt to write to shared memory *)
then (
Hh_logger.log
"There is already a persistent client: will handle new connection later.";
ServerUtils.Needs_writes
{
env;
finish_command_handling = handle_persistent_client_connection;
recheck_restart_is_needed = true;
reason = "Cleaning up persistent client";
}
) else
ServerUtils.Done (handle_persistent_client_connection env)
| ServerCommandTypes.Non_persistent ->
Hh_logger.log "Handling non-persistent client command.";
ServerCommand.handle genv env client
let handle_client_command_or_persistent_connection genv env client =
handle_client_command_or_persistent_connection_ genv env client
(* Similarly to persistent client commands, we wrap in handle_client_command_try a second time here. *)
|> ServerUtils.wrap ~try_:(handle_client_command_try (fun x -> x) client)
end
let handle_client_command_or_persistent_connection genv env client client_kind :
ServerEnv.env ServerUtils.handle_command_result =
ServerIdle.stamp_connection ();
match client_kind with
| `Persistent ->
Hh_logger.log ~category:"clients" "Handling persistent client command";
Persistent.handle_client_command genv env client
| `Non_persistent ->
Hh_logger.log
~category:"clients"
"Handling non-persistent client command or persistent client connection.";
NonPersistent.handle_client_command_or_persistent_connection genv env client |
OCaml Interface | hhvm/hphp/hack/src/server/client_command_handler.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.
*
*)
(** Handle client command messages and connections from persistent clients. *)
val handle_client_command_or_persistent_connection :
ServerEnv.genv ->
ServerEnv.env ->
ClientProvider.client ->
[< `Non_persistent | `Persistent ] ->
ServerEnv.env ServerUtils.handle_command_result |
OCaml | hhvm/hphp/hack/src/server/codemodTypePrinter.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 Typing_defs
exception Non_denotable
let strip_ns str =
let str' = Utils.strip_ns str in
(* If we had more than one '\\' patternm then we must keep the first '\\'
otherwise it will cause an error (we are detecting types from the root
namespace)*)
if String.contains str' '\\' then
str
else
str'
let rec print_ty_exn ?(allow_nothing = false) ty =
match get_node ty with
| Tprim p -> Aast_defs.string_of_tprim p
| Tunion [] when allow_nothing -> "nothing"
| Tany _
| Tvar _
| Tdependent _
| Tunion _
| Tintersection _
| Tneg _ ->
raise Non_denotable
| Tnonnull -> "nonnull"
| Tdynamic -> "dynamic"
| Tgeneric (s, []) -> s
| Tgeneric (s, targs) -> Utils.strip_ns s ^ "<" ^ print_tyl_exn targs ^ ">"
| Toption ty -> begin
match get_node ty with
| Tnonnull -> "mixed"
| _ -> "?" ^ print_ty_exn ty
end
| Tfun ft ->
let params = List.map ft.ft_params ~f:print_fun_param_exn in
let params =
if get_ft_variadic ft then
params @ ["..."]
else
params
in
Printf.sprintf
"(function(%s): %s)"
(String.concat ~sep:", " params)
(print_ty_exn ft.ft_ret.et_type)
| Ttuple tyl -> "(" ^ print_tyl_exn tyl ^ ")"
| Tshape { s_origin = _; s_unknown_value = shape_kind; s_fields = fdm } ->
let fields = List.map (TShapeMap.elements fdm) ~f:print_shape_field_exn in
let fields =
if is_nothing shape_kind then
fields
else
fields @ ["..."]
in
Printf.sprintf "shape(%s)" (String.concat ~sep:", " fields)
| Tunapplied_alias name
| Tnewtype (name, [], _) ->
Utils.strip_ns name
| Tnewtype (name, tyl, _) ->
Utils.strip_ns name ^ "<" ^ print_tyl_exn tyl ^ ">"
| Tclass ((_, name), _, []) -> strip_ns name
| Tclass ((_, name), _, tyl) ->
Utils.strip_ns name ^ "<" ^ print_tyl_exn tyl ^ ">"
| Tvec_or_dict (ty1, ty2) ->
Printf.sprintf "vec_or_dict<%s, %s>" (print_ty_exn ty1) (print_ty_exn ty2)
| Taccess (ty, id) -> Printf.sprintf "%s::%s" (print_ty_exn ty) (snd id)
and print_tyl_exn tyl = String.concat ~sep:", " (List.map tyl ~f:print_ty_exn)
and print_fun_param_exn param =
match get_fp_mode param with
| FPinout -> "inout " ^ print_ty_exn param.fp_type.et_type
| _ -> print_ty_exn param.fp_type.et_type
and print_shape_field_exn (name, { sft_optional; sft_ty; _ }) =
Printf.sprintf
"%s%s => %s"
(if sft_optional then
"?"
else
"")
(print_shape_field_name name)
(print_ty_exn sft_ty)
and print_shape_field_name name =
let s = Typing_defs.TShapeField.name name in
match name with
| Typing_defs.TSFlit_str _ -> "'" ^ s ^ "'"
| _ -> s
let print ?(allow_nothing = false) ty =
try Some (print_ty_exn ~allow_nothing ty) with
| Non_denotable -> None |
OCaml | hhvm/hphp/hack/src/server/cstSearchService.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.
*
*)
module Hh_bucket = Bucket
open Hh_prelude
open Common
module Syntax = Full_fidelity_positioned_syntax
module SyntaxKind = Full_fidelity_syntax_kind
module SyntaxTree = Full_fidelity_syntax_tree.WithSyntax (Syntax)
(**
* A `SyntaxKind.t`. We can generate a string from a kind, but not the other way
* around, so we store the string value given to us in the input directly. Then,
* when examining a node to see if it's a match, we'll convert the node's kind
* to a string and simply use string comparison.
*
* (Note that multiple syntax kinds map to the same string anyways, so it would
* be hard to reverse the mapping.)
*)
type node_kind = NodeKind of string [@@deriving ord]
(**
* An identifier in the pattern used to identify the this node when returning
* the results of a match to the caller. This identifier may not be unique in
* the list of returned results.
*)
type match_name = MatchName of string [@@deriving ord]
(**
* The name of a child of a node.
*
* For example, a binary expression has three possible child names:
*
* * binary_left_operand
* * binary_operator
* * binary_right_operand
*
* See the FFP schema definition in `src/parser/schema/schema_definition.ml`.
* Note that `BinaryExpression` has the prefix of `binary` and children like
* `left_operand`. When combined, this forms the full name
* `binary_left_operand`.
*)
type child_type = ChildType of string
(**
* A query that can be run on the syntax tree. It will return the matched nodes
* of any matched `MatchPattern`s.
*)
type pattern =
(*
* Match any node with the given kind, and whose children match the given
* patterns.
*)
| NodePattern of {
kind: node_kind;
(*
* Mapping from child name to pattern that the child must satisfy.
* Children may be omitted from this map. No child type may be specified
* more than once.
*)
children: (child_type * pattern) list;
}
(* Match any missing node. *)
| MissingNodePattern
(*
* Return the given node in the result list, assuming that the pattern overall
* matches. (This pattern by itself always matches; it's often used with
* `AndPattern`).
*)
| MatchPattern of { match_name: match_name }
(*
* Matches a given node if there is descendant node matching the given pattern
* anywhere in the subtree underneath the parent node.
*)
| DescendantPattern of { pattern: pattern }
(*
* Matches a list node (such as a statement list) only if all the children at
* the given indexes match their respective patterns.
*)
| ListPattern of {
children: (int * pattern) list;
max_length: int option;
}
(*
* Matches a given node if its raw text is exactly the specified string. The
* "raw" text doesn't include trivia.
*)
| RawTextPattern of { raw_text: string }
(*
* Matches a given expression node if its type is a subtype of the given type.
* TODO: decide if we want to handle exact type equality or supertypes.
* TODO: decide what we want to name the pattern for decl types, if we create
* one.
*)
| TypePattern of { subtype_of: Typing_defs.locl_ty }
(*
* Matches if all of the children patterns match.
*)
| AndPattern of { patterns: pattern list }
(*
* Matches if any of the children patterns match.
*
* Note that currently:
*
* * This short-circuits, so the after any pattern succeeds, no other
* patterns will be evaluated. This means that if two patterns have
* `MatchPattern`s somewhere underneath them, then the `MatchPattern`s from
* at most one of these patterns will be included in the results.
* * The order in which the provided patterns are evaluated is not
* specified. (For example, in the future, we may want to order it so that
* patterns that rely only on syntactic information are executed before
* patterns that rely on type information.)
*
* Consequently, you shouldn't rely on `MatchPattern`s that are nested inside
* the constituent patterns.
*)
| OrPattern of { patterns: pattern list }
(*
* Matches only if the given pattern does not match.
*
* Regardless of whether the child pattern matches or not, any matches that it
* produced are thrown away. (In the case that it doesn't match, we don't keep
* around "witness" matches explaining why this `NotPattern` didn't match.)
*)
| NotPattern of { pattern: pattern }
type matched_node = {
match_name: match_name;
kind: node_kind;
start_offset: int;
end_offset: int;
}
[@@deriving ord]
type result = {
(*
* The list of nodes for which a `MatchPattern` matched.
*)
matched_nodes: matched_node list;
}
[@@deriving ord]
type rel_path_result = Relative_path.t * result [@@deriving ord]
type collected_type_map =
Tast_type_collector.collected_type list Pos.AbsolutePosMap.t
(* The environment used in searching a single file. *)
type env = {
ctx: Provider_context.t;
entry: Provider_context.entry;
collected_types: collected_type_map option;
}
let empty_result : result option = Some { matched_nodes = [] }
let merge_results (lhs : result option) (rhs : result option) : result option =
Option.merge lhs rhs ~f:(fun lhs rhs ->
{ matched_nodes = lhs.matched_nodes @ rhs.matched_nodes })
let find_child_with_type (node : Syntax.t) (child_type : child_type) :
Syntax.t option =
let child_index =
Syntax.children_names node
|> List.findi ~f:(fun _i actual_child_type ->
match child_type with
| ChildType expected_child_type ->
String.equal expected_child_type actual_child_type)
|> Option.map ~f:fst
in
match child_index with
| None -> None
| Some index -> List.nth (Syntax.children node) index
let collect_types (env : env) : env * collected_type_map =
match env with
| { collected_types = Some collected_types; _ } -> (env, collected_types)
| { collected_types = None; ctx; entry } ->
let { Tast_provider.Compute_tast.tast; _ } =
Tast_provider.compute_tast_unquarantined ~ctx ~entry
in
let collected_types =
Tast_type_collector.collect_types
env.ctx
tast.Tast_with_dynamic.under_normal_assumptions
in
let env = { env with collected_types = Some collected_types } in
(env, collected_types)
let rec search_node ~(env : env) ~(pattern : pattern) ~(node : Syntax.t) :
env * result option =
match pattern with
| NodePattern { kind; children } ->
let kind =
match kind with
| NodeKind kind -> kind
in
if not (String.equal (node |> Syntax.kind |> SyntaxKind.to_string) kind)
then
(env, None)
else
let patterns =
List.map children ~f:(fun (child_type, pattern) ->
let child_node = find_child_with_type node child_type in
let child_node = Option.value_exn child_node in
(child_node, pattern))
in
search_and ~env ~patterns
| MissingNodePattern ->
(match Syntax.kind node with
| SyntaxKind.Missing -> (env, empty_result)
| _ -> (env, None))
| MatchPattern { match_name } ->
let result =
{
matched_nodes =
[
{
match_name;
kind = NodeKind (SyntaxKind.to_string (Syntax.kind node));
start_offset = Syntax.start_offset node;
end_offset = Syntax.end_offset node;
};
];
}
in
(env, Some result)
| DescendantPattern { pattern } -> search_descendants ~env ~pattern ~node
| ListPattern { children; max_length } ->
let syntax_list =
Syntax.(
match node.syntax with
| SyntaxList syntax_list -> begin
match max_length with
| None -> Some syntax_list
| Some max_length ->
if List.length syntax_list <= max_length then
Some syntax_list
else
None
end
| _ -> None)
in
begin
match syntax_list with
| None -> (env, None)
| Some syntax_list ->
Option.Monad_infix.(
let patterns =
List.map children ~f:(fun (index, pattern) ->
List.nth syntax_list index >>| fun child_node ->
(child_node, pattern))
in
begin
match Option.all patterns with
| Some patterns -> search_and ~env ~patterns
| None ->
(* We tried to match a pattern for the child at at index N, but the syntax
list didn't have an Nth element. *)
(env, None)
end)
end
| RawTextPattern { raw_text } ->
if String.equal (Syntax.text node) raw_text then
(env, empty_result)
else
(env, None)
| TypePattern { subtype_of } ->
Line_break_map.reset_global_state ();
let pos = Syntax.position env.entry.Provider_context.path node in
begin
match pos with
| None -> (env, None)
| Some pos ->
let (env, collected_types) = collect_types env in
let pos = Pos.to_absolute pos in
let tys = Tast_type_collector.get_from_pos_map pos collected_types in
let is_subtype_of (tast_env, ty) =
match ty with
| Typing_defs.LoclTy ty -> Tast_env.can_subtype tast_env ty subtype_of
| Typing_defs.DeclTy _ty -> false
in
(match tys with
| Some tys when List.exists tys ~f:is_subtype_of -> (env, empty_result)
| Some _
| None ->
(env, None))
end
| AndPattern { patterns } ->
let patterns = List.map patterns ~f:(fun pattern -> (node, pattern)) in
search_and ~env ~patterns
| OrPattern { patterns } ->
let patterns = List.map patterns ~f:(fun pattern -> (node, pattern)) in
search_or ~env ~patterns
| NotPattern { pattern } ->
let (env, result) = search_node ~env ~node ~pattern in
begin
match result with
| Some _ -> (env, None)
| None -> (env, empty_result)
end
(* TODO: this will likely have to become more intelligent *)
and search_descendants ~(env : env) ~(pattern : pattern) ~(node : Syntax.t) :
env * result option =
List.fold_left_env
env
(Syntax.children node)
~init:None
~f:(fun env acc_result child ->
let (env, child_result) = search_node ~env ~pattern ~node:child in
let (env, descendants_result) =
search_descendants ~env ~pattern ~node:child
in
let result = merge_results child_result descendants_result in
(env, merge_results result acc_result))
and search_and ~(env : env) ~(patterns : (Syntax.t * pattern) list) :
env * result option =
List.fold_left_env
env
patterns
~init:empty_result
~f:(fun env result (node, pattern) ->
match result with
| None ->
(* Short-circuit. *)
(env, None)
| Some _ as result ->
let (env, pattern_result) = search_node ~env ~pattern ~node in
(match pattern_result with
| None -> (env, None)
| Some _ as pattern_result -> (env, merge_results result pattern_result)))
and search_or ~(env : env) ~(patterns : (Syntax.t * pattern) list) :
env * result option =
List.fold_left_env
env
patterns
~init:None
~f:(fun env result (node, pattern) ->
match result with
| Some _ as result ->
(* Short-circuit. *)
(env, result)
| None -> search_node ~env ~pattern ~node)
let compile_pattern (ctx : Provider_context.t) (json : Hh_json.json) :
(pattern, string) Result.t =
let open Result in
let open Result.Monad_infix in
let wrap_json_accessor f x =
Result.map_error (f x) ~f:Hh_json.Access.access_failure_to_string
in
let get_string x = wrap_json_accessor (Hh_json.Access.get_string x) in
let get_obj x = wrap_json_accessor (Hh_json.Access.get_obj x) in
let get_array x = wrap_json_accessor (Hh_json.Access.get_array x) in
let keytrace_to_string = Hh_json.Access.keytrace_to_string in
let error_at_keytrace ~keytrace error_message =
Error (error_message ^ keytrace_to_string keytrace)
in
let rec compile_pattern ~json ~keytrace : (pattern, string) Result.t =
get_string "pattern_type" (json, keytrace)
>>= fun (pattern_type, pattern_type_keytrace) ->
match pattern_type with
| "node_pattern" -> compile_node_pattern ~json ~keytrace
| "missing_node_pattern" -> compile_missing_node_pattern ~json ~keytrace
| "match_pattern" -> compile_match_pattern ~json ~keytrace
| "descendant_pattern" -> compile_descendant_pattern ~json ~keytrace
| "list_pattern" -> compile_list_pattern ~json ~keytrace
| "raw_text_pattern" -> compile_raw_text_pattern ~json ~keytrace
| "type_pattern" -> compile_type_pattern ~json ~keytrace
| "and_pattern" -> compile_and_pattern ~json ~keytrace
| "or_pattern" -> compile_or_pattern ~json ~keytrace
| "not_pattern" -> compile_not_pattern ~json ~keytrace
| pattern_type ->
error_at_keytrace
~keytrace:pattern_type_keytrace
(Printf.sprintf "Unknown pattern type '%s'" pattern_type)
and compile_node_pattern ~json ~keytrace : (pattern, string) Result.t =
get_string "kind" (json, keytrace) >>= fun (kind, kind_keytrace) ->
Schema_definition.(
let kind_info =
List.find schema ~f:(fun schema_node ->
String.equal schema_node.description kind)
in
match kind_info with
| None ->
error_at_keytrace
~keytrace:kind_keytrace
(Printf.sprintf "Kind '%s' doesn't exist" kind)
| Some kind_info ->
Ok kind_info >>= fun kind_info ->
get_obj "children" (json, keytrace)
>>= fun (children_json, children_keytrace) ->
(* This has already been verified to be an object above. *)
let children = Hh_json.get_object_exn children_json in
let get_child_type
(child_keytrace : Hh_json.Access.keytrace) (child_name : string) :
(child_type, string) Result.t =
(* We're given a field name like `binary_right_operand`, but the field
names in the schema are things like `right_operand`, and you have to
affix the prefix yourself. For consistency with other tooling, we want
to use `binary_right_operand` instead of just `right_operand`. *)
let get_prefixed_field_name field_name =
kind_info.prefix ^ "_" ^ field_name
in
let field =
List.find kind_info.fields ~f:(fun (field_name, _) ->
String.equal (get_prefixed_field_name field_name) child_name)
in
match field with
| None ->
let valid_types =
List.map kind_info.fields ~f:(fun (field_name, _) ->
get_prefixed_field_name field_name)
in
error_at_keytrace
~keytrace:child_keytrace
(Printf.sprintf
("Unknown child type '%s'; "
^^ "valid child types for a node of kind '%s' are: %s")
child_name
kind
(String.concat ~sep:", " valid_types))
| Some _ -> Ok (ChildType child_name)
in
let children_patterns =
List.mapi children ~f:(fun index (child_name, pattern_json) ->
let child_keytrace = string_of_int index :: children_keytrace in
get_child_type child_keytrace child_name >>= fun child_name ->
compile_pattern ~json:pattern_json ~keytrace:child_keytrace
>>| fun pattern -> (child_name, pattern))
in
all children_patterns >>| fun children ->
NodePattern { kind = NodeKind kind; children })
and compile_missing_node_pattern ~json:_json ~keytrace:_keytrace =
Ok MissingNodePattern
and compile_match_pattern ~json ~keytrace =
get_string "match_name" (json, keytrace)
>>| fun (match_name, _match_name_keytrace) ->
MatchPattern { match_name = MatchName match_name }
and compile_descendant_pattern ~json ~keytrace =
get_obj "pattern" (json, keytrace) >>= fun (pattern, pattern_keytrace) ->
compile_pattern ~json:pattern ~keytrace:pattern_keytrace >>| fun pattern ->
DescendantPattern { pattern }
and compile_list_pattern ~json ~keytrace =
let max_length =
Hh_json.get_field_opt (Hh_json.Access.get_number_int "max_length") json
in
get_obj "children" (json, keytrace)
>>= fun (children_json, children_keytrace) ->
(* This has already been verified to be an object above. *)
let children = Hh_json.get_object_exn children_json in
let children_patterns =
List.map children ~f:(fun (index_str, pattern_json) ->
let child_keytrace = index_str :: children_keytrace in
begin
match int_of_string_opt index_str with
| Some index -> Ok index
| None ->
error_at_keytrace
(Printf.sprintf "Invalid integer key: %s" index_str)
~keytrace:child_keytrace
end
>>= fun index ->
begin
if index >= 0 then
Ok index
else
error_at_keytrace
"Integer key must be non-negative"
~keytrace:child_keytrace
end
>>= fun index ->
compile_pattern ~json:pattern_json ~keytrace:child_keytrace
>>| fun pattern -> (index, pattern))
in
Result.all children_patterns >>| fun children ->
ListPattern { children; max_length }
and compile_raw_text_pattern ~json ~keytrace =
get_string "raw_text" (json, keytrace)
>>| fun (raw_text, _raw_text_keytrace) -> RawTextPattern { raw_text }
and compile_type_pattern ~json ~keytrace =
get_obj "subtype_of" (json, keytrace)
>>= fun (subtype_of_json, subtype_of_keytrace) ->
let locl_ty =
Typing_print.json_to_locl_ty
~keytrace:subtype_of_keytrace
ctx
subtype_of_json
in
match locl_ty with
| Ok locl_ty -> Ok (TypePattern { subtype_of = locl_ty })
| Error (Typing_defs.Wrong_phase message)
| Error (Typing_defs.Not_supported message)
| Error (Typing_defs.Deserialization_error message) ->
Error message
and compile_child_patterns_helper ~json ~keytrace =
get_array "patterns" (json, keytrace)
>>= fun (pattern_list, pattern_list_keytrace) ->
let compiled_patterns =
List.mapi pattern_list ~f:(fun i json ->
let keytrace = string_of_int i :: pattern_list_keytrace in
compile_pattern ~json ~keytrace)
in
Result.all compiled_patterns
and compile_and_pattern ~json ~keytrace =
compile_child_patterns_helper ~json ~keytrace >>| fun patterns ->
AndPattern { patterns }
and compile_or_pattern ~json ~keytrace =
compile_child_patterns_helper ~json ~keytrace >>| fun patterns ->
OrPattern { patterns }
and compile_not_pattern ~json ~keytrace =
get_obj "pattern" (json, keytrace) >>= fun (json, keytrace) ->
compile_pattern ~json ~keytrace >>| fun pattern -> NotPattern { pattern }
in
compile_pattern ~json ~keytrace:[]
let result_to_json ~(sort_results : bool) (result : result option) :
Hh_json.json =
let open Hh_json in
match result with
| None -> JSON_Null
| Some result ->
let matched_nodes = result.matched_nodes in
let matched_nodes =
if sort_results then
List.sort matched_nodes ~compare:compare_matched_node
else
matched_nodes
in
let matched_nodes =
List.map matched_nodes ~f:(fun matched_node ->
let match_name =
match matched_node.match_name with
| MatchName match_name -> match_name
in
let kind =
match matched_node.kind with
| NodeKind kind -> kind
in
JSON_Object
[
("match_name", JSON_String match_name);
("kind", JSON_String kind);
("start_offset", Hh_json.int_ matched_node.start_offset);
("end_offset", Hh_json.int_ matched_node.end_offset);
])
in
JSON_Object [("matched_nodes", JSON_Array matched_nodes)]
let search
(ctx : Provider_context.t)
(entry : Provider_context.entry)
(pattern : pattern) : result option =
let syntax_tree = Ast_provider.compute_cst ~ctx ~entry in
let env = { ctx; entry; collected_types = None } in
let (_env, result) =
search_node ~env ~pattern ~node:(SyntaxTree.root syntax_tree)
in
result
let go
(genv : ServerEnv.genv)
(env : ServerEnv.env)
~(sort_results : bool)
~(files_to_search : string list option)
(input : Hh_json.json) : (Hh_json.json, string) Result.t =
let open Result.Monad_infix in
let ctx = Provider_utils.ctx_from_server_env env in
compile_pattern ctx input >>| fun pattern ->
let num_files_searched = ref 0 in
let last_printed_num_files_searched = ref 0 in
let done_searching = ref false in
let progress_fn ~total:_total ~start:_start ~(length : int) : unit =
let is_bucket_empty = length = 0 in
if not !done_searching then (
num_files_searched := !num_files_searched + length;
if
!num_files_searched - !last_printed_num_files_searched >= 10000
|| is_bucket_empty
then (
ServerProgress.write
"CST search: searched %d files..."
!num_files_searched;
last_printed_num_files_searched := !num_files_searched
)
);
if is_bucket_empty then done_searching := true
in
let next_files : (Relative_path.t * pattern) list Hh_bucket.next =
let get_job_info path =
let path = Relative_path.create_detect_prefix path in
if Naming_table.has_file env.ServerEnv.naming_table path then
Some (path, pattern)
else
(* We may not have the file information for a file such as one that we
ignore in `.hhconfig`. *)
None
in
match files_to_search with
| Some files_to_search ->
let files_to_search =
Sys_utils.parse_path_list files_to_search
|> List.filter_map ~f:get_job_info
in
MultiWorker.next genv.ServerEnv.workers files_to_search ~progress_fn
| None ->
let indexer = genv.ServerEnv.indexer FindUtils.is_hack in
fun () ->
let files = indexer () |> List.filter_map ~f:get_job_info in
progress_fn ~total:0 ~start:0 ~length:(List.length files);
Hh_bucket.of_list files
in
let ctx = Provider_utils.ctx_from_server_env env in
let job
(acc : (Relative_path.t * result) list)
(inputs : (Relative_path.t * pattern) list) :
(Relative_path.t * result) list =
List.fold inputs ~init:acc ~f:(fun acc (path, pattern) ->
try
let (ctx, entry) = Provider_context.add_entry_if_missing ~ctx ~path in
match search ctx entry pattern with
| Some result -> (path, result) :: acc
| None -> acc
with
| exn ->
let e = Exception.wrap exn in
let prefix =
Printf.sprintf
"Error while running CST search on path %s:\n"
(Relative_path.to_absolute path)
in
Hh_logger.exception_ e ~prefix;
Exception.reraise e)
in
let results =
MultiWorker.call
genv.ServerEnv.workers
~job
~neutral:[]
~merge:List.rev_append
~next:next_files
in
let results =
if sort_results then
List.sort results ~compare:compare_rel_path_result
else
results
in
Hh_json.JSON_Object
(List.map results ~f:(fun (path, result) ->
( Relative_path.to_absolute path,
result_to_json ~sort_results (Some result) ))) |
OCaml Interface | hhvm/hphp/hack/src/server/cstSearchService.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.
*
*)
open Hh_prelude
type pattern
type result
(** Compile JSON input into a pattern that can be searched for. *)
val compile_pattern :
Provider_context.t -> Hh_json.json -> (pattern, string) Result.t
(** Convert the result of a search into JSON output that can be sent back to the
user. *)
val result_to_json : sort_results:bool -> result option -> Hh_json.json
(** Search for the given pattern across the given set of files. *)
val go :
ServerEnv.genv ->
ServerEnv.env ->
sort_results:bool ->
files_to_search:string list option ->
Hh_json.json ->
(Hh_json.json, string) Result.t
(** Execute a search on a single syntax tree. This is most useful in debugging
utilities like `hh_single_type_check`. *)
val search :
Provider_context.t -> Provider_context.entry -> pattern -> result option |
OCaml | hhvm/hphp/hack/src/server/customErrorConfig.ml | (*
* 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.
*
*)
let config_path_relative_to_repo_root = "CUSTOM_ERRORS.json"
let repo_config_path =
Relative_path.from_root ~suffix:config_path_relative_to_repo_root
let log_debug (msg : ('a, unit, string, string, string, unit) format6) : 'a =
Hh_logger.debug ~category:"custom errors" ?exn:None msg
let load_and_parse ?(path = repo_config_path) () =
match Custom_error_config.initialize (`Relative path) with
| Ok cfg ->
List.iter
(fun rule ->
log_debug "CustomErrorConfig bad rule: %s" rule.Custom_error.name)
cfg.Custom_error_config.invalid;
cfg
| Error msg ->
log_debug "CustomErrorConfig: %s" msg;
Hh_logger.log
~lvl:Hh_logger.Level.Fatal
"Custom errors config malformed: %s"
msg;
Exit.exit Exit_status.Config_error |
OCaml Interface | hhvm/hphp/hack/src/server/customErrorConfig.mli | (*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the "hack" directory of this source tree.
*
*)
val load_and_parse : ?path:Relative_path.t -> unit -> Custom_error_config.t
val repo_config_path : Relative_path.t |
OCaml | hhvm/hphp/hack/src/server/diagnostic_pusher.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 Option.Monad_infix
open Reordered_argument_collections
type error = Errors.error [@@deriving show]
type seconds_since_epoch = float
type phase = PhaseSingleton [@@deriving eq, show]
module PhaseMap = struct
include Reordered_argument_map (WrappedMap.Make (struct
type t = phase
let rank = function
| PhaseSingleton -> 4
let compare x y = rank x - rank y
end))
let pp pp_data = make_pp pp_phase pp_data
let show pp_data x = Format.asprintf "%a" (pp pp_data) x
end
module FileMap = Relative_path.Map
(** A 2D map from files to phases to errors, with the usual map helpers. *)
module ErrorMap = struct
type errors = error list [@@deriving show]
let equal_errors err1 err2 =
let err1 = Errors.ErrorSet.of_list err1 in
let err2 = Errors.ErrorSet.of_list err2 in
Errors.ErrorSet.equal err1 err2
type t = errors PhaseMap.t FileMap.t [@@deriving eq, show]
let remove map k1 k2 =
FileMap.find_opt map k1
>>| (fun inner_map -> PhaseMap.remove inner_map k2)
|> Option.fold ~init:map ~f:(fun map inner_map ->
if PhaseMap.is_empty inner_map then
FileMap.remove map k1
else
FileMap.add map ~key:k1 ~data:inner_map)
(** Set value in map for given file and phase.
If the file is not already present in the map, initialize its phase map
with the phase map for that file from [init_phase_map_from] *)
let set :
t -> Relative_path.t -> phase -> errors -> init_phase_map_from:t -> t =
fun map file phase data ~init_phase_map_from:init_map ->
FileMap.find_opt map file
|> Option.value
~default:
(FileMap.find_opt init_map file
|> Option.value ~default:PhaseMap.empty)
|> PhaseMap.add ~key:phase ~data
|> fun inner_map -> FileMap.add map ~key:file ~data:inner_map
let find_opt map k1 k2 =
FileMap.find_opt map k1 >>= fun inner_map -> PhaseMap.find_opt inner_map k2
let mem map k1 k2 = Option.is_some @@ find_opt map k1 k2
let files = FileMap.keys
end
(** This keeps track of the set of errors in the current LSP client and
the set of errors which still need to be pushed. *)
module ErrorTracker : sig
type t [@@deriving eq, show]
val init : t
(** Inform the tracker of a new batch of errors produced by the server for
a specific set of [rechecked] files, and
get the set of errors which need to be pushed.
This set may or may not contain the new errors, depending on what's in the IDE
and what was successfully pushed so far. *)
val get_errors_to_push :
t ->
rechecked:Relative_path.Set.t ->
new_errors:Errors.t ->
priority_files:Relative_path.Set.t option ->
t * ServerCommandTypes.diagnostic_errors
(** Inform the tracker that errors yet to be pushed have been successfully pushed
to the IDE. *)
val commit_pushed_errors : t -> t
(** Reset the tracker for when the previous client has been lost
and we have got / will get a new one. *)
val reset_for_new_client : t -> t
val get_files_with_diagnostics : t -> Relative_path.t list
(** Module to export internal functions for unit testing. Do not use in production code. *)
module TestExporter : sig
val make :
errors_in_ide:ErrorMap.t ->
to_push:ErrorMap.t ->
errors_beyond_limit:ErrorMap.t ->
t
val with_error_limit : int -> (unit -> 'result) -> 'result
end
end = struct
type t = {
errors_in_ide: ErrorMap.t;
(** The set of errors currently in the IDE, based on what has been pushed so far. *)
to_push: ErrorMap.t; (** The set of errors yet to be pushed to the IDE. *)
errors_beyond_limit: ErrorMap.t;
(** Errors beyond the limit on the number of errors we want to have in the IDE.
We may be able to send those later. *)
}
[@@deriving eq, show]
(** Limit on the number of errors we want to have in the IDE.
The IDE may not be very resonsive beyond this limit. *)
let default_error_limit = 1000
let error_limit : int ref = ref default_error_limit
let init =
{
errors_in_ide = FileMap.empty;
to_push = FileMap.empty;
errors_beyond_limit = FileMap.empty;
}
let error_count_in_phase_map : error list PhaseMap.t -> int =
PhaseMap.fold ~init:0 ~f:(fun _phase errors count ->
List.length errors + count)
let error_count_in_file_map : ErrorMap.t -> int =
FileMap.fold ~init:0 ~f:(fun _file phase_map count ->
error_count_in_phase_map phase_map + count)
(** For each file key from [rechecked] and for [phase], update value in [to_push] with value from
[new_error], possibly removing entry if there are no more errors.
[errors_in_ide] is used to possibly initialize other phases for a file in [to_push]. *)
let merge_errors_to_push :
ErrorMap.t ->
errors_in_ide:ErrorMap.t ->
rechecked:Relative_path.Set.t ->
new_errors:error list FileMap.t ->
phase:phase ->
ErrorMap.t =
fun to_push ~errors_in_ide ~rechecked ~new_errors ~phase ->
let to_push =
Relative_path.Set.fold
rechecked
~init:to_push
~f:(fun rechecked_file to_push ->
ErrorMap.remove to_push rechecked_file phase)
in
let to_push =
FileMap.fold new_errors ~init:to_push ~f:(fun file file_errors to_push ->
if List.is_empty file_errors then
(* We'll deal with erasing (which we do by sending the empty list) in erase_errors.
* This should normally not happen, we're just being defensive here. *)
to_push
else
ErrorMap.set
to_push
file
phase
file_errors
~init_phase_map_from:errors_in_ide)
in
to_push
(** Add [file -> phase -> []] entry in the [to_push] map for each file which used to have
errors but doesn't anymore. *)
let erase_errors :
errors_in_ide:ErrorMap.t ->
rechecked:Relative_path.Set.t ->
phase:phase ->
ErrorMap.t ->
ErrorMap.t =
fun ~errors_in_ide ~rechecked ~phase to_push ->
let rechecked_which_had_errors =
Relative_path.Set.filter rechecked ~f:(fun file ->
ErrorMap.mem errors_in_ide file phase)
in
let to_push =
Relative_path.Set.fold
rechecked_which_had_errors
~init:to_push
~f:(fun rechecked_file to_push ->
if ErrorMap.mem to_push rechecked_file phase then
to_push
else
ErrorMap.set
to_push
rechecked_file
phase
[]
~init_phase_map_from:errors_in_ide)
in
to_push
(** Truncate the list of errors to push so that the total number of errors
in the IDE does not exceed [error_limit]. This partitions the errors as
a set of errors we can push now and the remainder of the errors. *)
let truncate :
ErrorMap.t ->
errors_in_ide:ErrorMap.t ->
priority_files:Relative_path.Set.t option ->
ErrorMap.t * ErrorMap.t =
fun to_push_candidates ~errors_in_ide ~priority_files ->
let error_count_in_ide = error_count_in_file_map errors_in_ide in
let to_push = FileMap.empty in
(* First push errors in prority files, regardless of error limit. *)
let (to_push, to_push_candidates, error_count_in_ide) =
Relative_path.Set.fold
(priority_files |> Option.value ~default:Relative_path.Set.empty)
~init:(to_push, to_push_candidates, error_count_in_ide)
~f:(fun file (to_push, to_push_candidates, error_count_in_ide) ->
match FileMap.find_opt to_push_candidates file with
| None -> (to_push, to_push_candidates, error_count_in_ide)
| Some phase_map ->
let to_push = FileMap.add to_push ~key:file ~data:phase_map in
let to_push_candidates = FileMap.remove to_push_candidates file in
let error_count_in_ide =
let error_count = error_count_in_phase_map phase_map in
let error_count_before =
FileMap.find_opt errors_in_ide file
>>| error_count_in_phase_map
|> Option.value ~default:0
in
error_count_in_ide + error_count - error_count_before
in
(to_push, to_push_candidates, error_count_in_ide))
in
(* Then push errors in files which already have errors *)
let (to_push, to_push_candidates, error_count_in_ide) =
FileMap.fold
to_push_candidates
~init:(to_push, FileMap.empty, error_count_in_ide)
~f:(fun file phase_map (to_push, to_push_candidates, error_count_in_ide)
->
match FileMap.find_opt errors_in_ide file with
| None ->
(* Let's consider it again later. *)
let to_push_candidates =
FileMap.add to_push_candidates ~key:file ~data:phase_map
in
(to_push, to_push_candidates, error_count_in_ide)
| Some errors_in_ide ->
let error_count = error_count_in_phase_map phase_map in
let error_count_before = error_count_in_phase_map errors_in_ide in
if
error_count_in_ide + error_count - error_count_before
<= !error_limit
then
let error_count_in_ide =
error_count_in_ide + error_count - error_count_before
in
let to_push = FileMap.add to_push ~key:file ~data:phase_map in
(to_push, to_push_candidates, error_count_in_ide)
else
(* Erase those errors in the IDE, because for each file we want either all errors or none,
and we can't have all errors here because we'd need to go beyond the limit. *)
let to_push =
FileMap.add to_push ~key:file ~data:PhaseMap.empty
in
let error_count_in_ide =
error_count_in_ide - error_count_before
in
let to_push_candidates =
FileMap.add to_push_candidates ~key:file ~data:phase_map
in
(to_push, to_push_candidates, error_count_in_ide))
in
(* Keep pushing until we reach the limit. *)
let (to_push, errors_beyond_limit, _error_count_in_ide) =
FileMap.fold
to_push_candidates
~init:(to_push, FileMap.empty, error_count_in_ide)
~f:(fun file phase_map (to_push, errors_beyond_limit, error_count_in_ide)
->
(* [to_push_candidates] now only contains files which are not in
[errors_in_ide] or have been deduced from it. *)
let error_count = error_count_in_phase_map phase_map in
if error_count_in_ide + error_count <= !error_limit then
let to_push = FileMap.add to_push ~key:file ~data:phase_map in
let error_count_in_ide = error_count_in_ide + error_count in
(to_push, errors_beyond_limit, error_count_in_ide)
else
let errors_beyond_limit =
FileMap.add errors_beyond_limit ~key:file ~data:phase_map
in
(to_push, errors_beyond_limit, error_count_in_ide))
in
(to_push, errors_beyond_limit)
(* Convert all paths to absolute paths and union all phases for each file. *)
let to_diagnostic_errors : ErrorMap.t -> ServerCommandTypes.diagnostic_errors
=
fun errors ->
FileMap.fold errors ~init:SMap.empty ~f:(fun path phase_map errors_acc ->
let path = Relative_path.to_absolute path in
let file_errors =
PhaseMap.fold phase_map ~init:[] ~f:(fun _phase -> ( @ ))
|> List.map ~f:User_error.to_absolute
in
SMap.add ~key:path ~data:file_errors errors_acc)
let get_errors_to_push :
t ->
rechecked:Relative_path.Set.t ->
new_errors:Errors.t ->
priority_files:Relative_path.Set.t option ->
t * ServerCommandTypes.diagnostic_errors =
fun { errors_in_ide; to_push; errors_beyond_limit }
~rechecked
~new_errors
~priority_files ->
let phase = PhaseSingleton in
let new_errors : error list FileMap.t =
Errors.as_map (Errors.drop_fixmed_errors_in_files new_errors)
in
(* Merge to_push and errors_beyond_limit to obtain the total
* set of errors to be pushed. *)
let to_push = FileMap.union errors_beyond_limit to_push in
(* Update that set with the new errors. *)
let to_push =
merge_errors_to_push to_push ~rechecked ~errors_in_ide ~new_errors ~phase
in
(* Clear any old errors that are no longer there. *)
let to_push = erase_errors to_push ~errors_in_ide ~rechecked ~phase in
(* Separate errors we'll push now vs. errors we won't push yet
* because they are beyond the error limit *)
let (to_push, errors_beyond_limit) =
truncate to_push ~errors_in_ide ~priority_files
in
let to_push_absolute = to_diagnostic_errors to_push in
({ errors_in_ide; to_push; errors_beyond_limit }, to_push_absolute)
let compute_total_errors : ErrorMap.t -> ErrorMap.t -> ErrorMap.t =
fun errors_in_ide to_push ->
FileMap.fold
to_push
~init:errors_in_ide
~f:(fun file phase_map errors_in_ide ->
let phase_map =
PhaseMap.fold
phase_map
~init:PhaseMap.empty
~f:(fun phase errors phase_map ->
if List.is_empty errors then
phase_map
else
PhaseMap.add phase_map ~key:phase ~data:errors)
in
if PhaseMap.is_empty phase_map then
FileMap.remove errors_in_ide file
else
FileMap.add errors_in_ide ~key:file ~data:phase_map)
let commit_pushed_errors : t -> t =
fun { errors_in_ide; to_push; errors_beyond_limit } ->
let all_errors = compute_total_errors errors_in_ide to_push in
{ errors_in_ide = all_errors; to_push = FileMap.empty; errors_beyond_limit }
let reset_for_new_client : t -> t =
fun { errors_in_ide; to_push; errors_beyond_limit } ->
let all_errors = compute_total_errors errors_in_ide to_push in
{ errors_in_ide = FileMap.empty; to_push = all_errors; errors_beyond_limit }
let get_files_with_diagnostics : t -> Relative_path.t list =
(fun { errors_in_ide; _ } -> ErrorMap.files errors_in_ide)
module TestExporter = struct
let make ~errors_in_ide ~to_push ~errors_beyond_limit =
{ errors_in_ide; to_push; errors_beyond_limit }
let with_error_limit limit f =
let previous_error_limit = !error_limit in
error_limit := limit;
let result = f () in
error_limit := previous_error_limit;
result
end
end
type t = {
error_tracker: ErrorTracker.t;
tracked_ide_id: int option;
}
[@@deriving show]
type push_result =
| DidPush of { timestamp: seconds_since_epoch }
| DidNotPush
let push_result_as_option = function
| DidPush { timestamp } -> Some timestamp
| DidNotPush -> None
let init = { error_tracker = ErrorTracker.init; tracked_ide_id = None }
let push_to_client :
ServerCommandTypes.diagnostic_errors -> ClientProvider.client -> push_result
=
fun errors client ->
if ClientProvider.client_has_message client then
DidNotPush
else if SMap.is_empty errors then
DidNotPush
else
let message =
ServerCommandTypes.DIAGNOSTIC { errors; is_truncated = None }
in
try
ClientProvider.send_push_message_to_client client message;
DidPush { timestamp = Unix.gettimeofday () }
with
| ClientProvider.Client_went_away -> DidNotPush
(** Reset the error tracker if the new client ID is different from the tracked one. *)
let possibly_reset_tracker { error_tracker; tracked_ide_id } new_ide_id =
let log_went_away old_id =
Hh_logger.info
~category:"clients"
"[Diagnostic_pusher] Tracked client with ID %d went away"
old_id
in
let log_new_client new_id =
Hh_logger.info
~category:"clients"
"[Diagnostic_pusher] New client with ID %d"
new_id
in
let client_went_away =
match (tracked_ide_id, new_ide_id) with
| (None, None) -> false
| (None, Some client_id) ->
log_new_client client_id;
false
| (Some tracked_ide_id, None) ->
log_went_away tracked_ide_id;
true
| (Some tracked_ide_id, Some client_id) ->
let went_away = not (Int.equal tracked_ide_id client_id) in
if went_away then (
log_went_away tracked_ide_id;
log_new_client client_id
);
went_away
in
let error_tracker =
if client_went_away then
ErrorTracker.reset_for_new_client error_tracker
else
error_tracker
in
let tracked_ide_id = new_ide_id in
{ error_tracker; tracked_ide_id }
let break_down_ide_info_option :
Ide_info_store.t option ->
int option * ClientProvider.client option * Relative_path.Set.t option =
function
| None -> (None, None, None)
| Some { Ide_info_store.id; client; open_files } ->
(Some id, Some client, Some open_files)
(** Get client from the client provider and possibly reset the error tracker
if we've lost the previous client. *)
let get_client :
t -> t * (ClientProvider.client option * Relative_path.Set.t option) =
fun pusher ->
let (current_ide_id, current_client, current_ide_open_files) =
Ide_info_store.get () |> break_down_ide_info_option
in
let pusher = possibly_reset_tracker pusher current_ide_id in
(pusher, (current_client, current_ide_open_files))
let push_new_errors :
t ->
rechecked:Relative_path.Set.t ->
Errors.t ->
t * seconds_since_epoch option =
fun pusher ~rechecked new_errors ->
let ({ error_tracker; tracked_ide_id }, (client, priority_files)) =
get_client pusher
in
let (error_tracker, to_push) =
ErrorTracker.get_errors_to_push
error_tracker
~rechecked
~new_errors
~priority_files
in
let push_result =
match client with
| None -> DidNotPush
| Some client -> push_to_client to_push client
in
let error_tracker =
match push_result with
| DidPush { timestamp = _ } ->
ErrorTracker.commit_pushed_errors error_tracker
| DidNotPush -> error_tracker
in
({ error_tracker; tracked_ide_id }, push_result_as_option push_result)
let push_whats_left : t -> t * seconds_since_epoch option =
fun pusher ->
push_new_errors ~rechecked:Relative_path.Set.empty pusher Errors.empty
let get_files_with_diagnostics : t -> Relative_path.t list =
fun { error_tracker; _ } ->
ErrorTracker.get_files_with_diagnostics error_tracker
module TestExporter = struct
module FileMap = FileMap
module ErrorTracker = ErrorTracker
end |
OCaml Interface | hhvm/hphp/hack/src/server/diagnostic_pusher.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.
*
*)
(** Module to push diagnostics to the LSP client. *)
(** This needs to persist for the whole lifetime of the server to properly
keep track of diagnostics. *)
type t [@@deriving show]
type seconds_since_epoch = float
val init : t
(** Push a new batch of errors to the LSP client. [rechecked] is the full
set of files that have been rechecked to produce this new batch of errors.
Return the updated pusher and the timestamp of the push if anything was pushed,
or None if not, e.g. there was nothing to push or no persistent client or the push failed. *)
val push_new_errors :
t ->
rechecked:Relative_path.Set.t ->
Errors.t ->
t * seconds_since_epoch option
(** If any error remains to be pushed, for example because the previous push failed or
because there was no IDE connected at the time, push them.
Return the updated pusher and the timestamp of the push if anything was pushed,
or None if not, e.g. there was nothing to push or no persistent client or the push failed. *)
val push_whats_left : t -> t * seconds_since_epoch option
val get_files_with_diagnostics : t -> Relative_path.t list
(** This is a dummy placeholder *)
type phase = PhaseSingleton [@@deriving eq]
module PhaseMap : sig
include Reordered_argument_collections.Map_S with type key = phase
val pp : (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a t -> unit
val show : (Format.formatter -> 'a -> unit) -> 'a t -> string
end
(** Module to export internal functions for unit testing. Do not use in production code. *)
module TestExporter : sig
module FileMap : module type of Relative_path.Map
module ErrorTracker : sig
type t [@@deriving eq, show]
val init : t
val get_errors_to_push :
t ->
rechecked:Relative_path.Set.t ->
new_errors:Errors.t ->
priority_files:Relative_path.Set.t option ->
t * Errors.finalized_error list SMap.t
val commit_pushed_errors : t -> t
module TestExporter : sig
val make :
errors_in_ide:Errors.error list PhaseMap.t FileMap.t ->
to_push:Errors.error list PhaseMap.t FileMap.t ->
errors_beyond_limit:Errors.error list PhaseMap.t FileMap.t ->
t
val with_error_limit : int -> (unit -> 'result) -> 'result
end
end
end |
OCaml | hhvm/hphp/hack/src/server/diffHotDecls.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.
*
*)
(*
* 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 Decl_export
let decls_type_match (decls1, decls2) suffix =
Filename.check_suffix decls1 suffix && Filename.check_suffix decls2 suffix
let legacy decls1 decls2 : bool = decls_type_match (decls1, decls2) ".decls"
let shallow decls1 decls2 : bool =
decls_type_match (decls1, decls2) ".shallowdecls"
(*
Print the diff of decls1_str and decls2_str, and
return whether they differ.
*)
let diff_decls decls1_str decls2_str =
if String.equal decls1_str decls2_str then (
Hh_logger.log "The hot decls are identical!";
false
) else (
Hh_logger.log "The hot decls are different:";
Tempfile.with_real_tempdir (fun dir ->
let temp_dir = Path.to_string dir in
let control =
Caml.Filename.temp_file ~temp_dir "control_decls" ".txt"
in
let test = Caml.Filename.temp_file ~temp_dir "test_decls" ".txt" in
Disk.write_file ~file:control ~contents:decls1_str;
Disk.write_file ~file:test ~contents:decls2_str;
Ppxlib_print_diff.print
~diff_command:"diff --label control_decls --label test_decls"
~file1:control
~file2:test
());
true
)
let diff_legacy_decls
(decls1 : saved_legacy_decls) (decls2 : saved_legacy_decls) =
Hh_logger.log "Diffing legacy hot decls...";
let decls1_str = show_saved_legacy_decls decls1 ^ "\n" in
let decls2_str = show_saved_legacy_decls decls2 ^ "\n" in
diff_decls decls1_str decls2_str
let diff_shallow_decls
(decls1 : saved_shallow_decls) (decls2 : saved_shallow_decls) =
Hh_logger.log "Diffing shallow hot decls...";
let decls1_str = show_saved_shallow_decls decls1 ^ "\n" in
let decls2_str = show_saved_shallow_decls decls2 ^ "\n" in
diff_decls decls1_str decls2_str
let load_hot_decls decls_path =
Hh_logger.log "Loading hot decls from %s..." decls_path;
let t = Unix.gettimeofday () in
(* trusting the user to give us a file of the correct format! *)
let decls = SaveStateService.load_contents_unsafe decls_path in
let _ = Hh_logger.log_duration "Loaded hot decls" t in
decls
let diff control_path test_path =
let control_decls = load_hot_decls control_path in
let test_decls = load_hot_decls test_path in
if shallow control_path test_path then
diff_shallow_decls control_decls test_decls
else if legacy control_path test_path then
diff_legacy_decls control_decls test_decls
else
failwith "invalid decl comparison" |
OCaml | hhvm/hphp/hack/src/server/diffNamingTable.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 get_default_provider_context () =
let () =
Relative_path.set_path_prefix Relative_path.Root (Path.make_unsafe "root")
in
let () =
Relative_path.set_path_prefix Relative_path.Hhi (Path.make_unsafe "hhi")
in
Provider_backend.set_local_memory_backend_with_defaults_for_test ();
let hh_parser_options = GlobalOptions.default in
let provider_backend = Provider_backend.get () in
Provider_context.empty_for_tool
~popt:hh_parser_options
~tcopt:hh_parser_options
~backend:provider_backend
~deps_mode:(Typing_deps_mode.InMemoryMode None)
let get_naming_table_and_errors provider_context path =
let sqlite_path = Some path in
let errors_path = Str.replace_first (Str.regexp "_naming.sql") ".err" path in
SaveStateService.load_saved_state_exn
~naming_table_fallback_path:sqlite_path
~errors_path
provider_context
type diff = {
added_files: Relative_path.t list;
removed_files: Relative_path.t list;
changed_files: (Relative_path.t * FileInfo.diff) list;
removed_errors: Relative_path.t list;
added_errors: Relative_path.t list;
}
let empty_diff =
{
added_files = [];
removed_files = [];
changed_files = [];
removed_errors = [];
added_errors = [];
}
let is_nonempty
({ added_files; removed_files; changed_files; removed_errors; added_errors } :
diff) =
match
(added_files, removed_files, changed_files, removed_errors, added_errors)
with
| ([], [], [], [], []) -> false
| _ -> true
let calculate_diff naming_table1 naming_table2 errors1 errors2 =
let diff =
Naming_table.fold
naming_table1
~init:empty_diff
~f:(fun path fileinfo1 acc ->
match Naming_table.get_file_info naming_table2 path with
| None -> { acc with removed_files = path :: acc.removed_files }
| Some fileinfo2 -> begin
match FileInfo.diff fileinfo1 fileinfo2 with
| None -> acc
| Some file_diff ->
{ acc with changed_files = (path, file_diff) :: acc.changed_files }
end)
in
let diff =
Naming_table.fold naming_table2 ~init:diff ~f:(fun path _ acc ->
match Naming_table.get_file_info naming_table1 path with
| None -> { acc with added_files = path :: acc.added_files }
| _ -> acc)
in
let removed_errors =
Relative_path.Set.elements (Relative_path.Set.diff errors1 errors2)
in
let added_errors =
Relative_path.Set.elements (Relative_path.Set.diff errors2 errors1)
in
{ diff with removed_errors; added_errors }
let file_info_diff_to_string path d =
let open FileInfo in
let set_to_string sset = String.concat (SSet.elements sset) ~sep:", " in
let helper acc (description, s) =
if SSet.is_empty s then
acc
else
description :: set_to_string s :: acc
in
let t =
List.fold
~f:helper
~init:[]
[
("Removed consts:", d.removed_consts);
("Added consts:", d.added_consts);
("Removed types:", d.removed_types);
("Added types:", d.added_types);
("Removed classes:", d.removed_classes);
("Added classes:", d.added_classes);
("Removed functions:", d.removed_funs);
("Added functions", d.added_funs);
]
in
String.concat ~sep:"\n" (Relative_path.S.to_string path :: t)
let print_diff print_count diff =
Hh_logger.log "Diffing the naming tables...";
let no_difference =
List.is_empty diff.added_files
&& List.is_empty diff.removed_files
&& List.is_empty diff.changed_files
in
if no_difference then
Hh_logger.log "The naming tables are identical!"
else if print_count then (
let print_category description change =
if not (List.is_empty change) then
Hh_logger.log "%s: %s" description (string_of_int @@ List.length change)
in
print_category "Added files" diff.added_files;
print_category "Removed files" diff.removed_files;
print_category "Changed files" diff.changed_files;
print_category "Added errors" diff.added_errors;
print_category "Removed errors" diff.removed_errors
) else
let concat_paths paths =
let paths =
List.map ~f:(fun path -> Relative_path.S.to_string path) paths
in
String.concat paths ~sep:"\n"
in
let print_category description change =
if not (List.is_empty change) then
Hh_logger.log "%s:\n%s" description (concat_paths change)
in
print_category "Added files" diff.added_files;
print_category "Removed files" diff.removed_files;
if not (List.is_empty diff.changed_files) then (
Hh_logger.log "Changed files";
List.iter diff.changed_files ~f:(fun (path, d) ->
Hh_logger.log "%s" (file_info_diff_to_string path d))
);
print_category "Added errors" diff.added_errors;
print_category "Removed errors" diff.removed_errors
(*
Prints the diff of test and control (naming table, error) pairs, and
returns whether test and control differ.
*)
let diff control_path test_path =
let provider_context = get_default_provider_context () in
let (control_naming_table, control_errors) =
get_naming_table_and_errors provider_context control_path
in
let (test_naming_table, test_errors) =
get_naming_table_and_errors provider_context test_path
in
let diff =
calculate_diff
control_naming_table
test_naming_table
control_errors
test_errors
in
print_diff false diff;
is_nonempty diff |
OCaml | hhvm/hphp/hack/src/server/docblockService.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.
*
*)
type docblock_element =
| HackSnippet of string
| XhpSnippet of string
| Markdown of string
type result = docblock_element list
(* Represents a symbol location determined by the docblock service *)
type dbs_symbol_location = {
dbs_filename: string;
dbs_line: int;
dbs_column: int;
dbs_base_class: string option;
}
type dbs_symbol_location_result = dbs_symbol_location option |
hhvm/hphp/hack/src/server/dune | (library
(name server_pos)
(wrapped false)
(modules serverPos)
(libraries naming_provider tast_env)
(preprocess
(pps lwt_ppx ppx_deriving.std)))
(library
(name server_symbol_info_service_utils)
(wrapped false)
(modules symbolInfoServiceUtils)
(libraries
ast_provider
naming
server_command_types
tast_provider
server_services
utils_core)
(preprocess
(pps lwt_ppx ppx_deriving.std)))
(library
(name server_codemod_type_printer)
(wrapped false)
(modules codemodTypePrinter)
(libraries typing_defs tast_env utils_core)
(preprocess
(pps lwt_ppx ppx_deriving.std)))
(library
(name server_revision_tracker)
(wrapped false)
(modules serverRevisionTracker)
(libraries hg server_config watchman_utils)
(preprocess
(pps lwt_ppx ppx_deriving.std)))
(library
(name server_env_build)
(wrapped false)
(modules serverEnvBuild)
(libraries server_env server_revision_tracker dfind)
(preprocess
(pps lwt_ppx ppx_deriving.std)))
(library
(name server_prechecked_files)
(wrapped false)
(modules serverPrecheckedFiles)
(libraries provider_utils server_env server_revision_tracker)
(preprocess
(pps lwt_ppx ppx_deriving.std)))
(library
(name server_find_refs)
(wrapped false)
(modules serverFindRefs serverDepsInBatch)
(libraries
provider_context
server_command_types
server_env
server_prechecked_files
server_services
utils_core)
(preprocess
(pps lwt_ppx ppx_deriving.std)))
(library
(name server_call_hierarchy)
(wrapped false)
(modules serverPrepareCallHierarchy serverCallHierarchyIncomingCalls serverCallHierarchyOutgoingCalls serverCallHierarchyUtils)
(libraries provider_context server_find_refs server_services lsp server_command_types)
(preprocess
(pps lwt_ppx ppx_deriving.std)))
(library
(name server_go_to)
(wrapped false)
(modules serverGoToDefinition serverGoToImpl)
(libraries provider_context server_find_refs server_services)
(preprocess
(pps lwt_ppx ppx_deriving.std)))
(library
(name server_highlight_refs)
(wrapped false)
(modules serverHighlightRefs)
(libraries provider_context server_services)
(preprocess
(pps lwt_ppx ppx_deriving.std)))
(library
(name server_type_hierarchy)
(wrapped false)
(modules serverTypeHierarchy)
(libraries
provider_context
server_services
server_infer_type)
(preprocess
(pps
lwt_ppx
ppx_deriving.std
ppx_deriving.show
ppx_deriving.enum)))
(library
(name server_file_outline)
(wrapped false)
(modules fileOutline)
(libraries search utils_core)
(preprocess
(pps lwt_ppx ppx_deriving.std)))
(library
(name monitor_rpc)
(wrapped false)
(modules monitorRpc)
(libraries
connection_tracker
hh_json
logging
sys_utils
)
)
(library
(name server_args)
(wrapped false)
(modules serverArgs)
(libraries
ai_options
cli_args
string
sys_utils
utils_core
utils_exit
utils_www_root
version))
(library
(name server_progress)
(wrapped false)
(modules serverProgress)
(libraries
errors
server_command_types
server_files
watchman
)
(preprocess
(pps lwt_ppx ppx_deriving.std)))
(library
(name server_progress_lwt)
(wrapped false)
(modules serverProgressLwt)
(libraries
server_progress
)
(preprocess
(pps lwt_ppx ppx_deriving.std)))
(library
(name server_notifier)
(wrapped false)
(modules serverNotifier)
(libraries
server_command_types
server_files
server_revision_tracker
dfind
watchman)
(preprocess
(pps lwt_ppx ppx_deriving.std)))
(library
(name server_config)
(wrapped false)
(modules serverConfig serverLocalConfig)
(libraries
custom_error_config
server_args
errors
experiments_config_file
heap_shared_mem
typechecker_options
glean_options
ai_options
build_options
symbol_write_options
parser_options
procs_bucket
server_local_config_knobs_stubs
utils_config_file
)
(preprocess
(pps lwt_ppx ppx_deriving.std)))
(library
(name server_env)
(wrapped false)
(modules serverEnv )
(libraries
ci_util
diagnostic_pusher
server_client_provider
server_config
server_notifier)
(preprocess
(pps lwt_ppx ppx_deriving.std)))
(library
(name server_files)
(wrapped false)
(modules serverFiles)
(libraries core_kernel hhi global_config sys_utils utils_core)
(preprocess
(pps lwt_ppx ppx_deriving.std)))
(library
(name server_utils)
(wrapped false)
(modules serverUtils)
(libraries
core_kernel
find
decl
decl_class
decl_provider
hhi
procs_bucket
procs_procs
relative_path
server_files
sys_utils
tast_env
utils_core
watchman)
(preprocess
(pps lwt_ppx ppx_deriving.std)))
(library
(name server_command_types)
(wrapped false)
(modules
autocompleteTypes
docblockService
findRefsWireFormat
hoverService
inferAtPosService
inferErrorAtPosService
saveStateServiceTypes
serverCommandTypes
serverCommandTypesUtils
serverFormatTypes
serverGlobalInferenceTypes
serverHighlightRefsTypes
serverTypeHierarchyTypes
serverLintTypes
serverRageTypes
serverRenameTypes
tastHolesService)
(libraries
base64
connection_tracker
full_fidelity
hh_json
ide_rpc_api_types
lsp
lwt
marshal_tools
pos
search_utils
symbol
typing_defs
typing_deps
utils_lint
version)
(preprocess
(pps lwt_ppx ppx_deriving.std ppx_deriving.show ppx_deriving.enum)))
(library
(name server_client_provider)
(wrapped false)
(modules
clientProvider
clientProvider_sig
ide_info_store
serverClientProvider
serverIdleGc
testClientProvider)
(libraries
libancillary
monitor_rpc
relative_path
server_command_types
server_progress
server_utils
utils_core)
(preprocess
(pps lwt_ppx ppx_deriving.std)))
(library
(name server_autocomplete_services)
(wrapped false)
(modules
autocompleteService
serverAutoComplete)
(libraries
provider_utils
search
server_command_types
server_pos
tast_provider)
(preprocess
(pps lwt_ppx ppx_deriving.std)))
(library
(name server_services)
(wrapped false)
(modules
cstSearchService
findRefsService
identifySymbolService
methodJumps
saveStateService
serverDepsOutBatch
serverDepsUtil
serverFindTypeVar
serverFindLocals
serverFunDepsBatch
serverGlobalState
serverIdentifyFunction
serverRxApiShared
serverSymbolDefinition
symbolFunCallService
symbolTypeService)
(libraries
ast
cgroupprofiler
decl
decl_compare
decl_export
fileutils
heap_shared_mem
hint_print
parser
provider_context
provider_utils
server_command_types
server_env
server_file_outline
server_pos
sys_utils
tast_check
tast_provider
tast_type_collector
typechecker_options
typing
typing_check
typing_deps
utils_core)
(preprocess
(pps lwt_ppx ppx_deriving.std)))
(library
(name server_search)
(wrapped false)
(modules serverSearch)
(preprocess
(pps lwt_ppx ppx_deriving.std))
(libraries
server_autocomplete_services
search
search_utils
utils_core
hh_json
pos))
(library
(name server_infer_type)
(wrapped false)
(modules serverInferType serverInferTypeError serverCollectTastHoles)
(libraries
annotated_ast
ast
hh_json
pos
provider_context
server_command_types
tast_env
tast_provider
typing
typing_defs
utils_core)
(preprocess
(pps lwt_ppx ppx_deriving.std)))
(library
(name server_docblock_at)
(wrapped false)
(modules serverDocblockAt)
(libraries
ast
collections
decl_provider
naming_provider
parser
pos
provider_context
relative_path
search
search_utils
server_command_types
server_services
symbol
typing_defs
utils_core)
(preprocess
(pps lwt_ppx ppx_deriving.std)))
(library
(name server_hover)
(wrapped false)
(modules serverHover)
(libraries
decl_provider
naming_special_names
pos
provider_context
server_command_types
server_docblock_at
server_infer_type
server_services
symbol
tast_provider
typing
utils_core
)
(preprocess
(pps lwt_ppx ppx_deriving.std)))
(rule
(target serverInvalidateUnits.fb.ml)
(action
(copy# facebook/serverInvalidateUnits.ml serverInvalidateUnits.fb.ml)))
(library
(name server)
(wrapped false)
(modules
fullFidelityParseService
searchServiceRunner
serverBusyStatus
serverCheckUtils
serverCheckpoint
serverConcatenateAll
serverError
serverExtractStandalone
serverFileDependents
serverFileSync
serverFormat
serverIdle
serverInferTypeBatch
serverTastHolesBatch
serverInvalidateUnits
serverIsSubtype
serverLint
serverMethodJumps
serverMethodJumpsBatch
serverPopulateRemoteDecls
serverRage
serverRename
serverRewriteLambdaParameters
serverSignatureHelp
serverStamp
serverStatusSingle
serverTypeCheck
serverTypeDefinition
serverWorker
symbolInfoService)
(libraries
base64
buffered_line_reader
cgroupprofiler
decl_redecl_service
direct_decl_service
dfind
fileutils
format_helpers
hg
hhi
hint_print
ide_rpc_api_types
remote_old_decls_ffi
linting
linting_main
lints_core
lsp
security_stubs
shallow_classes_provider
direct_decl_parser
direct_decl_utils
server_codemod_type_printer
server_code_actions_services
server_docblock_at
server_env
server_find_refs
server_hover
server_infer_type
server_prechecked_files
server_revision_tracker
server_services
server_symbol_info_service_utils
sys_utils
tast_provider
typing
typing_check_job
utils_core
version
watchman_utils
(select
serverInvalidateUnits.ml
from
(facebook signed_source -> serverInvalidateUnits.fb.ml)
(-> serverInvalidateUnits.stubs.ml)))
(preprocess
(pps lwt_ppx ppx_deriving.std)))
(rule
(target serverInitMessages.fb.ml)
(action
(copy# facebook/serverInitMessages.ml serverInitMessages.fb.ml)))
(library
(name custom_error_config)
(wrapped false)
(modules customErrorConfig)
(libraries
custom_error_types
relative_path
sys_utils
utils_exit
)
)
(library
(name hh_server_monitor)
(wrapped false)
(modules
client_command_handler
serverCommand
serverCommandLwt
serverEagerInit
serverInit
serverInitCommon
serverInitMessages
serverInitTypes
serverLazyInit
serverMain
serverRpc)
(libraries
ast
ast_and_decl_service
build
ci_util
cgroupprofiler
custom_error_config
direct_decl_service
folly_stubs
load_script
lwt
memory_stats
package_config
parent
provider_backend
security_stubs
server
server_env_build
server_call_hierarchy
server_go_to
server_highlight_refs
server_search
startup_initializer_stubs
state_loader
watchman_client
write_symbol_info
(select
serverInitMessages.ml
from
(facebook signed_source -> serverInitMessages.fb.ml)
(-> serverInitMessages.stubs.ml)))
(preprocess
(pps lwt_ppx ppx_deriving.std)))
(library
(name diagnostic_pusher)
(wrapped false)
(modules diagnostic_pusher)
(libraries
errors
relative_path
utils_core
server_client_provider
server_command_types)
(preprocess
(pps lwt_ppx ppx_deriving.std))) |
|
OCaml | hhvm/hphp/hack/src/server/fileOutline.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
open Reordered_argument_collections
open SymbolDefinition
open Aast
module Parser = Full_fidelity_ast
type outline = string SymbolDefinition.t list
let modifiers_to_list ~is_final ~visibility ~is_abstract ~is_static =
let modifiers =
match visibility with
| Public -> [SymbolDefinition.Public]
| Private -> [SymbolDefinition.Private]
| Protected -> [SymbolDefinition.Protected]
| Internal -> [SymbolDefinition.Internal]
in
let modifiers =
if is_final then
Final :: modifiers
else
modifiers
in
let modifiers =
if is_abstract then
Abstract :: modifiers
else
modifiers
in
let modifiers =
if is_static then
Static :: modifiers
else
modifiers
in
List.rev modifiers
let get_full_name class_name name =
match class_name with
| None -> name
| Some class_name -> class_name ^ "::" ^ name
let summarize_property class_name var =
let modifiers =
modifiers_to_list
~is_final:var.cv_final
~visibility:var.cv_visibility
~is_abstract:var.cv_abstract
~is_static:var.cv_is_static
in
let (pos, name) = var.cv_id in
let kind = Property in
let id = get_symbol_id kind (Some class_name) name in
let full_name = get_full_name (Some class_name) name in
{
kind;
name;
full_name;
class_name = Some class_name;
id;
pos;
span = var.cv_span;
modifiers;
children = None;
params = None;
docblock = None;
}
let maybe_summarize_property class_name ~skip var =
let (_, name) = var.cv_id in
if SSet.mem skip name then
[]
else
[summarize_property class_name var]
let summarize_class_const class_name cc =
let (pos, name) = cc.cc_id in
let (span, modifiers) =
match cc.cc_kind with
| CCConcrete (_, p, _) -> (Pos.btw pos p, [])
| CCAbstract (Some (_, p_default, _)) -> (Pos.btw pos p_default, [Abstract])
| CCAbstract None -> (pos, [Abstract])
in
let kind = ClassConst in
let id = get_symbol_id kind (Some class_name) name in
let full_name = get_full_name (Some class_name) name in
{
kind;
name;
full_name;
class_name = Some class_name;
id;
pos;
span;
modifiers;
children = None;
params = None;
docblock = None;
}
let modifier_of_fun_kind acc = function
| Ast_defs.FAsync
| Ast_defs.FAsyncGenerator ->
Async :: acc
| _ -> acc
let modifier_of_param_kind acc = function
| Ast_defs.Pinout _ -> Inout :: acc
| Ast_defs.Pnormal -> acc
let summarize_typeconst class_name t =
let (pos, name) = t.c_tconst_name in
let kind = Typeconst in
let id = get_symbol_id kind (Some class_name) name in
let modifiers =
match t.c_tconst_kind with
| TCAbstract _ -> [Abstract]
| _ -> []
in
let full_name = get_full_name (Some class_name) name in
{
kind;
name;
full_name;
class_name = Some class_name;
id;
pos;
span = t.c_tconst_span;
modifiers;
children = None;
params = None;
docblock = None;
}
let summarize_param param =
let pos = param.param_pos in
let name = param.param_name in
let param_start =
Option.value_map
(hint_of_type_hint param.param_type_hint)
~f:fst
~default:pos
in
let param_end =
Option.value_map param.param_expr ~f:(fun (_, p, _) -> p) ~default:pos
in
let modifiers = modifier_of_param_kind [] param.param_callconv in
let modifiers =
match param.param_visibility with
| Some Public -> SymbolDefinition.Public :: modifiers
| Some Private -> SymbolDefinition.Private :: modifiers
| Some Protected -> SymbolDefinition.Protected :: modifiers
| _ -> modifiers
in
let kind = Param in
let id = get_symbol_id kind None name in
let full_name = get_full_name None name in
{
kind;
name;
full_name;
class_name = None;
id;
pos;
span = Pos.btw param_start param_end;
children = None;
modifiers;
params = None;
docblock = None;
}
let summarize_method class_name m =
let modifiers = modifier_of_fun_kind [] m.m_fun_kind in
let modifiers =
modifiers_to_list
~is_final:m.m_final
~visibility:m.m_visibility
~is_abstract:m.m_abstract
~is_static:m.m_static
@ modifiers
in
let params = Some (List.map m.m_params ~f:summarize_param) in
let name = snd m.m_name in
let kind = Method in
let id = get_symbol_id kind (Some class_name) name in
let full_name = get_full_name (Some class_name) name in
{
kind;
name;
full_name;
class_name = Some class_name;
id;
pos = fst m.m_name;
span = m.m_span;
modifiers;
children = None;
params;
docblock = None;
}
(* Parser synthesizes AST nodes for implicit properties (defined in constructor
* parameter lists. We don't want them to show up in outline view *)
let params_implicit_fields params =
List.filter_map params ~f:(function
| { param_visibility = Some _vis; param_name; _ } ->
Some (String_utils.lstrip param_name "$")
| _ -> None)
let class_implicit_fields class_ =
List.concat_map class_.c_methods ~f:(fun m ->
let (_, name) = m.m_name in
if String.equal name "__construct" then
params_implicit_fields m.m_params
else
[])
let summarize_class class_ ~no_children =
let class_name = Utils.strip_ns (snd class_.c_name) in
let class_name_pos = fst class_.c_name in
let c_span = class_.c_span in
let modifiers =
if class_.c_final then
[Final]
else
[]
in
let modifiers =
if Ast_defs.is_classish_abstract class_.c_kind then
Abstract :: modifiers
else
modifiers
in
let children =
if no_children then
None
else
let implicit_props =
List.fold (class_implicit_fields class_) ~f:SSet.add ~init:SSet.empty
in
let acc =
(* Summarized class properties *)
List.fold_left
~init:[]
~f:(fun acc cv ->
List.fold_right
~init:acc
~f:List.cons
(maybe_summarize_property class_name ~skip:implicit_props cv))
class_.c_vars
in
let acc =
(* Summarized xhp_attrs *)
List.fold_left
~init:acc
~f:(fun acc (_, var, _, _) ->
List.fold_right
~init:acc
~f:List.cons
(maybe_summarize_property class_name ~skip:implicit_props var))
class_.c_xhp_attrs
in
let acc =
(* Summarized consts *)
List.fold_left
~init:acc
~f:(fun acc c -> summarize_class_const class_name c :: acc)
class_.c_consts
in
let acc =
(* Summarized type consts *)
List.fold_left
~init:acc
~f:(fun acc tc -> summarize_typeconst class_name tc :: acc)
class_.c_typeconsts
in
let acc =
(* Summarized methods *)
List.fold_left
~init:acc
~f:(fun acc m -> summarize_method class_name m :: acc)
class_.c_methods
in
let sort_by_line summaries =
let cmp x y = Int.compare (Pos.line x.pos) (Pos.line y.pos) in
List.sort ~compare:cmp summaries
in
Some (sort_by_line acc)
in
let kind =
match class_.c_kind with
| Ast_defs.Cinterface -> Interface
| Ast_defs.Ctrait -> Trait
| Ast_defs.Cenum_class _
| Ast_defs.Cenum ->
Enum
| Ast_defs.(Cclass _) -> Class
in
let name = class_name in
let id = get_symbol_id kind None name in
let full_name = get_full_name None name in
{
kind;
name;
full_name;
class_name = Some class_name;
id;
pos = class_name_pos;
span = c_span;
modifiers;
children;
params = None;
docblock = None;
}
let summarize_typedef tdef =
let kind = SymbolDefinition.Typedef in
let name = Utils.strip_ns (snd tdef.t_name) in
let id = get_symbol_id kind None name in
let full_name = get_full_name None name in
let pos = fst tdef.t_name in
let kind_pos = fst tdef.t_kind in
let span = Pos.btw pos kind_pos in
{
kind;
name;
full_name;
class_name = None;
id;
pos;
span;
modifiers = [];
children = None;
params = None;
docblock = None;
}
let summarize_fun fd =
let f = fd.fd_fun in
let modifiers = modifier_of_fun_kind [] f.f_fun_kind in
let params = Some (List.map f.f_params ~f:summarize_param) in
let kind = SymbolDefinition.Function in
let name = Utils.strip_ns (snd fd.fd_name) in
let id = get_symbol_id kind None name in
let full_name = get_full_name None name in
{
kind;
name;
full_name;
class_name = None;
id;
pos = fst fd.fd_name;
span = f.f_span;
modifiers;
children = None;
params;
docblock = None;
}
let summarize_gconst cst =
let pos = fst cst.cst_name in
let gconst_start = Option.value_map cst.cst_type ~f:fst ~default:pos in
let (_, gconst_end, _) = cst.cst_value in
let kind = GlobalConst in
let name = Utils.strip_ns (snd cst.cst_name) in
let id = get_symbol_id kind None name in
let full_name = get_full_name None name in
{
kind;
name;
full_name;
class_name = None;
id;
pos;
span = Pos.btw gconst_start gconst_end;
modifiers = [];
children = None;
params = None;
docblock = None;
}
let summarize_local name span =
let kind = LocalVar in
let id = get_symbol_id kind None name in
let full_name = get_full_name None name in
{
kind;
name;
full_name;
class_name = None;
id;
pos = span;
span;
modifiers = [];
children = None;
params = None;
docblock = None;
}
let summarize_module_def md =
let kind = SymbolDefinition.Module in
let name = snd md.md_name in
let full_name = get_full_name None name in
let id = get_symbol_id kind None name in
let span = md.md_span in
let doc_comment = md.md_doc_comment in
let docblock =
match doc_comment with
| None -> None
| Some dc -> Some (snd dc)
in
{
kind;
name;
full_name;
class_name = None;
id;
pos = span;
span;
modifiers = [];
children = None;
params = None;
docblock;
}
let outline_ast ast =
let outline =
List.filter_map ast ~f:(function
| Fun f -> Some (summarize_fun f)
| Class c -> Some (summarize_class c ~no_children:false)
| _ -> None)
in
List.map outline ~f:SymbolDefinition.to_absolute
let should_add_docblock = function
| Function
| Class
| Method
| Property
| ClassConst
| GlobalConst
| Enum
| Interface
| Trait
| Typeconst
| Typedef
| Module ->
true
| LocalVar
| TypeVar
| Param ->
false
let add_def_docblock finder previous_def_line def =
let line = Pos.line def.pos in
let docblock =
if should_add_docblock def.kind then
Docblock_finder.find_docblock finder previous_def_line line
else
None
in
(line, { def with docblock })
let add_docblocks defs comments =
let finder = Docblock_finder.make_docblock_finder comments in
let rec map_def f (acc : int) (def : string SymbolDefinition.t) =
let (acc, def) = f acc def in
let (acc, children) =
Option.value_map
def.children
~f:(fun defs ->
let (acc, defs) = map_def_list f acc defs in
(acc, Some defs))
~default:(acc, None)
in
(acc, { def with children })
and map_def_list f (acc : int) (defs : string SymbolDefinition.t list) =
let (acc, defs) =
List.fold_left
defs
~f:(fun (acc, defs) def ->
let (acc, def) = map_def f acc def in
(acc, def :: defs))
~init:(acc, [])
in
(acc, List.rev defs)
in
snd (map_def_list (add_def_docblock finder) 0 defs)
let outline popt content =
let { Parser_return.ast; comments; _ } =
let ast =
Errors.ignore_ (fun () ->
if Ide_parser_cache.is_enabled () then
Ide_parser_cache.(
with_ide_cache @@ fun () ->
get_ast popt Relative_path.default content)
else
let env =
Parser.make_env
~parser_options:popt
~include_line_comments:true
Relative_path.default
in
Parser.from_text_with_legacy env content)
in
ast
in
let result = outline_ast ast in
add_docblocks result comments
let outline_entry_no_comments
~(popt : ParserOptions.t) ~(entry : Provider_context.entry) :
string SymbolDefinition.t list =
Ast_provider.compute_ast ~popt ~entry |> outline_ast
let rec print_def ~short_pos indent def =
let {
name;
kind;
id;
pos;
span;
modifiers;
children;
params;
docblock;
full_name = _;
class_name = _;
} =
def
in
let (print_pos, print_span) =
if short_pos then
(Pos.string_no_file, Pos.multiline_string_no_file)
else
(Pos.string, Pos.multiline_string)
in
Printf.printf "%s%s\n" indent name;
Printf.printf "%s kind: %s\n" indent (string_of_kind kind);
Option.iter id ~f:(fun id -> Printf.printf "%s id: %s\n" indent id);
Printf.printf "%s position: %s\n" indent (print_pos pos);
Printf.printf "%s span: %s\n" indent (print_span span);
Printf.printf "%s modifiers: " indent;
List.iter modifiers ~f:(fun x -> Printf.printf "%s " (string_of_modifier x));
Printf.printf "\n";
Option.iter params ~f:(fun x ->
Printf.printf "%s params:\n" indent;
print ~short_pos (indent ^ " ") x);
Option.iter docblock ~f:(fun x ->
Printf.printf "%s docblock:\n" indent;
Printf.printf "%s\n" x);
Printf.printf "\n";
Option.iter children ~f:(fun x -> print ~short_pos (indent ^ " ") x)
and print ~short_pos indent defs =
List.iter defs ~f:(print_def ~short_pos indent)
let print_def ?(short_pos = false) = print_def ~short_pos
let print ?(short_pos = false) = print ~short_pos "" |
OCaml | hhvm/hphp/hack/src/server/findRefsService.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
open Option.Monad_infix
open Reordered_argument_collections
open ServerCommandTypes.Find_refs
open Typing_defs
module Cls = Decl_provider.Class
type member_class =
| Class_set of SSet.t
| Subclasses_of of string
type action_internal =
| IClass of string
| IExplicitClass of string
| IMember of member_class * member
| IFunction of string
| IGConst of string
let process_fun_id target_fun id =
if String.equal target_fun (snd id) then
Pos.Map.singleton (fst id) (snd id)
else
Pos.Map.empty
let check_if_extends_class ctx target_class_name class_name =
let class_ = Decl_provider.get_class ctx class_name in
match class_ with
| Some cls
when Cls.has_ancestor cls target_class_name
|| Cls.requires_ancestor cls target_class_name ->
true
| _ -> false
let is_target_class ctx target_classes class_name =
match target_classes with
| Class_set s -> SSet.mem s class_name
| Subclasses_of s ->
String.equal s class_name || check_if_extends_class ctx s class_name
let process_member_id
ctx target_classes target_member class_name mid ~is_method ~is_const =
let member_name = snd mid in
let is_target =
match target_member with
| Method target_name -> is_method && String.equal member_name target_name
| Property target_name ->
(not is_method)
&& (not is_const)
&& String.equal (String_utils.lstrip member_name "$") target_name
| Class_const target_name ->
is_const && String.equal member_name target_name
| Typeconst _ -> false
in
if is_target && is_target_class ctx target_classes class_name then
Pos.Map.singleton (fst mid) (class_name ^ "::" ^ snd mid)
else
Pos.Map.empty
let process_class_id
target_class
(pos, class_name)
(class_id_type : SymbolOccurrence.class_id_type)
(include_all_ci_types : bool) =
if String.equal target_class class_name then
match (include_all_ci_types, class_id_type) with
| (false, SymbolOccurrence.Other) -> Pos.Map.empty
| _ -> Pos.Map.singleton pos class_name
else
Pos.Map.empty
let process_taccess
ctx target_classes target_typeconst (class_name, tconst_name, p) =
if
is_target_class ctx target_classes class_name
&& String.equal target_typeconst tconst_name
then
Pos.Map.singleton p (class_name ^ "::" ^ tconst_name)
else
Pos.Map.empty
let process_gconst_id target_gconst id =
if String.equal target_gconst (snd id) then
Pos.Map.singleton (fst id) (snd id)
else
Pos.Map.empty
let add_if_extends_class ctx target_class_name class_name acc =
if check_if_extends_class ctx target_class_name class_name then
SSet.add acc class_name
else
acc
let find_child_classes ctx target_class_name naming_table files =
SharedMem.invalidate_local_caches ();
Relative_path.Set.fold files ~init:SSet.empty ~f:(fun fn acc ->
try
let { FileInfo.classes; _ } =
Naming_table.get_file_info_unsafe naming_table fn
in
List.fold_left classes ~init:acc ~f:(fun acc (_, cid, _) ->
add_if_extends_class ctx target_class_name cid acc)
with
| Naming_table.File_info_not_found -> acc)
let get_origin_class_name ctx class_name member =
let origin =
match member with
| Method method_name -> begin
match Decl_provider.get_class ctx class_name with
| Some class_ ->
let get_origin_class meth =
match meth with
| Some meth -> Some meth.ce_origin
| None -> None
in
let origin = get_origin_class (Cls.get_method class_ method_name) in
if Option.is_some origin then
origin
else
get_origin_class (Cls.get_smethod class_ method_name)
| None -> None
end
| Property _
| Class_const _
| Typeconst _ ->
None
in
Option.value origin ~default:class_name
let get_child_classes_files ctx class_name =
match Naming_provider.get_type_kind ctx class_name with
| Some Naming_types.TClass ->
let deps_mode = Provider_context.get_deps_mode ctx in
(* Find the files that contain classes that extend class_ *)
let cid_hash = Typing_deps.(Dep.make (Dep.Type class_name)) in
let extend_deps =
Decl_compare.get_extend_deps
deps_mode
cid_hash
(Typing_deps.DepSet.singleton cid_hash)
in
Naming_provider.get_files ctx extend_deps
| _ -> Relative_path.Set.empty
let get_deps_set ctx classes =
let deps_mode = Provider_context.get_deps_mode ctx in
SSet.fold
classes
~f:
begin
fun class_name acc ->
match Naming_provider.get_type_path ctx class_name with
| None -> acc
| Some fn ->
let dep = Typing_deps.Dep.Type class_name in
let ideps = Typing_deps.get_ideps deps_mode dep in
let files = Naming_provider.get_files ctx ideps in
let files = Relative_path.Set.add files fn in
Relative_path.Set.union files acc
end
~init:Relative_path.Set.empty
let get_files_for_descendants_and_dependents_of_members_in_descendants
ctx ~class_name members =
let mode = Provider_context.get_deps_mode ctx in
let class_dep =
Typing_deps.DepSet.singleton
(Typing_deps.Dep.make (Typing_deps.Dep.Type class_name))
in
let class_and_descendants_dep = Typing_deps.add_extend_deps mode class_dep in
let dependents =
Typing_deps.DepSet.fold
class_and_descendants_dep
~init:(Typing_deps.DepSet.make ())
~f:(fun descendant_dep result ->
List.fold members ~init:result ~f:(fun result member ->
let member_dep =
Typing_deps.Dep.make_member_dep_from_type_dep
descendant_dep
member
in
let member_fanout =
Typing_deps.get_ideps_from_hash mode member_dep
in
Typing_deps.DepSet.union result member_fanout))
in
( Naming_provider.get_files ctx class_and_descendants_dep,
Naming_provider.get_files ctx dependents )
let get_deps_set_function ctx f_name =
match Naming_provider.get_fun_path ctx f_name with
| Some fn ->
let deps_mode = Provider_context.get_deps_mode ctx in
let dep = Typing_deps.Dep.Fun f_name in
let ideps = Typing_deps.get_ideps deps_mode dep in
let files = Naming_provider.get_files ctx ideps in
Relative_path.Set.add files fn
| None -> Relative_path.Set.empty
let get_deps_set_gconst ctx cst_name =
match Naming_provider.get_const_path ctx cst_name with
| Some fn ->
let deps_mode = Provider_context.get_deps_mode ctx in
let dep = Typing_deps.Dep.GConst cst_name in
let ideps = Typing_deps.get_ideps deps_mode dep in
let files = Naming_provider.get_files ctx ideps in
Relative_path.Set.add files fn
| None -> Relative_path.Set.empty
let fold_one_tast ctx target acc symbol =
let module SO = SymbolOccurrence in
let SO.{ type_; pos; name; _ } = symbol in
Pos.Map.union acc
@@
match (target, type_) with
| (IMember (classes, Typeconst tc), SO.Typeconst (c_name, tc_name)) ->
process_taccess ctx classes tc (c_name, tc_name, pos)
| (IMember (classes, member), SO.Method (SO.ClassName c_name, m_name))
| (IMember (classes, member), SO.ClassConst (SO.ClassName c_name, m_name))
| (IMember (classes, member), SO.Property (SO.ClassName c_name, m_name))
| (IMember (classes, member), SO.XhpLiteralAttr (c_name, m_name)) ->
let mid = (pos, m_name) in
let is_method =
match type_ with
| SO.Method _ -> true
| _ -> false
in
let is_const =
match type_ with
| SO.ClassConst _ -> true
| _ -> false
in
process_member_id ctx classes member c_name mid ~is_method ~is_const
| (IFunction fun_name, SO.Function) -> process_fun_id fun_name (pos, name)
| (IClass c, SO.Class class_id_type) ->
let include_all_ci_types = true in
process_class_id c (pos, name) class_id_type include_all_ci_types
| (IExplicitClass c, SO.Class class_id_type) ->
let include_all_ci_types = false in
process_class_id c (pos, name) class_id_type include_all_ci_types
| (IGConst cst_name, SO.GConst) -> process_gconst_id cst_name (pos, name)
| _ -> Pos.Map.empty
let find_refs
(ctx : Provider_context.t)
(target : action_internal)
(acc : (string * Pos.t) list)
(files : Relative_path.t list)
~(omit_declaration : bool)
~(stream_file : Path.t option) : (string * Pos.t) list =
(* The helper function 'results_from_tast' takes a tast, looks at all *)
(* use-sites in the tast e.g. "foo(1)" is a use-site of symbol foo, *)
(* and returns a map from use-site-position to name of the symbol. *)
let results_from_tast tast : string Pos.Map.t =
IdentifySymbolService.all_symbols ctx tast
|> List.filter ~f:(fun symbol ->
if omit_declaration then
not symbol.SymbolOccurrence.is_declaration
else
true)
|> List.fold ~init:Pos.Map.empty ~f:(fold_one_tast ctx target)
in
(* Helper: [files] can legitimately refer to non-existent files, e.g.
if they've been deleted since the depgraph was created.
This is how we'll filter them out. *)
let is_entry_valid entry =
entry |> Provider_context.get_file_contents_if_present |> Option.is_some
in
(* Helper: given a path, obtains its tast *)
let tast_of_file path =
let (_ctx, entry) = Provider_context.add_entry_if_missing ~ctx ~path in
try
let { Tast_provider.Compute_tast.tast; _ } =
Tast_provider.compute_tast_unquarantined ~ctx ~entry
in
Some tast.Tast_with_dynamic.under_normal_assumptions
with
| _ when not (is_entry_valid entry) -> None
in
let stream_fd =
Option.map stream_file ~f:(fun file ->
Unix.openfile (Path.to_string file) [Unix.O_WRONLY; Unix.O_APPEND] 0o666)
in
Utils.try_finally
~finally:(fun () -> Option.iter stream_fd ~f:Unix.close)
~f:(fun () ->
let batch_results =
List.concat_map files ~f:(fun path ->
match tast_of_file path with
| None -> []
| Some tast ->
let results : string Pos.Map.t = results_from_tast tast in
let results : (string * Pos.t) list =
Pos.Map.fold (fun p str acc -> (str, p) :: acc) results []
in
Option.iter stream_fd ~f:(fun fd ->
results
|> List.map ~f:(fun (r, p) -> (r, Pos.to_absolute p))
|> FindRefsWireFormat.Ide_stream.append fd);
results)
in
batch_results @ acc)
let find_refs_ctx
~(ctx : Provider_context.t)
~(entry : Provider_context.entry)
~(target : action_internal) : (string * Pos.Map.key) list =
let symbols = IdentifySymbolService.all_symbols_ctx ~ctx ~entry in
let results =
symbols
|> List.filter ~f:(fun symbol -> not symbol.SymbolOccurrence.is_declaration)
|> List.fold ~init:Pos.Map.empty ~f:(fold_one_tast ctx target)
in
Pos.Map.fold (fun p str acc -> (str, p) :: acc) results []
let parallel_find_refs
workers
files
target
ctx
~(omit_declaration : bool)
~(stream_file : Path.t option) =
MultiWorker.call
workers
~job:(find_refs ctx target ~omit_declaration ~stream_file)
~neutral:[]
~merge:List.rev_append
~next:(MultiWorker.next workers files)
let get_definitions ctx action =
List.map ~f:(fun (name, pos) ->
(name, Naming_provider.resolve_position ctx pos))
@@
match action with
| IMember (Class_set classes, Method method_name) ->
SSet.fold classes ~init:[] ~f:(fun class_name acc ->
match Decl_provider.get_class ctx class_name with
| Some class_ ->
let add_meth get acc =
match get method_name with
| Some meth when String.equal meth.ce_origin (Cls.name class_) ->
let pos = get_pos @@ Lazy.force meth.ce_type in
(method_name, pos) :: acc
| _ -> acc
in
let acc = add_meth (Cls.get_method class_) acc in
let acc = add_meth (Cls.get_smethod class_) acc in
acc
| None -> acc)
| IMember (Class_set classes, Class_const class_const_name) ->
SSet.fold classes ~init:[] ~f:(fun class_name acc ->
match Decl_provider.get_class ctx class_name with
| Some class_ ->
let add_class_const get acc =
match get class_const_name with
| Some class_const
when String.equal class_const.cc_origin (Cls.name class_) ->
let pos = class_const.cc_pos in
(class_const_name, pos) :: acc
| _ -> acc
in
let acc = add_class_const (Cls.get_const class_) acc in
acc
| None -> acc)
| IExplicitClass class_name
| IClass class_name ->
Option.value
~default:[]
(Naming_provider.get_type_kind ctx class_name >>= function
| Naming_types.TClass ->
Decl_provider.get_class ctx class_name >>= fun class_ ->
Some [(class_name, Cls.pos class_)]
| Naming_types.TTypedef ->
Decl_provider.get_typedef ctx class_name >>= fun type_ ->
Some [(class_name, type_.td_pos)])
| IFunction fun_name -> begin
match Decl_provider.get_fun ctx fun_name with
| Some { fe_pos; _ } -> [(fun_name, fe_pos)]
| _ -> []
end
| IGConst _
| IMember (Subclasses_of _, _)
| IMember (_, (Property _ | Typeconst _)) ->
(* this code path is used only in ServerRename, we can update it at some
later time *)
[]
let find_references ctx workers target include_defs files ~stream_file =
let len = List.length files in
Hh_logger.debug "find_references: %d files" len;
let results =
if len < 10 then
find_refs ctx target [] files ~omit_declaration:true ~stream_file
else
parallel_find_refs
workers
files
target
ctx
~omit_declaration:true
~stream_file
in
let () =
Hh_logger.debug "find_references: %d results" (List.length results)
in
if include_defs then
let defs = get_definitions ctx target in
let () = Hh_logger.debug "find_references: +%d defs" (List.length defs) in
List.rev_append defs results
else
results
let find_references_single_file ctx target file =
let results =
find_refs ctx target [] [file] ~omit_declaration:false ~stream_file:None
in
let () =
Hh_logger.debug
"find_references_single_file: %d results"
(List.length results)
in
results
let get_dependent_files_function ctx _workers f_name =
(* This is performant enough to not need to go parallel for now *)
get_deps_set_function ctx f_name
let get_dependent_files_gconst ctx _workers cst_name =
(* This is performant enough to not need to go parallel for now *)
get_deps_set_gconst ctx cst_name
let get_dependent_files ctx _workers input_set =
(* This is performant enough to not need to go parallel for now *)
get_deps_set ctx input_set |
OCaml Interface | hhvm/hphp/hack/src/server/findRefsService.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.
*
*)
(* The class containing the member can be specified in two ways:
* - Class_set - as an explicit, pre-computed set of names, which are then
* compared using string comparison
* - Subclasses_of - the class's name, in which comparison will use the
* subtyping relation
*)
type member_class =
| Class_set of SSet.t
| Subclasses_of of string
type action_internal =
| IClass of string
| IExplicitClass of string
| IMember of member_class * ServerCommandTypes.Find_refs.member
| IFunction of string
| IGConst of string
val find_refs_ctx :
ctx:Provider_context.t ->
entry:Provider_context.entry ->
target:action_internal ->
(string * Pos.t) list
val find_references :
Provider_context.t ->
MultiWorker.worker list option ->
action_internal ->
bool ->
Relative_path.t list ->
stream_file:Path.t option ->
(string * Pos.t) list
val find_references_single_file :
Provider_context.t ->
action_internal ->
Relative_path.t ->
(string * Pos.t) list
val find_child_classes :
Provider_context.t ->
string ->
Naming_table.t ->
Relative_path.Set.t ->
SSet.t
val get_origin_class_name :
Provider_context.t -> string -> ServerCommandTypes.Find_refs.member -> string
val get_child_classes_files :
Provider_context.t -> string -> Relative_path.Set.t
val get_files_for_descendants_and_dependents_of_members_in_descendants :
Provider_context.t ->
class_name:string ->
Typing_deps.Dep.Member.t list ->
Relative_path.Set.t * Relative_path.Set.t
val get_dependent_files_function :
Provider_context.t ->
MultiWorker.worker list option ->
string ->
Relative_path.Set.t
val get_dependent_files_gconst :
Provider_context.t ->
MultiWorker.worker list option ->
string ->
Relative_path.Set.t
val get_dependent_files :
Provider_context.t ->
MultiWorker.worker list option ->
SSet.t ->
Relative_path.Set.t |
OCaml | hhvm/hphp/hack/src/server/findRefsWireFormat.ml | (*
* 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.
*
*)
open Hh_prelude
type half_open_one_based = {
filename: string; (** absolute *)
line: int; (** 1-based *)
char_start: int; (** 1-based *)
char_end: int; (** 1-based *)
}
let pos_to_one_based_json
?(timestamp : float option)
~(half_open_interval : bool)
((name, pos) : string * Pos.absolute) : Hh_json.json =
let (st_line, st_column, _ed_line, ed_column) =
if half_open_interval then
Pos.destruct_range pos
else
let (line, start, end_) = Pos.info_pos pos in
(line, start, line, end_)
in
let timestamp =
match timestamp with
| None -> []
| Some t -> [("timestamp", Hh_json.float_ t)]
in
Hh_json.JSON_Object
(timestamp
@ [
("name", Hh_json.JSON_String name);
("filename", Hh_json.JSON_String (Pos.filename pos));
("line", Hh_json.int_ st_line);
("char_start", Hh_json.int_ st_column);
("char_end", Hh_json.int_ ed_column);
])
let half_open_one_based_json_to_pos_exn (json : Hh_json.json) :
half_open_one_based =
let open Hh_json_helpers in
let json = Some json in
{
filename = Jget.string_exn json "filename";
line = Jget.int_exn json "line";
char_start = Jget.int_exn json "char_start";
char_end = Jget.int_exn json "char_end";
}
(** Produced by "hh --ide-find-refs-by-symbol" and parsed by clientLsp *)
module IdeShellout = struct
let to_string (results : (string * Pos.absolute) list) : string =
let entries =
List.map results ~f:(pos_to_one_based_json ~half_open_interval:true)
in
Hh_json.JSON_Array entries |> Hh_json.json_to_string
let from_string_exn (s : string) : half_open_one_based list =
let json = Hh_json.json_of_string s in
let entries = Hh_json.get_array_exn json in
List.map entries ~f:half_open_one_based_json_to_pos_exn
end
(** Used by hh_server's findRefsService to write to a streaming file, read by clientLsp *)
module Ide_stream = struct
let append (fd : Unix.file_descr) (results : (string * Pos.absolute) list) :
unit =
let bytes =
List.map results ~f:(fun (name, pos) ->
Printf.sprintf
"%s\n"
(pos_to_one_based_json
(name, pos)
~half_open_interval:true
~timestamp:(Unix.gettimeofday ())
|> Hh_json.json_to_string))
|> String.concat ~sep:""
|> Bytes.of_string
in
Sys_utils.with_lock fd Unix.F_LOCK ~f:(fun () ->
let (_ : int) = Unix.lseek fd 0 Unix.SEEK_END in
Sys_utils.write_non_intr fd bytes 0 (Bytes.length bytes);
Unix.fsync fd)
let read (fd : Unix.file_descr) ~(pos : int) : half_open_one_based list * int
=
Sys_utils.with_lock fd Unix.F_RLOCK ~f:(fun () ->
let end_pos = Unix.lseek fd 0 Unix.SEEK_END in
if pos = end_pos then
([], pos)
else
let (_ : int) = Unix.lseek fd pos Unix.SEEK_SET in
let bytes =
Sys_utils.read_non_intr fd (end_pos - pos) |> Option.value_exn
in
let jsons =
Bytes.to_string bytes
|> String_utils.split_on_newlines
|> List.map ~f:Hh_json.json_of_string
in
(List.map jsons ~f:half_open_one_based_json_to_pos_exn, end_pos))
end
(** Used "hh --find-refs --json" and read by HackAst and other tools *)
module HackAst = struct
let to_string results =
let entries =
List.map results ~f:(pos_to_one_based_json ~half_open_interval:false)
in
Hh_json.JSON_Array entries |> Hh_json.json_to_string
end
(** Used by "hh --find-refs" *)
module CliHumanReadable = struct
let print_results results =
List.iter results ~f:(fun (name, pos) ->
Printf.printf "%s %s\n" (Pos.string pos) name);
Printf.printf "%d total results\n" (List.length results)
end
(** CliArgs is produced by clientLsp when it invokes "hh --ide-find-refs-by-symbol <args>"
and consumed by clientArgs when it parses that argument. *)
module CliArgs = struct
open SearchTypes.Find_refs
type t = {
symbol_name: string;
action: SearchTypes.Find_refs.action;
stream_file: Path.t option;
hint_suffixes: string list;
}
(**
* Output strings in the form of
* SYMBOL_NAME|COMMA_SEPARATED_ACTION_STRING
* For example,
* HackTypecheckerQueryBase::getWWWDir|Member,\HackTypecheckerQueryBase,Method,getWWWDir
* Must be manually kept in sync with string_to_symbol_and_action_exn.
*)
let to_string { symbol_name; action; _ } : string =
let action_serialized =
match action with
| Class str -> Printf.sprintf "Class,%s" str
| ExplicitClass str -> Printf.sprintf "ExplicitClass,%s" str
| Function str -> Printf.sprintf "Function,%s" str
| GConst str -> Printf.sprintf "GConst,%s" str
| Member (str, Method s) ->
Printf.sprintf "Member,%s,%s,%s" str "Method" s
| Member (str, Property s) ->
Printf.sprintf "Member,%s,%s,%s" str "Property" s
| Member (str, Class_const s) ->
Printf.sprintf "Member,%s,%s,%s" str "Class_const" s
| Member (str, Typeconst s) ->
Printf.sprintf "Member,%s,%s,%s" str "Typeconst" s
| LocalVar _ ->
Printf.eprintf "Invalid action\n";
raise Exit_status.(Exit_with Input_error)
in
Printf.sprintf "%s|%s" symbol_name action_serialized
(**
* Expects input strings in the form of
* SYMBOL_NAME|COMMA_SEPARATED_ACTION_STRING
* For example,
* HackTypecheckerQueryBase::getWWWDir|Member,\HackTypecheckerQueryBase,Method,getWWWDir
* The implementation explicitly is tied to whatever is generated from symbol_and_action_to_string_exn
* and should be kept in sync manually by anybody editing.
*)
let from_string_exn (string1 : string) : t =
let pair = Str.split (Str.regexp "|") string1 in
let (symbol_name, action_arg) =
match pair with
| [symbol_name; action_arg] -> (symbol_name, action_arg)
| _ ->
Printf.eprintf "Invalid input\n";
raise Exit_status.(Exit_with Input_error)
in
let action =
(* Explicitly ignoring localvar support *)
match Str.split (Str.regexp ",") action_arg with
| ["Class"; str] -> Class str
| ["ExplicitClass"; str] -> ExplicitClass str
| ["Function"; str] -> Function str
| ["GConst"; str] -> GConst str
| ["Member"; str; "Method"; member_name] ->
Member (str, Method member_name)
| ["Member"; str; "Property"; member_name] ->
Member (str, Property member_name)
| ["Member"; str; "Class_const"; member_name] ->
Member (str, Class_const member_name)
| ["Member"; str; "Typeconst"; member_name] ->
Member (str, Typeconst member_name)
| _ ->
Printf.eprintf "Invalid input for action, got %s\n" action_arg;
raise Exit_status.(Exit_with Input_error)
in
{ symbol_name; action; stream_file = None; hint_suffixes = [] }
let to_string_triple { symbol_name; action; stream_file; hint_suffixes } :
string * string * string =
let action =
to_string { symbol_name; action; stream_file; hint_suffixes }
in
let stream_file =
Option.value_map stream_file ~default:"-" ~f:Path.to_string
in
let hint_suffixes = hint_suffixes |> String.concat ~sep:"|" in
(action, stream_file, hint_suffixes)
let from_string_triple_exn
((action, stream_file, hints) : string * string * string) : t =
let { symbol_name; action; _ } = from_string_exn action in
let stream_file =
if String.equal stream_file "-" then
None
else
Some (Path.make stream_file)
in
let hint_suffixes = String.split_on_chars hints ~on:['|'] in
{ symbol_name; action; stream_file; hint_suffixes }
end |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.