language
stringlengths
0
24
filename
stringlengths
9
214
code
stringlengths
99
9.93M
Rust
hhvm/hphp/hack/src/oxidized_by_ref/manual/mod.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. pub use crate::gen::aast_defs as aast; pub mod decl_counters; pub mod decl_env; pub mod direct_decl_parser; pub mod i_map; pub mod i_set; pub mod ident; pub mod lazy; pub mod local_id; pub mod local_id_map; pub mod method_flags; pub mod opaque_digest; pub mod pos; pub mod prop_flags; pub mod relative_path; pub mod s_map; pub mod s_set; pub mod shape_map; pub mod symbol_name; pub mod t_shape_map; pub mod tany_sentinel; pub mod typing_defs_flags; mod ast_defs_impl; mod shallow_decl_defs_impl; mod typing_defs_core_impl; mod typing_reason_impl;
Rust
hhvm/hphp/hack/src/oxidized_by_ref/manual/opaque_digest.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 no_pos_hash::NoPosHash; use ocamlrep::FromOcamlRepIn; use ocamlrep::ToOcamlRep; use serde::Deserialize; use serde::Serialize; #[derive( Copy, Clone, Debug, Deserialize, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct OpaqueDigest<'a>(pub &'a [u8]);
Rust
hhvm/hphp/hack/src/oxidized_by_ref/manual/pos.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::cmp::Ordering; use std::ops::Range; use std::result::Result::*; use bumpalo::Bump; use eq_modulo_pos::EqModuloPos; use ocamlrep::FromOcamlRepIn; use ocamlrep::ToOcamlRep; use oxidized::file_pos::FilePos; use oxidized::file_pos_large::FilePosLarge; use oxidized::file_pos_small::FilePosSmall; use oxidized::pos_span_raw::PosSpanRaw; use oxidized::pos_span_tiny::PosSpanTiny; use serde::Deserialize; use serde::Serialize; use crate::relative_path::RelativePath; #[derive(Clone, Deserialize, Hash, Serialize, ToOcamlRep, FromOcamlRepIn)] enum PosImpl<'a> { Small { #[serde(deserialize_with = "arena_deserializer::arena", borrow)] file: &'a RelativePath<'a>, start: FilePosSmall, end: FilePosSmall, }, Large { #[serde(deserialize_with = "arena_deserializer::arena", borrow)] file: &'a RelativePath<'a>, #[serde(deserialize_with = "arena_deserializer::arena", borrow)] start: &'a FilePosLarge, #[serde(deserialize_with = "arena_deserializer::arena", borrow)] end: &'a FilePosLarge, }, Tiny { #[serde(deserialize_with = "arena_deserializer::arena", borrow)] file: &'a RelativePath<'a>, span: PosSpanTiny, }, } arena_deserializer::impl_deserialize_in_arena!(PosImpl<'arena>); impl arena_trait::TrivialDrop for PosImpl<'_> {} use PosImpl::*; #[derive(Clone, Deserialize, Hash, Serialize, ToOcamlRep, FromOcamlRepIn)] pub struct Pos<'a>(#[serde(deserialize_with = "arena_deserializer::arena", borrow)] PosImpl<'a>); arena_deserializer::impl_deserialize_in_arena!(Pos<'arena>); impl arena_trait::TrivialDrop for Pos<'_> {} const NONE: Pos<'_> = Pos(Tiny { file: RelativePath::empty(), span: PosSpanTiny::make_dummy(), }); impl<'a> Pos<'a> { pub const fn none() -> &'static Pos<'static> { &NONE } pub fn is_none(&self) -> bool { match self { Pos(PosImpl::Tiny { file, span }) => span.is_dummy() && file.is_empty(), _ => false, } } pub fn from_raw_span(b: &'a Bump, file: &'a RelativePath<'a>, span: PosSpanRaw) -> &'a Self { if let Some(span) = PosSpanTiny::make(&span.start, &span.end) { return b.alloc(Pos(Tiny { file, span })); } let (lnum, bol, offset) = span.start.line_beg_offset(); if let Some(start) = FilePosSmall::from_lnum_bol_offset(lnum, bol, offset) { let (lnum, bol, offset) = span.end.line_beg_offset(); if let Some(end) = FilePosSmall::from_lnum_bol_offset(lnum, bol, offset) { return b.alloc(Pos(Small { file, start, end })); } } b.alloc(Pos(Large { file, start: b.alloc(span.start), end: b.alloc(span.end), })) } pub fn to_raw_span(&self) -> PosSpanRaw { match &self.0 { Tiny { span, .. } => span.to_raw_span(), &Small { start, end, .. } => PosSpanRaw { start: start.into(), end: end.into(), }, Large { start, end, .. } => PosSpanRaw { start: **start, end: **end, }, } } pub fn filename(&self) -> &'a RelativePath<'a> { match &self.0 { Small { file, .. } | Large { file, .. } | Tiny { file, .. } => file, } } /// Returns a closed interval that's incorrect for multi-line spans. pub fn info_pos(&self) -> (usize, usize, usize) { fn compute<P: FilePos>(pos_start: P, pos_end: P) -> (usize, usize, usize) { let (line, start_minus1, bol) = pos_start.line_column_beg(); let start = start_minus1.wrapping_add(1); let end_offset = pos_end.offset(); let mut end = end_offset - bol; // To represent the empty interval, pos_start and pos_end are equal because // end_offset is exclusive. Here, it's best for error messages to the user if // we print characters N to N (highlighting a single character) rather than characters // N to (N-1), which is very unintuitive. if start_minus1 == end { end = start } (line, start, end) } match self.0 { Small { start, end, .. } => compute(start, end), Large { start, end, .. } => compute(*start, *end), Tiny { span, .. } => { let PosSpanRaw { start, end } = span.to_raw_span(); compute(start, end) } } } pub fn info_pos_extended(&self) -> (usize, usize, usize, usize) { let (line_begin, start, end) = self.info_pos(); let line_end = match self.0 { Small { end, .. } => end.line_column_beg(), Large { end, .. } => end.line_column_beg(), Tiny { span, .. } => span.to_raw_span().end.line_column_beg(), } .0; (line_begin, line_end, start, end) } pub fn info_raw(&self) -> (usize, usize) { (self.start_offset(), self.end_offset()) } pub fn line(&self) -> usize { match self.0 { Small { start, .. } => start.line(), Large { start, .. } => start.line(), Tiny { span, .. } => span.start_line_number(), } } pub fn from_lnum_bol_offset( b: &'a Bump, file: &'a RelativePath<'a>, start: (usize, usize, usize), end: (usize, usize, usize), ) -> &'a Self { let (start_line, start_bol, start_offset) = start; let (end_line, end_bol, end_offset) = end; let start = FilePosLarge::from_lnum_bol_offset(start_line, start_bol, start_offset); let end = FilePosLarge::from_lnum_bol_offset(end_line, end_bol, end_offset); Self::from_raw_span(b, file, PosSpanRaw { start, end }) } pub fn to_start_and_end_lnum_bol_offset( &self, ) -> ((usize, usize, usize), (usize, usize, usize)) { match &self.0 { Small { start, end, .. } => (start.line_beg_offset(), end.line_beg_offset()), Large { start, end, .. } => (start.line_beg_offset(), end.line_beg_offset()), Tiny { span, .. } => { let PosSpanRaw { start, end } = span.to_raw_span(); (start.line_beg_offset(), end.line_beg_offset()) } } } /// For single-line spans only. pub fn from_line_cols_offset( b: &'a Bump, file: &'a RelativePath<'a>, line: usize, cols: Range<usize>, start_offset: usize, ) -> &'a Self { let start = FilePosLarge::from_line_column_offset(line, cols.start, start_offset); let end = FilePosLarge::from_line_column_offset( line, cols.end, start_offset + (cols.end - cols.start), ); Self::from_raw_span(b, file, PosSpanRaw { start, end }) } pub fn btw_nocheck(b: &'a Bump, x1: &'a Self, x2: &'a Self) -> &'a Self { let start = x1.to_raw_span().start; let end = x2.to_raw_span().end; Self::from_raw_span(b, x1.filename(), PosSpanRaw { start, end }) } pub fn btw(b: &'a Bump, x1: &'a Self, x2: &'a Self) -> Result<&'a Self, String> { let file1 = x1.filename(); let file2 = x2.filename(); if !std::ptr::eq(file1, file2) && file1 != file2 { // using string concatenation instead of format!, // it is not stable see T52404885 Err(String::from("Position in separate files ") + &x1.filename().to_string() + " and " + &x2.filename().to_string()) } else if x1.end_offset() > x2.end_offset() { Err(String::from("btw: invalid positions") + &x1.end_offset().to_string() + "and" + &x2.end_offset().to_string()) } else { Ok(Self::btw_nocheck(b, x1, x2)) } } pub fn merge(b: &'a Bump, x1: &'a Self, x2: &'a Self) -> Result<&'a Self, String> { let file1 = x1.filename(); let file2 = x2.filename(); if !std::ptr::eq(file1, file2) && file1 != file2 { // see comment above (T52404885) return Err(String::from("Position in separate files ") + &x1.filename().to_string() + " and " + &x2.filename().to_string()); } Ok(Self::merge_without_checking_filename(b, x1, x2)) } /// Return the smallest position containing both given positions (if they /// are both in the same file). The returned position will have the /// filename of the first Pos argument. /// /// For merging positions that may not occur within the same file, use /// `Pos::merge`. pub fn merge_without_checking_filename(b: &'a Bump, x1: &'a Self, x2: &'a Self) -> &'a Self { let span1 = x1.to_raw_span(); let span2 = x2.to_raw_span(); let start = if span1.start.is_dummy() { span2.start } else if span2.start.is_dummy() { span1.start } else if span1.start.offset() < span2.start.offset() { span1.start } else { span2.start }; let end = if span1.end.is_dummy() { span2.end } else if span2.end.is_dummy() { span1.end } else if span1.end.offset() < span2.end.offset() { span2.end } else { span1.end }; Self::from_raw_span(b, x1.filename(), PosSpanRaw { start, end }) } pub fn last_char(&'a self, b: &'a Bump) -> &'a Self { if self.is_none() { self } else { let end = self.to_raw_span().end; Self::from_raw_span(b, self.filename(), PosSpanRaw { start: end, end }) } } pub fn first_char_of_line(&'a self, b: &'a Bump) -> &'a Self { if self.is_none() { self } else { let start = self.to_raw_span().start.with_column(0); Self::from_raw_span(b, self.filename(), PosSpanRaw { start, end: start }) } } pub fn end_offset(&self) -> usize { match &self.0 { Small { end, .. } => end.offset(), Large { end, .. } => end.offset(), Tiny { span, .. } => span.end_offset(), } } pub fn start_offset(&self) -> usize { match &self.0 { Small { start, .. } => start.offset(), Large { start, .. } => start.offset(), Tiny { span, .. } => span.start_offset(), } } pub fn to_owned(&self) -> oxidized::pos::Pos { let file = self.filename(); let PosSpanRaw { start, end } = self.to_raw_span(); oxidized::pos::Pos::from_lnum_bol_offset( std::sync::Arc::new(file.to_oxidized()), start.line_beg_offset(), end.line_beg_offset(), ) } } impl<'a> Pos<'a> { pub fn from_oxidized_in(pos: &oxidized::pos::Pos, arena: &'a Bump) -> &'a Self { let file = RelativePath::from_oxidized_in(pos.filename(), arena); let (start, end) = pos.to_start_and_end_lnum_bol_offset(); Self::from_lnum_bol_offset(arena, file, start, end) } pub fn from_oxidized_with_file_in( pos: &oxidized::pos::Pos, file: &'a RelativePath<'a>, arena: &'a Bump, ) -> &'a Self { debug_assert!(pos.filename().prefix() == file.prefix()); debug_assert!(pos.filename().path() == file.path()); let (start, end) = pos.to_start_and_end_lnum_bol_offset(); Self::from_lnum_bol_offset(arena, file, start, end) } } impl std::fmt::Debug for Pos<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn do_fmt<P: FilePos>( f: &mut std::fmt::Formatter<'_>, file: &RelativePath<'_>, start: &P, end: &P, ) -> std::fmt::Result { let (start_line, start_col, _) = start.line_column_beg(); let (end_line, end_col, _) = end.line_column_beg(); // Use a format string rather than Formatter::debug_tuple to prevent // adding line breaks. Positions occur very frequently in ASTs and // types, so the Debug implementation of those data structures is // more readable if we minimize the vertical space taken up by // positions. Depends upon RelativePath's implementation of Display // also being single-line. if start_line == end_line { write!( f, "Pos({}, {}:{}-{})", &file, &start_line, &start_col, &end_col, ) } else { write!( f, "Pos({}, {}:{}-{}:{})", &file, &start_line, &start_col, &end_line, &end_col, ) } } match &self.0 { Small { file, start, end } => do_fmt(f, file, start, end), Large { file, start, end } => do_fmt(f, file, *start, *end), Tiny { file, span } => { let PosSpanRaw { start, end } = span.to_raw_span(); do_fmt(f, file, &start, &end) } } } } impl std::fmt::Display for Pos<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn do_fmt<P: FilePos>( f: &mut std::fmt::Formatter<'_>, file: &RelativePath<'_>, start: P, end: P, ) -> std::fmt::Result { write!(f, "{}", file)?; let (start_line, start_col, _) = start.line_column_beg(); let (end_line, end_col, _) = end.line_column_beg(); if start_line == end_line { write!(f, "({}:{}-{})", start_line, start_col, end_col) } else { write!(f, "({}:{}-{}:{})", start_line, start_col, end_line, end_col) } } match self.0 { Small { file, start, end } => do_fmt(f, file, start, end), Large { file, start, end } => do_fmt(f, file, *start, *end), Tiny { file, span } => { let PosSpanRaw { start, end } = span.to_raw_span(); do_fmt(f, file, start, end) } } } } impl Ord for Pos<'_> { // Intended to match the implementation of `Pos.compare` in OCaml. fn cmp(&self, other: &Pos<'_>) -> Ordering { self.filename() .cmp(other.filename()) .then(self.start_offset().cmp(&other.start_offset())) .then(self.end_offset().cmp(&other.end_offset())) } } impl PartialOrd for Pos<'_> { fn partial_cmp(&self, other: &Pos<'_>) -> Option<Ordering> { Some(self.cmp(other)) } } impl PartialEq for Pos<'_> { fn eq(&self, other: &Self) -> bool { self.cmp(other) == Ordering::Equal } } impl Eq for Pos<'_> {} impl<'a> Pos<'a> { /// Returns a struct implementing Display which produces the same format as /// `Pos.string` in OCaml. pub fn string(&self) -> PosString<'_> { PosString(self) } } impl EqModuloPos for Pos<'_> { fn eq_modulo_pos(&self, _rhs: &Self) -> bool { true } fn eq_modulo_pos_and_reason(&self, _rhs: &Self) -> bool { true } } /// This struct has an impl of Display which produces the same format as /// `Pos.string` in OCaml. pub struct PosString<'a>(&'a Pos<'a>); impl std::fmt::Display for PosString<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let (line, start, end) = self.0.info_pos(); write!( f, "File {:?}, line {}, characters {}-{}:", self.0.filename().path(), line, start, end ) } } // NoPosHash is meant to be position-insensitive, so don't do anything! impl no_pos_hash::NoPosHash for Pos<'_> { fn hash<H: std::hash::Hasher>(&self, _state: &mut H) {} } pub mod map { pub type Map<'a, T> = arena_collections::map::Map<'a, super::Pos<'a>, T>; } #[cfg(test)] mod tests { use pretty_assertions::assert_eq; use relative_path::Prefix; use super::*; fn make_pos<'a>( b: &'a Bump, name: &'a RelativePath<'a>, start: (usize, usize, usize), end: (usize, usize, usize), ) -> &'a Pos<'a> { b.alloc(Pos::from_lnum_bol_offset(b, name, start, end)) } #[test] fn test_pos_is_none() { let b = Bump::new(); assert!(Pos::none().is_none()); let path_a = b.alloc(RelativePath::make(Prefix::Dummy, "a")); assert!(!Pos::from_lnum_bol_offset(&b, path_a, (0, 0, 0), (0, 0, 0)).is_none()); let empty_path = b.alloc(RelativePath::make(Prefix::Dummy, "")); assert!(!Pos::from_lnum_bol_offset(&b, empty_path, (1, 0, 0), (0, 0, 0)).is_none()); } #[test] fn test_pos_string() { assert_eq!( Pos::none().string().to_string(), r#"File "", line 0, characters 0-0:"# ); let b = Bump::new(); let path = b.alloc(RelativePath::make(Prefix::Dummy, "a.php")); assert_eq!( Pos::from_lnum_bol_offset(&b, path, (5, 100, 117), (5, 100, 142)) .string() .to_string(), r#"File "a.php", line 5, characters 18-42:"# ); } #[test] fn test_pos_merge() { let b = Bump::new(); let test = |name, (exp_start, exp_end), ((fst_start, fst_end), (snd_start, snd_end))| { let path = b.alloc(RelativePath::make(Prefix::Dummy, "a")); assert_eq!( Ok(make_pos(&b, path, exp_start, exp_end)), Pos::merge( &b, make_pos(&b, path, fst_start, fst_end), make_pos(&b, path, snd_start, snd_end) ), "{}", name ); // Run this again because we want to test that we get the same // result regardless of order. assert_eq!( Ok(make_pos(&b, path, exp_start, exp_end)), Pos::merge( &b, make_pos(&b, path, snd_start, snd_end), make_pos(&b, path, fst_start, fst_end), ), "{} (reversed)", name ); }; test( "basic test", ((0, 0, 0), (0, 0, 5)), (((0, 0, 0), (0, 0, 2)), ((0, 0, 2), (0, 0, 5))), ); test( "merge should work with gaps", ((0, 0, 0), (0, 0, 15)), (((0, 0, 0), (0, 0, 5)), ((0, 0, 10), (0, 0, 15))), ); test( "merge should work with overlaps", ((0, 0, 0), (0, 0, 15)), (((0, 0, 0), (0, 0, 12)), ((0, 0, 7), (0, 0, 15))), ); test( "merge should work between lines", ((0, 0, 0), (2, 20, 25)), (((0, 0, 0), (1, 10, 15)), ((1, 10, 20), (2, 20, 25))), ); assert_eq!( Err("Position in separate files |a and |b".to_string()), Pos::merge( &b, make_pos( &b, &RelativePath::make(Prefix::Dummy, "a"), (0, 0, 0), (0, 0, 0) ), make_pos( &b, &RelativePath::make(Prefix::Dummy, "b"), (0, 0, 0), (0, 0, 0) ) ), "should reject merges with different filenames" ); } #[test] fn position_insensitive_hash() { use crate::ast_defs::Id; let b = &bumpalo::Bump::new(); let hash = no_pos_hash::position_insensitive_hash; let none = Pos::none(); let pos = Pos::from_line_cols_offset(b, RelativePath::empty(), 2, 2..10, 17); assert_eq!(hash(&Id(pos, "foo")), hash(&Id(pos, "foo"))); assert_eq!(hash(&Id(none, "foo")), hash(&Id(pos, "foo"))); assert_ne!(hash(&Id(pos, "foo")), hash(&Id(pos, "bar"))); } }
Rust
hhvm/hphp/hack/src/oxidized_by_ref/manual/prop_flags.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use bitflags::bitflags; use eq_modulo_pos::EqModuloPos; // NB: Keep the values of these flags in sync with shallow_decl_defs.ml. bitflags! { #[derive(EqModuloPos)] pub struct PropFlags: u16 { const ABSTRACT = 1 << 0; const CONST = 1 << 1; const LATEINIT = 1 << 2; const LSB = 1 << 3; const NEEDS_INIT = 1 << 4; const PHP_STD_LIB = 1 << 5; const READONLY = 1 << 6; const SAFE_GLOBAL_VARIABLE = 1 << 7; const NO_AUTO_LIKES = 1 << 8; } } impl PropFlags { pub fn is_abstract(&self) -> bool { self.contains(Self::ABSTRACT) } pub fn is_const(&self) -> bool { self.contains(Self::CONST) } pub fn is_lateinit(&self) -> bool { self.contains(Self::LATEINIT) } pub fn is_readonly(&self) -> bool { self.contains(Self::READONLY) } pub fn needs_init(&self) -> bool { self.contains(Self::NEEDS_INIT) } pub fn is_lsb(&self) -> bool { self.contains(Self::LSB) } pub fn is_safe_global_variable(&self) -> bool { self.contains(Self::SAFE_GLOBAL_VARIABLE) } pub fn no_auto_likes(&self) -> bool { self.contains(Self::NO_AUTO_LIKES) } } impl ocamlrep::ToOcamlRep for PropFlags { fn to_ocamlrep<'a, A: ocamlrep::Allocator>(&'a self, _alloc: &'a A) -> ocamlrep::Value<'a> { ocamlrep::Value::int(self.bits() as isize) } } impl ocamlrep::FromOcamlRep for PropFlags { fn from_ocamlrep(value: ocamlrep::Value<'_>) -> Result<Self, ocamlrep::FromError> { let int_value = ocamlrep::from::expect_int(value)?; Ok(Self::from_bits_truncate(int_value.try_into()?)) } } impl<'a> ocamlrep::FromOcamlRepIn<'a> for PropFlags { fn from_ocamlrep_in( value: ocamlrep::Value<'_>, _alloc: &'a bumpalo::Bump, ) -> Result<Self, ocamlrep::FromError> { use ocamlrep::FromOcamlRep; Self::from_ocamlrep(value) } } impl no_pos_hash::NoPosHash for PropFlags { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { std::hash::Hash::hash(self, state); } } impl serde::Serialize for PropFlags { fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { serializer.serialize_u16(self.bits()) } } impl<'de> serde::Deserialize<'de> for PropFlags { fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { struct Visitor; impl<'de> serde::de::Visitor<'de> for Visitor { type Value = PropFlags; fn expecting(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { write!(formatter, "a u16 for PropFlags") } fn visit_u16<E: serde::de::Error>(self, value: u16) -> Result<Self::Value, E> { Ok(Self::Value::from_bits_truncate(value)) } fn visit_u64<E: serde::de::Error>(self, value: u64) -> Result<Self::Value, E> { Ok(Self::Value::from_bits_truncate( u16::try_from(value).expect("expect an u16, but got u64"), )) } } deserializer.deserialize_u16(Visitor) } }
Rust
hhvm/hphp/hack/src/oxidized_by_ref/manual/relative_path.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::fmt; use std::fmt::Debug; use std::fmt::Display; use std::path::Path; use bumpalo::Bump; use eq_modulo_pos::EqModuloPos; use no_pos_hash::NoPosHash; use ocamlrep::ToOcamlRep; use relative_path::Prefix; use serde::Deserialize; use serde::Serialize; // Named Relative_path.default in OCaml, but it really isn't a suitable default // for most purposes. pub const EMPTY: RelativePath<'_> = RelativePath { prefix: Prefix::Dummy, path: None, }; #[derive( Copy, Clone, Eq, EqModuloPos, Hash, NoPosHash, Ord, PartialEq, PartialOrd )] pub struct RelativePath<'a> { prefix: Prefix, // Invariant: if Some, the path has length > 0. The use of Option here is // solely to allow us to assign EMPTY above, since it is not (yet) possible // to construct a Path in a const context. path: Option<&'a Path>, } //arena_deserializer::impl_deserialize_in_arena!(RelativePath<'arena>); impl<'a> RelativePath<'a> { pub const fn empty() -> &'static RelativePath<'static> { &EMPTY } pub fn new(prefix: Prefix, path: &'a Path) -> Self { let path = if path == Path::new("") { None } else { Some(path) }; Self { prefix, path } } pub fn make(prefix: Prefix, path: &'a str) -> Self { Self::new(prefix, Path::new(path)) } pub fn is_empty(&self) -> bool { self.prefix == Prefix::Dummy && self.path.is_none() } pub fn has_extension(&self, s: impl AsRef<std::ffi::OsStr>) -> bool { self.path().extension() == Some(s.as_ref()) } pub fn path(&self) -> &Path { match self.path { None => Path::new(""), Some(path) => path, } } pub fn path_str(&self) -> Option<&str> { self.path().to_str() } pub fn prefix(&self) -> Prefix { self.prefix } /// TODO(ljw): rename this pub fn to_oxidized(&self) -> relative_path::RelativePath { relative_path::RelativePath::make(self.prefix, self.path().to_owned()) } /// TODO(ljw): rename this pub fn from_oxidized_in(path: &relative_path::RelativePath, arena: &'a Bump) -> &'a Self { let path_str = bumpalo::collections::String::from_str_in(path.path_str(), arena).into_bump_str(); arena.alloc(Self::make(path.prefix(), path_str)) } } impl Debug for RelativePath<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { // Use a format string rather than Formatter::debug_struct to prevent // adding line breaks (they don't help readability here). write!(f, "RelativePath({})", self) } } impl Display for RelativePath<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}|{}", self.prefix, self.path().display()) } } impl arena_trait::TrivialDrop for RelativePath<'_> {} impl ToOcamlRep for RelativePath<'_> { fn to_ocamlrep<'a, A: ocamlrep::Allocator>(&'a self, alloc: &'a A) -> ocamlrep::Value<'a> { let mut block = alloc.block_with_size(2); alloc.set_field(&mut block, 0, alloc.add(&self.prefix)); alloc.set_field(&mut block, 1, alloc.add(self.path())); block.build() } } impl<'a> ocamlrep::FromOcamlRepIn<'a> for RelativePath<'a> { fn from_ocamlrep_in( value: ocamlrep::Value<'_>, alloc: &'a bumpalo::Bump, ) -> Result<Self, ocamlrep::FromError> { let (prefix, path) = <(Prefix, &'a Path)>::from_ocamlrep_in(value, alloc)?; Ok(Self::new(prefix, path)) } } // This custom implementation of Serialize/Deserialize encodes the RelativePath // as a string. This allows using it as a map key in serde_json. impl Serialize for RelativePath<'_> { fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { let path_str = self .path() .to_str() .ok_or_else(|| serde::ser::Error::custom("path contains invalid UTF-8 characters"))?; serializer.serialize_str(&format!("{}|{}", self.prefix, path_str)) } } fn parse(value: &str) -> Result<RelativePath<'_>, String> { let mut split = value.splitn(2, '|'); let prefix_str = split.next(); let path_str = split.next(); assert!(split.next().is_none(), "splitn(2) should yield <=2 results"); let prefix = match prefix_str { Some("root") => Prefix::Root, Some("hhi") => Prefix::Hhi, Some("tmp") => Prefix::Tmp, Some("") => Prefix::Dummy, _ => { return Err(format!("unknown relative_path::Prefix: {:?}", value)); } }; let path = match path_str { Some(path_str) => path_str, None => { return Err(format!( "missing pipe or got empty string when deserializing RelativePath, raw string \"{}\"", value )); } }; Ok(RelativePath::make(prefix, path)) } // See comment on impl of Serialize above. impl<'de> Deserialize<'de> for RelativePath<'de> { 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 = RelativePath<'de>; fn expecting(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { write!(formatter, "a string for RelativePath") } fn visit_borrowed_str<E>(self, value: &'de str) -> Result<RelativePath<'_>, E> where E: serde::de::Error, { parse(value).map_err(|e| E::invalid_value(serde::de::Unexpected::Other(&e), &self)) } } deserializer.deserialize_str(Visitor) } } impl<'arena> arena_deserializer::DeserializeInArena<'arena> for RelativePath<'arena> { fn deserialize_in_arena<D>( arena: &'arena bumpalo::Bump, deserializer: D, ) -> Result<Self, D::Error> where D: serde::Deserializer<'arena>, { struct Visitor<'a> { arena: &'a bumpalo::Bump, } impl<'arena, 'de> serde::de::Visitor<'de> for Visitor<'arena> { type Value = RelativePath<'arena>; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("[DeserializeInArena] string for RelativePath") } fn visit_str<E>(self, value: &str) -> Result<RelativePath<'arena>, E> where E: serde::de::Error, { let s = self.arena.alloc_str(value); parse(s).map_err(|e| E::invalid_value(serde::de::Unexpected::Other(&e), &self)) } } deserializer.deserialize_str(Visitor { arena }) } } impl<'arena> arena_deserializer::DeserializeInArena<'arena> for &'arena RelativePath<'arena> { fn deserialize_in_arena<D>( arena: &'arena bumpalo::Bump, deserializer: D, ) -> Result<Self, D::Error> where D: serde::Deserializer<'arena>, { let r = RelativePath::deserialize_in_arena(arena, deserializer)?; Ok(arena.alloc(r)) } } pub type Map<'a, T> = arena_collections::SortedAssocList<'a, RelativePath<'a>, T>; pub mod map { pub use super::Map; } #[cfg(test)] mod tests { use std::path::Path; use arena_deserializer::ArenaDeserializer; use arena_deserializer::DeserializeInArena; use super::*; #[test] fn test_serde() { let x = RelativePath::new(Prefix::Dummy, Path::new("/tmp/foo.php")); let se = serde_json::to_string(&x).unwrap(); let mut de = serde_json::Deserializer::from_str(&se); let x1 = RelativePath::deserialize(&mut de).unwrap(); assert_eq!(x, x1); } #[test] fn test_serde_with_arena() { let x = RelativePath::new(Prefix::Dummy, Path::new("/tmp/foo.php")); let se = serde_json::to_string(&x).unwrap(); let mut de = serde_json::Deserializer::from_str(&se); let arena = bumpalo::Bump::new(); let de = ArenaDeserializer::new(&arena, &mut de); let x1 = <&RelativePath<'_>>::deserialize_in_arena(&arena, de).unwrap(); assert_eq!(&x, x1); } }
Rust
hhvm/hphp/hack/src/oxidized_by_ref/manual/shallow_decl_defs_impl.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use oxidized::file_info::NameType; use crate::shallow_decl_defs::Decl; impl<'a> Decl<'a> { pub fn kind(&self) -> NameType { match self { Decl::Class(..) => NameType::Class, Decl::Fun(..) => NameType::Fun, Decl::Typedef(..) => NameType::Typedef, Decl::Const(..) => NameType::Const, Decl::Module(..) => NameType::Module, } } }
Rust
hhvm/hphp/hack/src/oxidized_by_ref/manual/shape_map.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::cmp::Ordering; use no_pos_hash::NoPosHash; use ocamlrep::FromOcamlRepIn; use ocamlrep::ToOcamlRep; use serde::Deserialize; use serde::Serialize; use crate::ast_defs::Id; use crate::ast_defs::ShapeFieldName; #[derive( Copy, Clone, Debug, Deserialize, FromOcamlRepIn, Hash, NoPosHash, Serialize, ToOcamlRep )] pub struct ShapeField<'a>( #[serde(deserialize_with = "arena_deserializer::arena", borrow)] pub ShapeFieldName<'a>, ); arena_deserializer::impl_deserialize_in_arena!(ShapeField<'arena>); impl arena_trait::TrivialDrop for ShapeField<'_> {} impl<'a> Ord for ShapeField<'a> { fn cmp(&self, other: &Self) -> Ordering { use ShapeFieldName::*; match (&self.0, &other.0) { (SFlitInt((_, s1)), SFlitInt((_, s2))) => s1.cmp(s2), (SFlitStr((_, s1)), SFlitStr((_, s2))) => s1.cmp(s2), (SFclassConst((Id(_, c1), (_, m1))), SFclassConst((Id(_, c2), (_, m2)))) => { (c1, m1).cmp(&(c2, m2)) } (SFlitInt(_), _) => Ordering::Less, (SFlitStr(_), SFlitInt(_)) => Ordering::Greater, (SFlitStr(_), _) => Ordering::Less, (SFclassConst(_), _) => Ordering::Greater, } } } impl<'a> PartialOrd for ShapeField<'a> { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl<'a> PartialEq for ShapeField<'a> { fn eq(&self, other: &Self) -> bool { self.cmp(other) == Ordering::Equal } } impl<'a> Eq for ShapeField<'a> {} pub type ShapeMap<'a, T> = arena_collections::SortedAssocList<'a, ShapeField<'a>, T>;
Rust
hhvm/hphp/hack/src/oxidized_by_ref/manual/symbol_name.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. pub mod fun_set { pub type FunSet<'a> = arena_collections::set::Set<'a, &'a str>; } pub mod type_set { pub type TypeSet<'a> = arena_collections::set::Set<'a, &'a str>; } pub mod const_set { pub type ConstSet<'a> = arena_collections::set::Set<'a, &'a str>; } pub mod i_fun { pub type IFun<'a> = &'a str; } pub mod i_type { pub type IType<'a> = &'a str; } pub mod i_const { pub type IConst<'a> = &'a str; }
Rust
hhvm/hphp/hack/src/oxidized_by_ref/manual/s_map.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. pub type SMap<'a, T> = arena_collections::map::Map<'a, &'a str, T>;
Rust
hhvm/hphp/hack/src/oxidized_by_ref/manual/s_set.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. pub type SSet<'a> = arena_collections::set::Set<'a, &'a str>;
Rust
hhvm/hphp/hack/src/oxidized_by_ref/manual/tany_sentinel.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 eq_modulo_pos::EqModuloPos; use no_pos_hash::NoPosHash; use ocamlrep::FromOcamlRep; use ocamlrep::FromOcamlRepIn; use ocamlrep::ToOcamlRep; use serde::Deserialize; use serde::Serialize; #[derive( Copy, Clone, Debug, Deserialize, Eq, EqModuloPos, Hash, NoPosHash, Ord, PartialEq, PartialOrd, FromOcamlRep, FromOcamlRepIn, ToOcamlRep, Serialize )] pub struct TanySentinel; arena_deserializer::impl_deserialize_in_arena!(TanySentinel); impl arena_trait::TrivialDrop for TanySentinel {}
Rust
hhvm/hphp/hack/src/oxidized_by_ref/manual/typing_defs_core_impl.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::cmp::Ordering; use crate::ast_defs::Id; use crate::ast_defs::ParamKind; use crate::ast_defs::Tprim; use crate::ident::Ident; use crate::pos::Pos; use crate::typing_defs_core::*; use crate::typing_reason::Reason; impl<'a> From<Id<'a>> for PosId<'a> { fn from(Id(pos, id): Id<'a>) -> Self { (pos, id) } } // Compare two types syntactically, ignoring reason information and other // small differences that do not affect type inference behaviour. This // comparison function can be used to construct tree-based sets of types, // or to compare two types for "exact" equality. // Note that this function does *not* expand type variables, or type // aliases. // But if compare_locl/decl_ty ty1 ty2 = 0, then the types must not be distinguishable // by any typing rules. impl PartialEq for Ty<'_> { fn eq(&self, other: &Self) -> bool { self.1 == other.1 } } impl Eq for Ty<'_> {} impl PartialOrd for Ty<'_> { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl Ord for Ty<'_> { fn cmp(&self, other: &Self) -> Ordering { self.1.cmp(&other.1) } } impl<'a> Ty<'a> { pub fn mk(reason: &'a Reason<'a>, ty_: Ty_<'a>) -> Ty<'a> { Ty(reason, ty_) } pub fn unpack(&self) -> (&'a Reason<'a>, Ty_<'a>) { (self.0, self.1) } pub fn get_node(&self) -> Ty_<'a> { self.1 } pub fn get_reason(&self) -> &'a Reason<'a> { let Ty(r, _t) = self; r } pub fn get_pos(&self) -> Option<&'a Pos<'a>> { self.get_reason().pos() } pub fn is_tyvar(&self) -> bool { match self.get_node() { Ty_::Tvar(_) => true, _ => false, } } pub fn is_generic(&self) -> bool { match self.get_node() { Ty_::Tgeneric(_) => true, _ => false, } } pub fn is_dynamic(&self) -> bool { match self.get_node() { Ty_::Tdynamic => true, _ => false, } } pub fn is_nonnull(&self) -> bool { match self.get_node() { Ty_::Tnonnull => true, _ => false, } } pub fn is_any(&self) -> bool { match self.get_node() { Ty_::Tany(_) => true, _ => false, } } pub fn is_prim(&self, kind: Tprim) -> bool { match self.get_node() { Ty_::Tprim(k) => kind == *k, _ => false, } } pub fn is_union(&self) -> bool { match self.get_node() { Ty_::Tunion(_) => true, _ => false, } } pub fn is_intersection(&self) -> bool { match self.get_node() { Ty_::Tintersection(_) => true, _ => false, } } } impl Ty<'_> { pub fn get_var(&self) -> Option<Ident> { match self.get_node() { Ty_::Tvar(v) => Some(v), _ => None, } } } impl std::fmt::Debug for Ty_<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { use Ty_::*; match self { Tthis => write!(f, "Tthis"), Tapply((id, tys)) => f.debug_tuple("Tapply").field(id).field(tys).finish(), Trefinement((ty, rs)) => f.debug_tuple("Trefinement").field(ty).field(rs).finish(), Taccess(taccess) => f.debug_tuple("Taccess").field(taccess).finish(), Tmixed => write!(f, "Tmixed"), Twildcard => write!(f, "Twildcard"), Tlike(ty) => f.debug_tuple("Tlike").field(ty).finish(), Tany(_) => write!(f, "Tany"), Tnonnull => write!(f, "Tnonnull"), Tdynamic => write!(f, "Tdynamic"), TunappliedAlias(name) => write!(f, "TunappliedAlias({:?})", name), Toption(ty) => f.debug_tuple("Toption").field(ty).finish(), Tprim(tprim) => write!(f, "Tprim({:?})", tprim), Tneg(tprim) => write!(f, "Tneg({:?})", tprim), Tfun(fun_type) => f.debug_tuple("Tfun").field(fun_type).finish(), Ttuple(tys) => f.debug_tuple("Ttuple").field(tys).finish(), Tshape(shape) => f.debug_tuple("Tshape").field(shape).finish(), Tvar(ident) => f.debug_tuple("Tvar").field(ident).finish(), Tgeneric((name, tys)) => write!(f, "Tgeneric({:?}, {:?})", name, tys), Tunion(tys) => f.debug_tuple("Tunion").field(tys).finish(), Tintersection(tys) => f.debug_tuple("Tintersection").field(tys).finish(), TvecOrDict((tk, tv)) => f.debug_tuple("TvecOrDict").field(tk).field(tv).finish(), Tnewtype((name, tys, constraint)) => f .debug_tuple("Tnewtype") .field(name) .field(tys) .field(constraint) .finish(), Tdependent((dependent_type, ty)) => f .debug_tuple("Tdependent") .field(dependent_type) .field(ty) .finish(), Tclass((id, exact, tys)) => f .debug_tuple("Tclass") .field(id) .field(exact) .field(tys) .finish(), } } } impl<'a> From<ParamKind<'a>> for ParamMode { fn from(callconv: ParamKind<'_>) -> Self { match callconv { ParamKind::Pinout(_) => ParamMode::FPinout, ParamKind::Pnormal => ParamMode::FPnormal, } } } impl<'a> std::fmt::Debug for TshapeFieldName<'a> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { use TshapeFieldName::*; match self { TSFlitInt(p) => f.debug_tuple("TSFlitInt").field(p).finish(), TSFlitStr(p) => f.debug_tuple("TSFlitStr").field(p).finish(), TSFclassConst((i, p)) => f.debug_tuple("TSFclassConst").field(i).field(p).finish(), } } }
Rust
hhvm/hphp/hack/src/oxidized_by_ref/manual/typing_defs_flags.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. pub use oxidized::typing_defs_flags::*;
Rust
hhvm/hphp/hack/src/oxidized_by_ref/manual/typing_reason_impl.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use crate::pos::Pos; use crate::typing_reason::*; const RNONE: &Reason<'_> = &Reason::Rnone; impl<'a> Reason<'a> { pub const fn none() -> &'static Reason<'static> { RNONE } pub fn hint(pos: &'a Pos<'a>) -> Self { Reason::Rhint(pos) } pub fn witness(pos: &'a Pos<'a>) -> Self { Reason::Rwitness(pos) } pub fn witness_from_decl(pos: &'a Pos<'a>) -> Self { Reason::RwitnessFromDecl(pos) } pub fn instantiate(args: &'a (Reason<'a>, &'a str, Reason<'a>)) -> Self { Reason::Rinstantiate(args) } pub fn pos(&self) -> Option<&'a Pos<'a>> { use T_::*; match self { Rnone => None, Rinvalid => None, Rwitness(p) | RwitnessFromDecl(p) | Ridx((p, _)) | RidxVector(p) | RidxVectorFromDecl(p) | Rforeach(p) | Rasyncforeach(p) | Rarith(p) | RarithRet(p) | RarithDynamic(p) | Rcomp(p) | RconcatRet(p) | RlogicRet(p) | Rbitwise(p) | RbitwiseRet(p) | RnoReturn(p) | RnoReturnAsync(p) | RretFunKind((p, _)) | RretFunKindFromDecl((p, _)) | Rhint(p) | Rthrow(p) | Rplaceholder(p) | RretDiv(p) | RyieldGen(p) | RyieldAsyncgen(p) | RyieldAsyncnull(p) | RyieldSend(p) | Rformat((p, _, _)) | RclassClass((p, _)) | RunknownClass(p) | RvarParam(p) | RvarParamFromDecl(p) | RunpackParam((p, _, _)) | RinoutParam(p) | Rtypeconst((Rnone, (p, _), _, _)) | RnullsafeOp(p) | RtconstNoCstr((p, _)) | Rpredicated((p, _)) | Ris(p) | Ras(p) | Requal(p) | RvarrayOrDarrayKey(p) | RvecOrDictKey(p) | Rusing(p) | RdynamicProp(p) | RdynamicCall(p) | RdynamicConstruct(p) | RidxDict(p) | RsetElement(p) | RmissingOptionalField((p, _)) | RunsetField((p, _)) | Rregex(p) | RimplicitUpperBound((p, _)) | RarithRetFloat((p, _, _)) | RarithRetNum((p, _, _)) | RarithRetInt(p) | RbitwiseDynamic(p) | RincdecDynamic(p) | RtypeVariable(p) | RtypeVariableGenerics((p, _, _)) | RtypeVariableError(p) | RglobalTypeVariableGenerics((p, _, _)) | RsolveFail(p) | RcstrOnGenerics((p, _)) | RlambdaParam((p, _)) | Rshape((p, _)) | RshapeLiteral(p) | Renforceable(p) | Rdestructure(p) | RkeyValueCollectionKey(p) | RglobalClassProp(p) | RglobalFunParam(p) | RglobalFunRet(p) | Rsplice(p) | RetBoolean(p) | RdefaultCapability(p) | RconcatOperand(p) | RinterpOperand(p) | RsupportDynamicType(p) | RdynamicPartialEnforcement((p, _, _)) | RrigidTvarEscape((p, _, _, _)) | RmissingClass(p) => Some(p), RlostInfo((_, r, _)) | Rinstantiate((_, _, r)) | Rtypeconst((r, _, _, _)) | RtypeAccess((r, _)) | RexprDepType((r, _, _)) | RcontravariantGeneric((r, _)) | RinvariantGeneric((r, _)) => r.pos(), RopaqueTypeFromModule((p, _, _)) => Some(p), RdynamicCoercion(r) => r.pos(), } } } impl<'a> std::fmt::Debug for T_<'a> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { use T_::*; match self { Rnone => f.debug_tuple("Rnone").finish(), Rwitness(p) => f.debug_tuple("Rwitness").field(p).finish(), RwitnessFromDecl(p) => f.debug_tuple("RwitnessFromDecl").field(p).finish(), Ridx((p, t)) => f.debug_tuple("Ridx").field(p).field(t).finish(), RidxVector(p) => f.debug_tuple("RidxVector").field(p).finish(), RidxVectorFromDecl(p) => f.debug_tuple("RidxVectorFromDecl").field(p).finish(), Rforeach(p) => f.debug_tuple("Rforeach").field(p).finish(), Rasyncforeach(p) => f.debug_tuple("Rasyncforeach").field(p).finish(), Rarith(p) => f.debug_tuple("Rarith").field(p).finish(), RarithRet(p) => f.debug_tuple("RarithRet").field(p).finish(), RarithRetFloat((p, t, ap)) => f .debug_tuple("RarithRetFloat") .field(p) .field(t) .field(ap) .finish(), RarithRetNum((p, t, ap)) => f .debug_tuple("RarithRetNum") .field(p) .field(t) .field(ap) .finish(), RarithRetInt(p) => f.debug_tuple("RarithRetInt").field(p).finish(), RarithDynamic(p) => f.debug_tuple("RarithDynamic").field(p).finish(), RbitwiseDynamic(p) => f.debug_tuple("RbitwiseDynamic").field(p).finish(), RincdecDynamic(p) => f.debug_tuple("RincdecDynamic").field(p).finish(), Rcomp(p) => f.debug_tuple("Rcomp").field(p).finish(), RconcatRet(p) => f.debug_tuple("RconcatRet").field(p).finish(), RlogicRet(p) => f.debug_tuple("RlogicRet").field(p).finish(), Rbitwise(p) => f.debug_tuple("Rbitwise").field(p).finish(), RbitwiseRet(p) => f.debug_tuple("RbitwiseRet").field(p).finish(), RnoReturn(p) => f.debug_tuple("RnoReturn").field(p).finish(), RnoReturnAsync(p) => f.debug_tuple("RnoReturnAsync").field(p).finish(), RretFunKind((p, fk)) => f.debug_tuple("RretFunKind").field(p).field(fk).finish(), RretFunKindFromDecl((p, fk)) => f .debug_tuple("RretFunKindFromDecl") .field(p) .field(fk) .finish(), Rhint(p) => f.debug_tuple("Rhint").field(p).finish(), Rthrow(p) => f.debug_tuple("Rthrow").field(p).finish(), Rplaceholder(p) => f.debug_tuple("Rplaceholder").field(p).finish(), RretDiv(p) => f.debug_tuple("RretDiv").field(p).finish(), RyieldGen(p) => f.debug_tuple("RyieldGen").field(p).finish(), RyieldAsyncgen(p) => f.debug_tuple("RyieldAsyncgen").field(p).finish(), RyieldAsyncnull(p) => f.debug_tuple("RieldAsyncnull").field(p).finish(), RyieldSend(p) => f.debug_tuple("RyieldSend").field(p).finish(), RlostInfo(p) => f.debug_tuple("RlostInfo").field(p).finish(), Rformat(p) => f.debug_tuple("Rformat").field(p).finish(), RclassClass(p) => f.debug_tuple("RclassClass").field(p).finish(), RunknownClass(p) => f.debug_tuple("RunknownClass").field(p).finish(), RvarParam(p) => f.debug_tuple("RvarParam").field(p).finish(), RvarParamFromDecl(p) => f.debug_tuple("RvarParamFromDecl").field(p).finish(), RunpackParam(p) => f.debug_tuple("RunpackParam").field(p).finish(), RinoutParam(p) => f.debug_tuple("RinoutParam").field(p).finish(), Rinstantiate(p) => f.debug_tuple("Rinstantiate").field(p).finish(), Rtypeconst(p) => f.debug_tuple("Rtypeconst").field(p).finish(), RtypeAccess(p) => f.debug_tuple("RtypeAccess").field(p).finish(), RexprDepType(p) => f.debug_tuple("RexprDepType").field(p).finish(), RnullsafeOp(p) => f.debug_tuple("RnullsafeOp").field(p).finish(), RtconstNoCstr(p) => f.debug_tuple("RtconstNoCstr").field(p).finish(), Rpredicated(p) => f.debug_tuple("Rpredicated").field(p).finish(), Ris(p) => f.debug_tuple("Ris").field(p).finish(), Ras(p) => f.debug_tuple("Ras").field(p).finish(), Requal(p) => f.debug_tuple("Requal").field(p).finish(), RvarrayOrDarrayKey(p) => f.debug_tuple("RvarrayOrDarrayKey").field(p).finish(), RvecOrDictKey(p) => f.debug_tuple("RvecOrDictKey").field(p).finish(), Rusing(p) => f.debug_tuple("Rusing").field(p).finish(), RdynamicProp(p) => f.debug_tuple("RdynamicProp").field(p).finish(), RdynamicCall(p) => f.debug_tuple("RdynamicCall").field(p).finish(), RdynamicConstruct(p) => f.debug_tuple("RdynamicConstruct").field(p).finish(), RidxDict(p) => f.debug_tuple("RidxDict").field(p).finish(), RsetElement(p) => f.debug_tuple("RsetElement").field(p).finish(), RmissingOptionalField(p) => f.debug_tuple("RmissingOptionalField").field(p).finish(), RunsetField(p) => f.debug_tuple("RunsetField").field(p).finish(), RcontravariantGeneric(p) => f.debug_tuple("RcontravariantGeneric").field(p).finish(), RinvariantGeneric(p) => f.debug_tuple("RinvariantGeneric").field(p).finish(), Rregex(p) => f.debug_tuple("Rregex").field(p).finish(), RimplicitUpperBound(p) => f.debug_tuple("RimplicitUpperBound").field(p).finish(), RtypeVariable(p) => f.debug_tuple("RtypeVariable").field(p).finish(), RtypeVariableGenerics(p) => f.debug_tuple("RtypeVariableGenerics").field(p).finish(), RtypeVariableError(p) => f.debug_tuple("RtypeVariableError").field(p).finish(), RglobalTypeVariableGenerics(p) => f .debug_tuple("RglobalTypeVariableGenerics") .field(p) .finish(), RsolveFail(p) => f.debug_tuple("RsolveFail").field(p).finish(), RcstrOnGenerics(p) => f.debug_tuple("RcstrOnGenerics").field(p).finish(), RlambdaParam(p) => f.debug_tuple("RlambdaParam").field(p).finish(), Rshape(p) => f.debug_tuple("Rshape").field(p).finish(), RshapeLiteral(p) => f.debug_tuple("RshapeLiteral").field(p).finish(), Renforceable(p) => f.debug_tuple("Renforceable").field(p).finish(), Rdestructure(p) => f.debug_tuple("Rdestructure").field(p).finish(), RkeyValueCollectionKey(p) => f.debug_tuple("RkeyValueCollectionKey").field(p).finish(), RglobalClassProp(p) => f.debug_tuple("RglobalClassProp").field(p).finish(), RglobalFunParam(p) => f.debug_tuple("RglobalFunParam").field(p).finish(), RglobalFunRet(p) => f.debug_tuple("RglobalFunRet").field(p).finish(), Rsplice(p) => f.debug_tuple("Rsplice").field(p).finish(), RetBoolean(p) => f.debug_tuple("RetBoolean").field(p).finish(), RdefaultCapability(p) => f.debug_tuple("RdefaultCapability").field(p).finish(), RconcatOperand(p) => f.debug_tuple("RconcatOperand").field(p).finish(), RinterpOperand(p) => f.debug_tuple("RinterpOperand").field(p).finish(), RdynamicCoercion(p) => f.debug_tuple("RdynamicCoercion").field(p).finish(), RsupportDynamicType(p) => f.debug_tuple("RsupportDynamicType").field(p).finish(), RdynamicPartialEnforcement((p, s, t)) => f .debug_tuple("RdynamicPartialEnforcement") .field(p) .field(s) .field(t) .finish(), RrigidTvarEscape((p, s1, s2, t)) => f .debug_tuple("RigidTvarEscape") .field(p) .field(s1) .field(s2) .field(t) .finish(), RopaqueTypeFromModule((p, s, t)) => f .debug_tuple("RopaqueTypeFromModule") .field(p) .field(s) .field(t) .finish(), RmissingClass(p) => f.debug_tuple("RmissingClass").field(p).finish(), Rinvalid => f.debug_tuple("Rinvalid").finish(), } } }
Rust
hhvm/hphp/hack/src/oxidized_by_ref/manual/t_shape_map.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::cmp::Ordering; use eq_modulo_pos::EqModuloPos; use no_pos_hash::NoPosHash; use ocamlrep::FromOcamlRepIn; use ocamlrep::ToOcamlRep; use serde::Deserialize; use serde::Serialize; use crate::typing_defs_core::PosByteString; use crate::typing_defs_core::PosString; use crate::typing_defs_core::TshapeFieldName; #[derive( Copy, Clone, Debug, Deserialize, FromOcamlRepIn, Hash, EqModuloPos, NoPosHash, Serialize, ToOcamlRep )] pub struct TShapeField<'a>( #[serde(deserialize_with = "arena_deserializer::arena", borrow)] pub TshapeFieldName<'a>, ); arena_deserializer::impl_deserialize_in_arena!(TShapeField<'arena>); impl arena_trait::TrivialDrop for TShapeField<'_> {} impl<'a> Ord for TShapeField<'a> { fn cmp(&self, other: &Self) -> Ordering { use TshapeFieldName::*; match (&self.0, &other.0) { (TSFlitInt(PosString(_, s1)), TSFlitInt(PosString(_, s2))) => s1.cmp(s2), (TSFlitStr(PosByteString(_, s1)), TSFlitStr(PosByteString(_, s2))) => s1.cmp(s2), ( TSFclassConst(((_, c1), PosString(_, m1))), TSFclassConst(((_, c2), PosString(_, m2))), ) => (c1, m1).cmp(&(c2, m2)), (TSFlitInt(_), _) => Ordering::Less, (TSFlitStr(_), TSFlitInt(_)) => Ordering::Greater, (TSFlitStr(_), _) => Ordering::Less, (TSFclassConst(_), _) => Ordering::Greater, } } } impl<'a> PartialOrd for TShapeField<'a> { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl<'a> PartialEq for TShapeField<'a> { fn eq(&self, other: &Self) -> bool { self.cmp(other) == Ordering::Equal } } impl<'a> Eq for TShapeField<'a> {} pub type TShapeMap<'a, T> = arena_collections::SortedAssocList<'a, TShapeField<'a>, T>;
Rust
hhvm/hphp/hack/src/package/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::collections::VecDeque; use hash::HashSet; use serde::Deserialize; use toml::Spanned; use crate::error::Error; use crate::types::DeploymentMap; use crate::types::NameSet; use crate::types::PackageMap; #[derive(Debug, Deserialize)] pub struct Config { pub packages: PackageMap, pub deployments: Option<DeploymentMap>, } impl Config { pub fn check_config(&self) -> Vec<Error> { let check_packages_are_defined = |errors: &mut Vec<Error>, pkgs: &Option<NameSet>, soft_pkgs: &Option<NameSet>| { if let Some(packages) = pkgs { packages.iter().for_each(|package| { if !self.packages.contains_key(package) { errors.push(Error::undefined_package(package)) } }) } if let Some(packages) = soft_pkgs { packages.iter().for_each(|package| { if !self.packages.contains_key(package) { errors.push(Error::undefined_package(package)) } }) } }; let mut used_globs = NameSet::default(); let mut check_each_glob_is_used_once = |errors: &mut Vec<Error>, globs: &Option<NameSet>| { if let Some(l) = globs { l.iter().for_each(|glob| { if used_globs.contains(glob) { errors.push(Error::duplicate_use(glob)) } used_globs.insert(glob.clone()); }) } }; let check_deployed_packages_are_transitively_closed = |errors: &mut Vec<Error>, deployment: &Spanned<String>, pkgs: &Option<NameSet>, soft_pkgs: &Option<NameSet>| { let deployed = pkgs.as_ref().unwrap_or_default(); let soft_deployed = soft_pkgs.as_ref().unwrap_or_default(); let (missing_pkgs, missing_soft_pkgs) = find_missing_packages_from_deployment(&self.packages, deployed, soft_deployed); if !missing_pkgs.is_empty() { errors.push(Error::incomplete_deployment( deployment, missing_pkgs, false, )); } if !missing_soft_pkgs.is_empty() { errors.push(Error::incomplete_deployment( deployment, missing_soft_pkgs, true, )); } }; let mut errors = vec![]; for (_, package) in self.packages.iter() { check_packages_are_defined(&mut errors, &package.includes, &package.soft_includes); check_each_glob_is_used_once(&mut errors, &package.uses); } if let Some(deployments) = &self.deployments { for (positioned_name, deployment) in deployments.iter() { check_packages_are_defined( &mut errors, &deployment.packages, &deployment.soft_packages, ); check_deployed_packages_are_transitively_closed( &mut errors, positioned_name, &deployment.packages, &deployment.soft_packages, ); } }; errors } } // The function takes a starting set of package names and a PackageMap, and // returns two HashSets: one with packages included by the starting set (transitive closure), // and the other with packages soft-included by the starting set (transitive closure) but not included. pub fn analyze_includes<'a>( starting_set: &'a NameSet, package_map: &'a PackageMap, ) -> (HashSet<&'a Spanned<String>>, HashSet<&'a Spanned<String>>) { // Sets to store packages that are included and soft-included, respectively let mut included = HashSet::default(); let mut soft_included = HashSet::default(); // Queue of package names and whether the package is soft included let mut queue = VecDeque::new(); // Add the starting set of package names to the queue, with 'is_soft' flag set to false for package_name in starting_set.iter() { queue.push_back((package_name, false)); } while let Some((current_package_name, is_soft)) = queue.pop_front() { if let Some(package) = package_map.get(current_package_name) { // If the package is not soft-included, add it to the 'included' set if !is_soft { included.insert(current_package_name); } else if !included.contains(current_package_name) { // If the package is soft-included and not in the 'included' set, add it to the 'soft_included' set soft_included.insert(current_package_name); } if let Some(ref includes) = package.includes { for include in includes.iter() { if !included.contains(include) { queue.push_back((include, false)); } } } if let Some(ref soft_includes) = package.soft_includes { for soft_include in soft_includes.iter() { if !included.contains(soft_include) && !soft_included.contains(soft_include) { queue.push_back((soft_include, true)); } } } } } (included, soft_included) } fn find_missing_packages_from_deployment( package_map: &PackageMap, deployed: &NameSet, soft_deployed: &NameSet, ) -> (Vec<Spanned<String>>, Vec<Spanned<String>>) { // Taking the transitive closure of all nested included packages so that the user // could complete the deployment set upon the first error message they receive, as // opposed to iterating upon it over multiple checks and going through a full init // every time they update the config. // TODO: simplify after incremental mode (T148526825) let (included, soft_included) = analyze_includes(deployed, package_map); let soft_or_regular_deployed = deployed.union(soft_deployed).cloned().collect(); fn get_missing<'a>( included: &HashSet<&'a Spanned<String>>, deployed: &NameSet, package_map: &PackageMap, ) -> Vec<Spanned<String>> { let mut missing_pkgs = included .iter() .filter_map(|pkg| { let pkg_name = pkg.get_ref().as_str(); if !deployed.contains(pkg_name) { let (positioned_pkg_name, _) = package_map.get_key_value(pkg_name).unwrap(); Some(positioned_pkg_name.clone()) } else { None } }) .collect::<Vec<_>>(); missing_pkgs.sort(); missing_pkgs } ( get_missing(&included, deployed, package_map), get_missing(&soft_included, &soft_or_regular_deployed, package_map), ) }
hhvm/hphp/hack/src/package/dune
; FFI OCaml to Rust (../../target/*/libpackage_ocaml_ffi.a) ; contains "external" function definition in .ml and ; the symbol is provided by the ocaml-rs Rust package via caml! macro (data_only_dirs cargo package_ocaml_ffi) (library (name package_ocaml_ffi) (modules) (wrapped false) (foreign_archives package_ocaml_ffi)) (rule (targets libpackage_ocaml_ffi.a) (deps (source_tree %{workspace_root}/hack/src)) (locks /cargo) (action (run %{workspace_root}/hack/scripts/invoke_cargo.sh package_ocaml_ffi package_ocaml_ffi))) (library (name package_info) (wrapped false) (modules package packageInfo) (libraries pos) (preprocess (pps ppx_deriving.std))) (library (name package_config) (wrapped false) (modules packageConfig) (libraries errors parsing_error package_info package_ocaml_ffi pos_or_decl) (preprocess (pps ppx_deriving.std)))
Rust
hhvm/hphp/hack/src/package/error.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 std::ops::Range; use toml::Spanned; #[derive(Debug, PartialEq)] pub enum Error { UndefinedInclude { name: String, span: (usize, usize), }, DuplicateUse { name: String, span: (usize, usize), }, IncompleteDeployment { name: String, span: (usize, usize), missing_pkgs: Vec<Spanned<String>>, soft: bool, }, } impl Error { pub fn undefined_package(x: &Spanned<String>) -> Self { let Range { start, end } = x.span(); Self::UndefinedInclude { name: x.get_ref().into(), span: (start, end), } } pub fn duplicate_use(x: &Spanned<String>) -> Self { let Range { start, end } = x.span(); Self::DuplicateUse { name: x.get_ref().into(), span: (start, end), } } pub fn incomplete_deployment( deployment: &Spanned<String>, missing_pkgs: Vec<Spanned<String>>, soft: bool, ) -> Self { let Range { start, end } = deployment.span(); Self::IncompleteDeployment { name: deployment.get_ref().into(), span: (start, end), missing_pkgs, soft, } } pub fn span(&self) -> (usize, usize) { match self { Self::DuplicateUse { span, .. } | Self::UndefinedInclude { span, .. } | Self::IncompleteDeployment { span, .. } => *span, } } pub fn msg(&self) -> String { format!("{}", self) } pub fn reasons(&self) -> Vec<(usize, usize, String)> { // Might need reasons later for more complicated error messages vec![] } } impl Display for Error { fn fmt(&self, f: &mut Formatter<'_>) -> Result { match self { Self::UndefinedInclude { name, .. } => { write!(f, "Undefined package: {}", name)?; } Self::DuplicateUse { name, .. } => { write!(f, "This module can only be used in one package: {}", name)?; } Self::IncompleteDeployment { name, missing_pkgs, soft, .. } => { let soft_str = if *soft { "soft-" } else { "" }; write!( f, "{} must {}deploy all nested {}included packages. Missing ", name, soft_str, soft_str )?; for (i, pkg) in missing_pkgs.iter().enumerate() { if i == missing_pkgs.len() - 1 { write!(f, "{}", pkg.get_ref())?; } else { write!(f, "{}, ", pkg.get_ref())?; } } } }; Ok(()) } }
OCaml
hhvm/hphp/hack/src/package/package.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. * *) (* * 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 pos_id = Pos.t * string [@@deriving eq, show] type t = { name: pos_id; uses: pos_id list; includes: pos_id list; soft_includes: pos_id list; } [@@deriving eq, show] type package_relationship = | Unrelated | Includes | Soft_includes | Equal let get_package_pos pkg = fst pkg.name let get_package_name pkg = snd pkg.name let includes pkg1 pkg2 = List.exists ~f:(fun (_, name) -> String.equal name @@ get_package_name pkg2) pkg1.includes let soft_includes pkg1 pkg2 = List.exists ~f:(fun (_, name) -> String.equal name @@ get_package_name pkg2) pkg1.soft_includes let relationship pkg1 pkg2 = if equal pkg1 pkg2 then Equal else if includes pkg1 pkg2 then Includes else if soft_includes pkg1 pkg2 then Soft_includes else Unrelated
OCaml Interface
hhvm/hphp/hack/src/package/package.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 pos_id = Pos.t * string [@@deriving eq, show] type t = { name: pos_id; uses: pos_id list; includes: pos_id list; soft_includes: pos_id list; } [@@deriving eq, show] (* Represents how two packages are related *) type package_relationship = | Unrelated | Includes | Soft_includes | Equal val get_package_name : t -> string val get_package_pos : t -> Pos.t val relationship : t -> t -> package_relationship
Rust
hhvm/hphp/hack/src/package/package.rs
// Copyright (c) Meta, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. mod config; mod error; mod package_info; pub use package_info::*; mod types;
OCaml
hhvm/hphp/hack/src/package/packageConfig.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 errors = (Pos.t * string * (Pos.t * string) list) list external extract_packages_from_text : string -> string -> (Package.t list, errors) result = "extract_packages_from_text_ffi" let pkgs_config_path_relative_to_repo_root = "PACKAGES.toml" let repo_config_path = Relative_path.from_root ~suffix:pkgs_config_path_relative_to_repo_root let log_debug (msg : ('a, unit, string, string, string, unit) format6) : 'a = Hh_logger.debug ~category:"packages" ?exn:None msg let parse (path : string) = let contents = Sys_utils.cat path in match extract_packages_from_text path contents with | Error errors -> let error_list = List.map errors ~f:(fun (pos, msg, reasons) -> let reasons = List.map ~f:(fun (p, s) -> (Pos_or_decl.of_raw_pos p, s)) reasons in Parsing_error.( to_user_error @@ Package_config_error { pos; msg; reasons })) in (Errors.from_error_list error_list, PackageInfo.empty) | Ok packages -> (Errors.empty, PackageInfo.from_packages packages) let load_and_parse ?(pkgs_config_abs_path = None) () : Errors.t * PackageInfo.t = let pkgs_config_abs_path = match pkgs_config_abs_path with | None -> Relative_path.to_absolute repo_config_path | Some path -> path in if not @@ Sys.file_exists pkgs_config_abs_path then (Errors.empty, PackageInfo.empty) else let result = parse pkgs_config_abs_path in log_debug "Parsed %s" pkgs_config_abs_path; result
OCaml Interface
hhvm/hphp/hack/src/package/packageConfig.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 : ?pkgs_config_abs_path:string option -> unit -> Errors.t * PackageInfo.t val repo_config_path : Relative_path.t
OCaml
hhvm/hphp/hack/src/package/packageInfo.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 t = { glob_to_package: Package.t SMap.t; existing_packages: Package.t SMap.t; } [@@deriving eq, show] let empty = { glob_to_package = SMap.empty; existing_packages = SMap.empty } let module_name_matches_pattern module_name pattern = if String.length pattern = 0 then false else if String.equal pattern "*" then true else let size = String.length pattern in (* If `pattern` is a prefix glob, check that its prefix matches `module_name`'s prefix. *) if String.is_suffix ~suffix:".*" pattern then if String.length module_name <= size - 1 then false else let prefix = String.sub pattern ~pos:0 ~len:(size - 1) in String.is_prefix ~prefix module_name else (* If `pattern` is a direct module name, check for an exact match. *) String.equal module_name pattern let get_package_for_module (info : t) (md : string) : Package.t option = let candidates = SMap.filter (fun glob _ -> module_name_matches_pattern md glob) info.glob_to_package in let (_strictest_matching_glob, package_with_strictest_matching_glob) = SMap.fold (fun glob pkg ((glob', _) as acc) -> if String.compare glob glob' > 0 then (glob, Some pkg) else acc) candidates ("", None) in package_with_strictest_matching_glob let package_exists (info : t) (pkg : string) : bool = SMap.mem pkg info.existing_packages let get_package (info : t) (pkg : string) : Package.t option = SMap.find_opt pkg info.existing_packages let from_packages (packages : Package.t list) : t = List.fold packages ~init:empty ~f:(fun acc pkg -> let pkg_name = Package.get_package_name pkg in let existing_packages = SMap.add pkg_name pkg acc.existing_packages in let acc = { acc with existing_packages } in List.fold pkg.Package.uses ~init:acc ~f:(fun acc (_, glob) -> let glob_to_package = SMap.add glob pkg acc.glob_to_package in let acc = { acc with glob_to_package } in acc))
OCaml Interface
hhvm/hphp/hack/src/package/packageInfo.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 t [@@deriving show, eq] val empty : t val from_packages : Package.t list -> t val get_package_for_module : t -> string -> Package.t option val get_package : t -> string -> Package.t option val package_exists : t -> string -> bool
Rust
hhvm/hphp/hack/src/package/package_info.rs
// Copyright (c) Meta, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use anyhow::Context; use anyhow::Result; use crate::config::*; use crate::error::*; use crate::types::DeploymentMap; pub use crate::types::NameSet; use crate::types::PackageMap; #[derive(Debug)] pub struct PackageInfo { packages: PackageMap, deployments: Option<DeploymentMap>, line_offsets: Vec<usize>, errors: Vec<Error>, } impl PackageInfo { pub fn from_text(contents: &str) -> Result<PackageInfo> { let config: Config = toml::from_str(contents) .with_context(|| format!("Failed to parse config file with contents: {}", contents))?; let line_offsets = contents .char_indices() .filter(|&(_i, c)| c == '\n') .map(|(i, _)| i) .collect::<Vec<_>>(); let errors = config.check_config(); Ok(Self { packages: config.packages, deployments: config.deployments, line_offsets, errors, }) } pub fn packages(&self) -> &PackageMap { &self.packages } pub fn deployments(&self) -> Option<&DeploymentMap> { self.deployments.as_ref() } pub fn errors(&self) -> &[Error] { &self.errors[..] } pub fn line_number(&self, byte_offset: usize) -> usize { match self.line_offsets.binary_search(&byte_offset) { Ok(n) | Err(n) => n + 1, } } pub fn beginning_of_line(&self, line_number: usize) -> usize { if line_number == 1 { 1 } else { let line_idx = line_number - 1; let prev_line_idx = line_idx - 1; let prev_line_end = self.line_offsets[prev_line_idx]; prev_line_end + 1 } } } #[cfg(test)] mod test { use super::*; #[test] fn test_parsing_basic_file() { let contents = include_str!("tests/package-1.toml"); let info = PackageInfo::from_text(contents).unwrap(); assert!(info.errors.is_empty()); let foo = &info.packages()["foo"]; assert_eq!(foo.uses.as_ref().unwrap()[0].get_ref(), "a.*"); assert!(foo.includes.is_none()); assert_eq!( info.line_number(foo.uses.as_ref().unwrap()[0].span().start), 4 ); let bar = &info.packages()["bar"]; assert_eq!(bar.uses.as_ref().unwrap()[0].get_ref(), "b.*"); assert_eq!(bar.includes.as_ref().unwrap()[0].get_ref(), "foo"); let baz = &info.packages()["baz"]; assert_eq!(baz.uses.as_ref().unwrap()[0].get_ref(), "x.*"); assert_eq!(baz.uses.as_ref().unwrap()[1].get_ref(), "y.*"); assert_eq!(baz.includes.as_ref().unwrap()[0].get_ref(), "foo"); assert_eq!(baz.includes.as_ref().unwrap()[1].get_ref(), "bar"); assert_eq!( info.line_number(baz.uses.as_ref().unwrap()[0].span().start), 11 ); assert_eq!( info.line_number(baz.uses.as_ref().unwrap()[1].span().start), 11 ); let my_prod = &info.deployments().unwrap()["my-prod"]; assert_eq!(my_prod.packages.as_ref().unwrap()[0].get_ref(), "foo"); assert_eq!(my_prod.packages.as_ref().unwrap()[1].get_ref(), "bar"); assert_eq!( my_prod.domains.as_ref().unwrap()[0].get_ref(), r"www\.my-prod\.com" ); assert_eq!( my_prod.domains.as_ref().unwrap()[1].get_ref(), r".*\.website\.com$" ); } #[test] fn test_multiline_uses() { let contents = include_str!("tests/package-2.toml"); let info = PackageInfo::from_text(contents).unwrap(); assert!(info.errors.is_empty()); let foo = &info.packages()["foo"]; let foo_uses = &foo.uses.as_ref().unwrap(); assert_eq!(foo_uses[0].get_ref(), "a.*"); assert_eq!(foo_uses[1].get_ref(), "b.*"); assert_eq!(info.line_number(foo_uses[0].span().start), 7); assert_eq!(info.line_number(foo_uses[1].span().start), 9); let foo_includes = &foo.includes.as_ref().unwrap(); assert_eq!(foo_includes[0].get_ref(), "bar"); assert_eq!(info.line_number(foo_includes[0].span().start), 12); } #[test] fn test_config_errors1() { let contents = include_str!("tests/package-3.toml"); let info = PackageInfo::from_text(contents).unwrap(); assert_eq!(info.errors.len(), 3); assert_eq!(info.errors[0].msg(), "Undefined package: baz"); assert_eq!(info.errors[1].msg(), "Undefined package: baz"); assert_eq!( info.errors[2].msg(), "This module can only be used in one package: b.*" ); } #[test] fn test_config_errors2() { let contents = include_str!("tests/package-4.toml"); let info = PackageInfo::from_text(contents).unwrap(); let errors = info .errors .iter() .map(|e| e.msg()) .collect::<std::collections::HashSet<_>>(); assert_eq!( errors, [String::from( "my-prod must deploy all nested included packages. Missing e, g, h, i" )] .iter() .cloned() .collect::<std::collections::HashSet<_>>() ); } #[test] fn test_soft() { let contents = include_str!("tests/package-5.toml"); let info = PackageInfo::from_text(contents).unwrap(); let c = &info.packages()["c"]; let errors = info .errors .iter() .map(|e| e.msg()) .collect::<std::collections::HashSet<_>>(); assert_eq!( errors, [ String::from("f must soft-deploy all nested soft-included packages. Missing b"), String::from("g must deploy all nested included packages. Missing c") ] .iter() .cloned() .collect::<std::collections::HashSet<_>>() ); assert_eq!(c.soft_includes.as_ref().unwrap()[0].get_ref(), "b"); let d = &info.deployments().unwrap()["d"]; assert_eq!(d.packages.as_ref().unwrap()[0].get_ref(), "c"); assert_eq!(d.soft_packages.as_ref().unwrap()[0].get_ref(), "b"); } }
Rust
hhvm/hphp/hack/src/package/types.rs
// Copyright (c) Meta, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::ops::Deref; use std::ops::DerefMut; use hash::IndexMap; use hash::IndexSet; use once_cell::sync::Lazy; use serde::Deserialize; use toml::Spanned; // Preserve the order for ease of testing // Alternatively, we could use HashMap for performance pub type PackageMap = IndexMap<Spanned<String>, Package>; pub type DeploymentMap = IndexMap<Spanned<String>, Deployment>; #[derive(Debug, Default, Deserialize)] pub struct NameSet(IndexSet<Spanned<String>>); #[derive(Debug, Deserialize)] pub struct Package { pub uses: Option<NameSet>, pub includes: Option<NameSet>, pub soft_includes: Option<NameSet>, } #[derive(Debug, Deserialize)] pub struct Deployment { pub packages: Option<NameSet>, pub soft_packages: Option<NameSet>, pub domains: Option<NameSet>, } impl<'a> Default for &'a NameSet { fn default() -> &'a NameSet { static SET: Lazy<NameSet> = Lazy::new(|| NameSet(IndexSet::default())); &SET } } impl Deref for NameSet { type Target = IndexSet<Spanned<String>>; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for NameSet { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl FromIterator<Spanned<String>> for NameSet { fn from_iter<I>(iter: I) -> Self where I: IntoIterator<Item = Spanned<String>>, { let mut set = IndexSet::default(); for name in iter { set.insert(name); } NameSet(set) } } impl Iterator for NameSet { type Item = Spanned<String>; fn next(&mut self) -> Option<Self::Item> { self.0.iter().next().cloned() } }
TOML
hhvm/hphp/hack/src/package/cargo/Cargo.toml
# @generated by autocargo [package] name = "package" version = "0.0.0" edition = "2021" [lib] path = "../package.rs" [dependencies] anyhow = "1.0.71" hash = { version = "0.0.0", path = "../../utils/hash" } once_cell = "1.12" serde = { version = "1.0.176", features = ["derive", "rc"] } toml = "0.7.3"
TOML
hhvm/hphp/hack/src/package/ffi_bridge/Cargo.toml
# @generated by autocargo [package] name = "package_ffi" version = "0.0.0" edition = "2021" [lib] path = "package_ffi.rs" test = false doctest = false crate-type = ["lib", "staticlib"] [dependencies] cxx = "1.0.100" package = { version = "0.0.0", path = "../cargo" } [build-dependencies] cxx-build = "1.0.100"
Rust
hhvm/hphp/hack/src/package/ffi_bridge/package_ffi.rs
/** * Copyright (c) Meta, 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. An additional * directory. * */ use cxx::CxxString; #[cxx::bridge(namespace = "HPHP::package")] mod ffi { struct PackageInfo { packages: Vec<PackageMapEntry>, deployments: Vec<DeploymentMapEntry>, } struct PackageMapEntry { name: String, package: Package, } struct Package { uses: Vec<String>, includes: Vec<String>, soft_includes: Vec<String>, } struct DeploymentMapEntry { name: String, deployment: Deployment, } struct Deployment { packages: Vec<String>, soft_packages: Vec<String>, domains: Vec<String>, } extern "Rust" { pub fn package_info(source_text: &CxxString) -> PackageInfo; } } pub fn package_info(source_text: &CxxString) -> ffi::PackageInfo { let s = package::PackageInfo::from_text(&source_text.to_string()); match s { Ok(info) => { let convert = |v: Option<&package::NameSet>| { v.map(|v| v.iter().map(|v| v.get_ref().clone()).collect()) .unwrap_or_default() }; let packages = info .packages() .iter() .map(|(name, package)| { let package_ffi = ffi::Package { uses: convert(package.uses.as_ref()), includes: convert(package.includes.as_ref()), soft_includes: convert(package.soft_includes.as_ref()), }; ffi::PackageMapEntry { name: name.get_ref().to_string(), package: package_ffi, } }) .collect(); let deployments = info .deployments() .map(|deployments_unwrapped| { deployments_unwrapped .iter() .map(|(name, deployment)| { let deployment_ffi = ffi::Deployment { packages: convert(deployment.packages.as_ref()), soft_packages: convert(deployment.soft_packages.as_ref()), domains: convert(deployment.domains.as_ref()), }; ffi::DeploymentMapEntry { name: name.get_ref().into(), deployment: deployment_ffi, } }) .collect() }) .unwrap_or_default(); ffi::PackageInfo { packages, deployments, } } Err(_e) => ffi::PackageInfo { packages: vec![], deployments: vec![], }, } }
Rust
hhvm/hphp/hack/src/package/ocaml_ffi/package_ocaml_ffi.rs
// Copyright (c) Meta Platforms, Inc. and affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::ops::Range; use std::path::PathBuf; use std::sync::Arc; use ocamlrep::ptr::UnsafeOcamlPtr; use ocamlrep::ToOcamlRep; use ocamlrep_ocamlpool::ocaml_ffi; use ocamlrep_ocamlpool::to_ocaml; use rc_pos::Pos; use relative_path::Prefix; use relative_path::RelativePath; use toml::Spanned; type PosId = (Pos, String); type Errors = Vec<(Pos, String, Vec<(Pos, String)>)>; #[derive(ToOcamlRep)] struct Package { name: PosId, uses: Vec<PosId>, includes: Vec<PosId>, soft_includes: Vec<PosId>, } ocaml_ffi! { fn extract_packages_from_text_ffi( filename: String, source_text: String, ) -> Result<UnsafeOcamlPtr, Errors> { let s = package::PackageInfo::from_text(&source_text); match s { Ok(info) => { let pos_from_span = |span: (usize, usize)| { let (start_offset, end_offset) = span; let start_lnum = info.line_number(start_offset); let start_bol = info.beginning_of_line(start_lnum); let end_lnum = info.line_number(end_offset); let end_bol = info.beginning_of_line(end_lnum); Pos::from_lnum_bol_offset( Arc::new(RelativePath::make( Prefix::Dummy, PathBuf::from(filename.clone()), )), (start_lnum, start_bol, start_offset), (end_lnum, end_bol, end_offset), ) }; let errors = info .errors() .iter() .map(|e| { let pos = pos_from_span(e.span()); let msg = e.msg(); let reasons = e .reasons() .into_iter() .map(|(start, end, reason)| (pos_from_span((start, end)), reason)) .collect(); (pos, msg, reasons) }) .collect::<Errors>(); if !errors.is_empty() { return Err(errors); }; let packages: Vec<Package> = info .packages() .iter() .map(|(name, package)| { let convert = |x: &Spanned<String>| -> PosId { let Range { start, end } = x.span(); let pos = pos_from_span((start, end)); let id = x.to_owned().into_inner(); (pos, id) }; let convert_many = |xs: &Option<package::NameSet>| -> Vec<PosId> { xs.as_ref() .unwrap_or_default() .iter() .map(convert) .collect() }; Package { name: convert(name), uses: convert_many(&package.uses), includes: convert_many(&package.includes), soft_includes: convert_many(&package.soft_includes), } }) .collect(); Ok(unsafe { UnsafeOcamlPtr::new(to_ocaml(packages.as_slice())) }) }, Err(_e) => { // TODO(T148525961): Send a proper error when packages.toml fails to parse Err(vec![]) } } } }
TOML
hhvm/hphp/hack/src/package/ocaml_ffi/cargo/Cargo.toml
# @generated by autocargo [package] name = "package_ocaml_ffi" version = "0.0.0" edition = "2021" [lib] path = "../package_ocaml_ffi.rs" test = false doctest = false crate-type = ["lib", "staticlib"] [dependencies] ocamlrep = { version = "0.1.0", git = "https://github.com/facebook/ocamlrep/", branch = "main" } ocamlrep_ocamlpool = { version = "0.1.0", git = "https://github.com/facebook/ocamlrep/", branch = "main" } package = { version = "0.0.0", path = "../../cargo" } rc_pos = { version = "0.0.0", path = "../../../utils/rust/pos" } relative_path = { version = "0.0.0", path = "../../../utils/rust/relative_path" } toml = "0.7.3"
TOML
hhvm/hphp/hack/src/package/tests/package-1.toml
[packages] [packages.foo] uses = ["a.*"] [packages.bar] uses = ["b.*"] includes = ["foo"] [packages.baz] uses = ["x.*", "y.*"] includes = ["foo", "bar"] [deployments] [deployments.my-prod] packages = ["foo", "bar"] domains = ['www\.my-prod\.com', '.*\.website\.com$']
TOML
hhvm/hphp/hack/src/package/tests/package-2.toml
[packages] [packages.bar] [packages.foo] uses = [ "a.*", # some comment "b.*" ] includes = [ "bar" ]
TOML
hhvm/hphp/hack/src/package/tests/package-3.toml
[packages] [packages.foo] includes = ["baz"] soft_includes=["baz"] uses = ["b.*"] [packages.bar] uses = ["b.*"]
TOML
hhvm/hphp/hack/src/package/tests/package-4.toml
[packages] [packages.a] includes = ["b"] [packages.b] includes = ["c", "d"] [packages.c] includes = ["a", "e"] [packages.d] includes = ["e"] [packages.e] includes = ["f", "g"] [packages.f] includes = ["e"] [packages.g] includes = ["e"] [packages.h] includes = ["j"] [packages.i] includes = ["h"] [packages.j] includes = ["i"] [deployments] [deployments.my-prod] packages = ["d", "f", "j"]
TOML
hhvm/hphp/hack/src/package/tests/package-5.toml
[packages] [packages.a] uses = ["a.*"] includes = ["b"] [packages.b] uses = ["b.*"] includes = ["c"] [packages.c] uses = [".*"] includes = [] soft_includes=["b"] [deployments.d] # no error packages=["c"] soft_packages=["b"] [deployments.e] # no error packages=["c", "b"] [deployments.f] # error, b needs to be soft included since c requires it packages=["c"] [deployments.g] # error, c needs to be hard included packages=["b"] soft_packages=["c"]
Rust
hhvm/hphp/hack/src/parser/aast_check.rs
// Copyright (c) 2019, Facebook, Inc. // All rights reserved. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use naming_special_names_rust::coeffects; use naming_special_names_rust::special_idents; use oxidized::aast; use oxidized::aast_visitor::visit; use oxidized::aast_visitor::AstParams; use oxidized::aast_visitor::Node; use oxidized::aast_visitor::Visitor; use oxidized::ast; use oxidized::ast_defs; use oxidized::pos::Pos; use parser_core_types::syntax_error; use parser_core_types::syntax_error::Error as ErrorMsg; use parser_core_types::syntax_error::SyntaxError; use parser_core_types::syntax_error::SyntaxQuickfix; /// Does this hint look like `Awaitable<Foo>` or `<<__Soft>> Awaitable<Foo>`? /// /// If it does, return the type arguments present. fn awaitable_type_args(hint: &ast::Hint) -> Option<&[ast::Hint]> { use oxidized::aast_defs::Hint_::*; match &*hint.1 { // Since `Awaitable` is an autoloaded class, we look for its // literal name. Defining a class named `Awaitable` in the // current namespace does not affect us. Happly(ast::Id(_, s), args) if s == "\\HH\\Awaitable" || s == "HH\\Awaitable" || s == "Awaitable" => { Some(args) } Hsoft(h) => awaitable_type_args(h), _ => None, } } fn is_any_local(ctxs: Option<&ast::Contexts>) -> bool { match ctxs { Some(c) => { for hint in &c.1 { if let aast::Hint_::Happly(ast_defs::Id(_, id), _) = &*hint.1 { if id.as_str() == coeffects::ZONED_LOCAL || id.as_str() == coeffects::LEAK_SAFE_LOCAL || id.as_str() == coeffects::RX_LOCAL { return true; } } } false } None => false, } } struct Context { in_methodish: bool, in_classish: bool, in_static_methodish: bool, is_any_local_fun: bool, is_typechecker: bool, } struct Checker { errors: Vec<SyntaxError>, } impl Checker { fn new() -> Self { Self { errors: vec![] } } fn add_error(&mut self, pos: &Pos, msg: ErrorMsg) { let (start_offset, end_offset) = pos.info_raw(); self.errors .push(SyntaxError::make(start_offset, end_offset, msg, vec![])); } fn add_error_with_quickfix( &mut self, start_offset: usize, end_offset: usize, msg: ErrorMsg, quickfix_title: &str, edits: Vec<(usize, usize, String)>, ) { let quickfixes = vec![SyntaxQuickfix { title: quickfix_title.into(), edits, }]; self.errors .push(SyntaxError::make(start_offset, end_offset, msg, quickfixes)); } fn name_eq_this_and_in_static_method(c: &Context, name: impl AsRef<str>) -> bool { c.in_classish && c.in_static_methodish && name.as_ref().eq_ignore_ascii_case(special_idents::THIS) } fn check_async_ret_hint<Hi>(&mut self, h: &aast::TypeHint<Hi>) { match &h.1 { Some(hint) => match awaitable_type_args(hint) { Some(typeargs) => { if typeargs.len() > 1 { self.add_error(&hint.0, syntax_error::invalid_awaitable_arity) } } None => { let (start_offset, end_offset) = hint.0.info_raw(); let edits = vec![ (start_offset, start_offset, "Awaitable<".into()), (end_offset, end_offset, ">".into()), ]; self.add_error_with_quickfix( start_offset, end_offset, syntax_error::invalid_async_return_hint, "Make return type Awaitable", edits, ); } }, None => {} } } } impl<'ast> Visitor<'ast> for Checker { type Params = AstParams<Context, ()>; fn object(&mut self) -> &mut dyn Visitor<'ast, Params = Self::Params> { self } fn visit_class_(&mut self, c: &mut Context, p: &aast::Class_<(), ()>) -> Result<(), ()> { p.recurse( &mut Context { in_classish: true, ..*c }, self, ) } fn visit_method_(&mut self, c: &mut Context, m: &aast::Method_<(), ()>) -> Result<(), ()> { if m.fun_kind == ast::FunKind::FAsync { self.check_async_ret_hint(&m.ret); } m.recurse( &mut Context { in_methodish: true, in_static_methodish: m.static_, is_any_local_fun: is_any_local(m.ctxs.as_ref()), ..*c }, self, ) } fn visit_fun_(&mut self, c: &mut Context, f: &aast::Fun_<(), ()>) -> Result<(), ()> { if f.fun_kind == ast::FunKind::FAsync { self.check_async_ret_hint(&f.ret); } f.recurse( &mut Context { in_methodish: true, in_static_methodish: c.in_static_methodish, is_any_local_fun: is_any_local(f.ctxs.as_ref()), ..*c }, self, ) } fn visit_stmt(&mut self, c: &mut Context, p: &aast::Stmt<(), ()>) -> Result<(), ()> { if let aast::Stmt_::Awaitall(_) = p.1 { if !c.in_methodish { self.add_error(&p.0, syntax_error::toplevel_await_use); } } p.recurse(c, self) } fn visit_expr(&mut self, c: &mut Context, p: &aast::Expr<(), ()>) -> Result<(), ()> { use aast::CallExpr; use aast::ClassId; use aast::ClassId_::*; use aast::Expr; use aast::Expr_::*; use aast::Lid; if let Await(_) = p.2 { if !c.in_methodish { self.add_error(&p.1, syntax_error::toplevel_await_use); } } else if let Some(CallExpr { func: Expr(_, _, f), args, .. }) = p.2.as_call() { if let Some((ClassId(_, _, CIexpr(Expr(_, pos, Id(id)))), ..)) = f.as_class_const() { if Self::name_eq_this_and_in_static_method(c, &id.1) { self.add_error(pos, syntax_error::this_in_static); } } else if let Some(ast::Id(_, fun_name)) = f.as_id() { if (fun_name == "\\HH\\meth_caller" || fun_name == "HH\\meth_caller" || fun_name == "meth_caller") && args.len() == 2 { if let (_, Expr(_, pos, String(classname))) = &args[0] { if classname.contains(&b'$') { self.add_error(pos, syntax_error::dollar_sign_in_meth_caller_argument); } } if let (_, Expr(_, pos, String(method_name))) = &args[1] { if method_name.contains(&b'$') { self.add_error(pos, syntax_error::dollar_sign_in_meth_caller_argument); } } } } } else if let Some(Lid(pos, (_, name))) = p.2.as_lvar() { if Self::name_eq_this_and_in_static_method(c, name) { self.add_error(pos, syntax_error::this_in_static); } } else if let Some(efun) = p.2.as_efun() { match efun.fun.ctxs { None if c.is_any_local_fun && c.is_typechecker => { self.add_error(&efun.fun.span, syntax_error::closure_in_local_context) } _ => {} } } else if let Some((f, ..)) = p.2.as_lfun() { match f.ctxs { None if c.is_any_local_fun && c.is_typechecker => { self.add_error(&f.span, syntax_error::closure_in_local_context) } _ => {} } } p.recurse(c, self) } } pub fn check_program( program: &aast::Program<(), ()>, is_typechecker: bool, for_debugger_eval: bool, ) -> Vec<SyntaxError> { let mut checker = Checker::new(); let mut context = Context { // If we are checking for debugger repl, we should assume that we are // inside a method in_methodish: for_debugger_eval, in_classish: false, in_static_methodish: false, is_any_local_fun: false, is_typechecker, }; visit(&mut checker, &mut context, program).unwrap(); checker.errors }
Rust
hhvm/hphp/hack/src/parser/aast_parser.rs
// Copyright (c) 2019, Facebook, Inc. // All rights reserved. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::sync::Arc; use std::time::Instant; use bumpalo::Bump; use hash::HashSet; use lowerer::lower; use lowerer::ScourComment; use mode_parser::parse_mode; use mode_parser::Language; use namespaces_rust as namespaces; use ocamlrep::FromOcamlRep; use ocamlrep::ToOcamlRep; use oxidized::aast::Program; use oxidized::file_info::Mode; use oxidized::namespace_env::Env as NamespaceEnv; use oxidized::pos::Pos; use oxidized::scoured_comments::ScouredComments; use parser_core_types::indexed_source_text::IndexedSourceText; use parser_core_types::parser_env::ParserEnv; use parser_core_types::source_text::SourceText; use parser_core_types::syntax_by_ref::positioned_syntax::PositionedSyntax; use parser_core_types::syntax_by_ref::positioned_token::PositionedToken; use parser_core_types::syntax_by_ref::positioned_token::TokenFactory; use parser_core_types::syntax_by_ref::positioned_value::PositionedValue; use parser_core_types::syntax_error::SyntaxError; use parser_core_types::syntax_tree::SyntaxTree; pub use rust_aast_parser_types::Env; pub use rust_aast_parser_types::ParserProfile; pub use rust_aast_parser_types::ParserResult; use rust_parser_errors::parse_errors_with_text; use smart_constructors::NoState; use crate::aast_check; use crate::coeffects_check; use crate::expression_tree_check; use crate::modules_check; use crate::readonly_check; type PositionedSyntaxTree<'src, 'arena> = SyntaxTree<'src, PositionedSyntax<'arena>, NoState>; #[derive(Debug, FromOcamlRep, ToOcamlRep)] pub enum Error { NotAHackFile(), ParserFatal(SyntaxError, Pos), Other(String), } impl<T: ToString> From<T> for Error { fn from(s: T) -> Self { Error::Other(s.to_string()) } } pub type Result<T, E = Error> = std::result::Result<T, E>; pub struct AastParser; impl<'src> AastParser { pub fn from_text( env: &Env, indexed_source_text: &'src IndexedSourceText<'src>, default_unstable_features: HashSet<rust_parser_errors::UnstableFeatures>, ) -> Result<ParserResult> { let ns = NamespaceEnv::empty( env.parser_options.po_auto_namespace_map.clone(), env.codegen, env.parser_options.po_disable_xhp_element_mangling, ); Self::from_text_with_namespace_env( env, Arc::new(ns), indexed_source_text, default_unstable_features, ) } pub fn from_text_with_namespace_env( env: &Env, ns: Arc<NamespaceEnv>, indexed_source_text: &'src IndexedSourceText<'src>, default_unstable_features: HashSet<rust_parser_errors::UnstableFeatures>, ) -> Result<ParserResult> { let start_t = Instant::now(); let arena = Bump::new(); stack_limit::reset(); let (language, mode, tree) = Self::parse_text(&arena, env, indexed_source_text)?; let parsing_t = start_t.elapsed(); let parse_peak = stack_limit::peak(); let mut pr = Self::from_tree_with_namespace_env( env, ns, indexed_source_text, &arena, language, mode, tree, default_unstable_features, )?; pr.profile.parse_peak = parse_peak as u64; pr.profile.parsing_t = parsing_t; pr.profile.total_t = start_t.elapsed(); Ok(pr) } pub fn from_tree<'arena>( env: &Env, indexed_source_text: &'src IndexedSourceText<'src>, arena: &'arena Bump, language: Language, mode: Option<Mode>, tree: PositionedSyntaxTree<'src, 'arena>, default_unstable_features: HashSet<rust_parser_errors::UnstableFeatures>, ) -> Result<ParserResult> { let ns = NamespaceEnv::empty( env.parser_options.po_auto_namespace_map.clone(), env.codegen, env.parser_options.po_disable_xhp_element_mangling, ); Self::from_tree_with_namespace_env( env, Arc::new(ns), indexed_source_text, arena, language, mode, tree, default_unstable_features, ) } fn from_tree_with_namespace_env<'arena>( env: &Env, ns: Arc<NamespaceEnv>, indexed_source_text: &'src IndexedSourceText<'src>, arena: &'arena Bump, language: Language, mode: Option<Mode>, tree: PositionedSyntaxTree<'src, 'arena>, default_unstable_features: HashSet<rust_parser_errors::UnstableFeatures>, ) -> Result<ParserResult> { let lowering_t = Instant::now(); match language { Language::Hack => {} _ => return Err(Error::NotAHackFile()), } let mode = mode.unwrap_or(Mode::Mstrict); let scoured_comments = Self::scour_comments_and_add_fixmes(env, indexed_source_text, tree.root())?; let mut lowerer_env = lowerer::Env::make( env.codegen, env.quick_mode, env.show_all_errors, mode, indexed_source_text, &env.parser_options, Arc::clone(&ns), TokenFactory::new(arena), arena, ); stack_limit::reset(); let ret = lower(&mut lowerer_env, tree.root()); let (lowering_t, elaboration_t) = (lowering_t.elapsed(), Instant::now()); let lower_peak = stack_limit::peak() as u64; let mut ret = if env.elaborate_namespaces { namespaces::toplevel_elaborator::elaborate_toplevel_defs(ns, ret) } else { ret }; let (elaboration_t, error_t) = (elaboration_t.elapsed(), Instant::now()); stack_limit::reset(); let syntax_errors = Self::check_syntax_error( env, indexed_source_text, &tree, Some(&mut ret), default_unstable_features, ); let error_peak = stack_limit::peak() as u64; let lowerer_parsing_errors = lowerer_env.parsing_errors().to_vec(); let errors = lowerer_env.hh_errors().to_vec(); let lint_errors = lowerer_env.lint_errors().to_vec(); let error_t = error_t.elapsed(); Ok(ParserResult { file_mode: mode, scoured_comments, aast: ret, lowerer_parsing_errors, syntax_errors, errors, lint_errors, profile: ParserProfile { lower_peak, lowering_t, elaboration_t, error_t, error_peak, arena_bytes: arena.allocated_bytes() as u64, ..Default::default() }, }) } fn check_syntax_error<'arena>( env: &Env, indexed_source_text: &'src IndexedSourceText<'src>, tree: &PositionedSyntaxTree<'src, 'arena>, aast: Option<&mut Program<(), ()>>, default_unstable_features: HashSet<rust_parser_errors::UnstableFeatures>, ) -> Vec<SyntaxError> { let find_errors = |hhi_mode: bool| -> Vec<SyntaxError> { let mut errors = tree.errors().into_iter().cloned().collect::<Vec<_>>(); let (parse_errors, uses_readonly) = parse_errors_with_text( tree, indexed_source_text.clone(), // TODO(hrust) change to parser_otions to ref in ParserErrors env.parser_options.clone(), true, /* hhvm_compat_mode */ hhi_mode, env.codegen, env.is_systemlib, default_unstable_features, ); errors.extend(parse_errors); errors.sort_by(SyntaxError::compare_offset); let mut empty_program = Program(vec![]); let aast = aast.unwrap_or(&mut empty_program); if uses_readonly && !env.parser_options.tco_no_parser_readonly_check { errors.extend(readonly_check::check_program(aast, !env.codegen)); } errors.extend(aast_check::check_program( aast, !env.codegen, env.for_debugger_eval, )); errors.extend(modules_check::check_program(aast)); errors.extend(expression_tree_check::check_splices(aast)); errors.extend(coeffects_check::check_program(aast, !env.codegen)); errors }; if env.codegen { find_errors(false /* hhi_mode */) } else { let first_error = tree.errors().into_iter().next(); match first_error { None if !env.quick_mode && !env.parser_options.po_parser_errors_only => { let is_hhi = indexed_source_text .source_text() .file_path() .has_extension("hhi"); find_errors(is_hhi) } None => vec![], Some(e) => vec![e.clone()], } } } fn parse_text<'arena>( arena: &'arena Bump, env: &Env, indexed_source_text: &'src IndexedSourceText<'src>, ) -> Result<(Language, Option<Mode>, PositionedSyntaxTree<'src, 'arena>)> { let source_text = indexed_source_text.source_text(); let (language, mode, parser_env) = Self::make_parser_env(env, source_text); let tree = Self::parse(arena, env, parser_env, source_text, mode)?; Ok((language, mode, tree)) } pub fn make_parser_env( env: &Env, source_text: &'src SourceText<'src>, ) -> (Language, Option<Mode>, ParserEnv) { let (language, mode) = parse_mode(source_text); let parser_env = ParserEnv { codegen: env.codegen, hhvm_compat_mode: env.codegen, php5_compat_mode: env.php5_compat_mode, allow_new_attribute_syntax: env.parser_options.po_allow_new_attribute_syntax, enable_xhp_class_modifier: env.parser_options.po_enable_xhp_class_modifier, disable_xhp_element_mangling: env.parser_options.po_disable_xhp_element_mangling, disable_xhp_children_declarations: env .parser_options .po_disable_xhp_children_declarations, interpret_soft_types_as_like_types: env .parser_options .po_interpret_soft_types_as_like_types, }; (language, mode.map(Into::into), parser_env) } fn parse<'arena>( arena: &'arena Bump, env: &Env, parser_env: ParserEnv, source_text: &'src SourceText<'src>, mode: Option<Mode>, ) -> Result<PositionedSyntaxTree<'src, 'arena>> { let quick_mode = match mode { None | Some(Mode::Mhhi) => !env.codegen, _ => !env.codegen && env.quick_mode, }; let tree = if quick_mode { let (tree, errors, _state) = decl_mode_parser::parse_script(arena, source_text, parser_env); PositionedSyntaxTree::create(source_text, tree, errors, mode.map(Into::into), NoState) } else { let (tree, errors, _state) = positioned_by_ref_parser::parse_script(arena, source_text, parser_env); PositionedSyntaxTree::create(source_text, tree, errors, mode.map(Into::into), NoState) }; Ok(tree) } fn scour_comments_and_add_fixmes<'arena>( env: &Env, indexed_source_text: &'src IndexedSourceText<'_>, script: &PositionedSyntax<'arena>, ) -> Result<ScouredComments> { if env.scour_comments { let scourer: ScourComment<'_, PositionedToken<'arena>, PositionedValue<'arena>> = ScourComment { phantom: std::marker::PhantomData, indexed_source_text, include_line_comments: env.include_line_comments, disable_hh_ignore_error: env.parser_options.po_disable_hh_ignore_error, allowed_decl_fixme_codes: &env.parser_options.po_allowed_decl_fixme_codes, }; Ok(scourer.scour_comments(script)) } else { Ok(ScouredComments { comments: Default::default(), fixmes: Default::default(), misuses: Default::default(), error_pos: Default::default(), bad_ignore_pos: Default::default(), }) } } }
Rust
hhvm/hphp/hack/src/parser/aast_parser_ffi.rs
// Copyright (c) 2019, Facebook, Inc. // All rights reserved. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::collections::HashSet; use aast_parser::rust_aast_parser_types::Env; use aast_parser::AastParser; use ocamlrep::FromOcamlRep; use ocamlrep_ocamlpool::to_ocaml; use parser_core_types::indexed_source_text::IndexedSourceText; use parser_core_types::source_text::SourceText; #[no_mangle] extern "C" fn from_text(env: usize, source_text: usize) -> usize { // XXX why this catch_unwind ocamlrep_ocamlpool::catch_unwind(|| { let env = unsafe { Env::from_ocaml(env).unwrap() }; let source_text = match unsafe { SourceText::from_ocaml(source_text) } { Ok(source_text) => source_text, Err(e) => panic!("SourceText::from_ocaml failed: {:#?}", e), }; let indexed_source_text = IndexedSourceText::new(source_text); let res = AastParser::from_text(&env, &indexed_source_text, HashSet::default()); // Safety: Requires no concurrent interaction with OCaml // runtime from other threads. unsafe { to_ocaml(&res) } }) }
Rust
hhvm/hphp/hack/src/parser/aast_parser_lib.rs
// Copyright (c) 2019, Facebook, Inc. // All rights reserved. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. mod aast_check; mod aast_parser; mod coeffects_check; mod expression_tree_check; mod modules_check; mod readonly_check; pub use aast_parser::AastParser; pub use aast_parser::Error; pub use aast_parser::ParserResult; pub use aast_parser::Result; pub use rust_aast_parser_types; pub use rust_aast_parser_types::ParserProfile;
Rust
hhvm/hphp/hack/src/parser/ast_and_decl_parser.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::collections::HashSet; use aast_parser::AastParser; pub use aast_parser::Result; use bumpalo::Bump; use oxidized::decl_parser_options::DeclParserOptions; use oxidized_by_ref::direct_decl_parser::ParsedFile; use parser_core_types::indexed_source_text::IndexedSourceText; pub use rust_aast_parser_types::Env; pub use rust_aast_parser_types::ParserResult; pub fn from_text<'a>( env: &'a Env, indexed_source_text: &'a IndexedSourceText<'a>, arena: &'a Bump, ) -> (Result<ParserResult>, ParsedFile<'a>) { let source = indexed_source_text.source_text(); let (language, mode, parser_env) = AastParser::make_parser_env(env, source); let opts = DeclParserOptions::from_parser_options(&env.parser_options); let (cst, decls) = cst_and_decl_parser::parse_script(&opts, parser_env, source, mode, arena); let ast_result = AastParser::from_tree( env, indexed_source_text, arena, language, mode, cst, HashSet::default(), ); (ast_result, decls) }
OCaml
hhvm/hphp/hack/src/parser/ast_and_decl_service.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 process_parse_result ctx ?(ide = false) ~quick ~trace ~cache_decls ~start_time (acc, errorl, error_files) fn (errorl', (ast, decls)) popt = let start_parse_time = start_time in let start_process_time = Unix.gettimeofday () in let { Parser_return.file_mode; comments = _; ast; content } = ast in (* This surely is a bug?? We're now degistering php_stdlib from the AST, but the decls we got (and which we're now about to cache) have not been deregistered. The two will be inconsistent! *) let ast = if Relative_path.(is_hhi (Relative_path.prefix fn)) && ParserOptions.deregister_php_stdlib popt then Nast.deregister_ignored_attributes ast else ast in let bytes = String.length content in let content = if ide then File_provider.Ide content else File_provider.Disk content in if Option.is_some file_mode then ( (* If this file was parsed from a tmp directory, save it to the main directory instead *) let fn = match Relative_path.prefix fn with | Relative_path.Tmp -> Relative_path.to_root fn | _ -> fn in if quick then File_provider.provide_file_hint fn content; let mode = if quick then Ast_provider.Decl else Ast_provider.Full in Ast_provider.provide_ast_hint fn ast mode; if cache_decls then Direct_decl_utils.cache_decls ctx fn decls.Direct_decl_utils.pfh_decls; let defs = Direct_decl_parser.decls_to_fileinfo fn decls in let acc = Relative_path.Map.add acc ~key:fn ~data:defs in let errorl = Errors.merge errorl' errorl in let error_files = if Errors.is_empty errorl' then error_files else Relative_path.Set.add error_files fn in if trace then Hh_logger.log "[%dk, %.0f+%.0fms] %s - %s" (bytes / 1024) ((start_process_time -. start_parse_time) *. 1000.0) ((Unix.gettimeofday () -. start_process_time) *. 1000.0) (Relative_path.suffix fn) (FileInfo.to_string defs); (acc, errorl, error_files) ) else ( File_provider.provide_file_hint fn content; (* we also now keep in the file_info regular php files * as we need at least their names in hack build *) let acc = Relative_path.Map.add acc ~key:fn ~data:FileInfo.empty_t in (acc, errorl, error_files) ) let parse ctx ~quick ~show_all_errors ~trace ~cache_decls popt acc fn = if not @@ FindUtils.path_filter fn then acc else let start_time = Unix.gettimeofday () in let res = Errors.do_with_context fn @@ fun () -> Full_fidelity_ast.ast_and_decls_from_file ~quick ~show_all_errors popt fn in process_parse_result ctx ~quick ~start_time ~trace ~cache_decls acc fn res popt let merge_parse (acc1, status1, files1) (acc2, status2, files2) = ( Relative_path.Map.union acc1 acc2, Errors.merge status1 status2, Relative_path.Set.union files1 files2 ) let go (ctx : Provider_context.t) ?(quick = false) ?(show_all_errors = false) (workers : MultiWorker.worker list option) ~(get_next : Relative_path.t list MultiWorker.Hh_bucket.next) (popt : ParserOptions.t) ~(trace : bool) ~(cache_decls : bool) ~(worker_call : MultiWorker.call_wrapper) : FileInfo.t Relative_path.Map.t * Errors.t * Relative_path.Set.t = worker_call.MultiWorker.f workers ~job:(fun init -> List.fold_left ~init ~f:(parse ctx ~quick ~show_all_errors ~trace ~cache_decls popt)) ~neutral:(Relative_path.Map.empty, Errors.empty, Relative_path.Set.empty) ~merge:merge_parse ~next:get_next
OCaml Interface
hhvm/hphp/hack/src/parser/ast_and_decl_service.mli
(* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) val go : Provider_context.t -> ?quick:bool -> ?show_all_errors:bool -> MultiWorker.worker list option -> get_next:Relative_path.t list Bucket.next -> ParserOptions.t -> trace:bool -> cache_decls:bool -> worker_call:MultiWorker.call_wrapper -> FileInfo.t Relative_path.Map.t * Errors.t * Relative_path.Set.t
Rust
hhvm/hphp/hack/src/parser/coeffects_check.rs
// Copyright (c) 2019, Facebook, Inc. // All rights reserved. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use bitflags::bitflags; use core_utils_rust as utils; use naming_special_names_rust::coeffects; use naming_special_names_rust::coeffects::Ctx; use naming_special_names_rust::members; use naming_special_names_rust::special_idents; use naming_special_names_rust::user_attributes; use oxidized::aast; use oxidized::aast::Binop; use oxidized::aast::Hint_; use oxidized::aast_defs; use oxidized::aast_defs::Hint; use oxidized::aast_visitor::visit; use oxidized::aast_visitor::AstParams; use oxidized::aast_visitor::Node; use oxidized::aast_visitor::Visitor; use oxidized::ast; use oxidized::ast_defs; use oxidized::local_id; use oxidized::pos::Pos; use parser_core_types::syntax_error; use parser_core_types::syntax_error::Error as ErrorMsg; use parser_core_types::syntax_error::SyntaxError; fn hints_contain_capability(hints: &[aast_defs::Hint], capability: Ctx) -> bool { for hint in hints { if let aast::Hint_::Happly(ast_defs::Id(_, id), _) = &*hint.1 { let (_, name) = utils::split_ns_from_name(id); let c = coeffects::ctx_str_to_enum(name); match c { Some(val) => { if coeffects::capability_matches_name(&capability, &val) { return true; } } None => continue, } } } false } fn has_capability(ctxs: Option<&ast::Contexts>, capability: Ctx) -> bool { match ctxs { Some(c) => hints_contain_capability(&c.1, capability), // No capabilities context is the same as defaults in scenarios where contexts are not inherited None => match capability { Ctx::WriteProps | Ctx::WriteThisProps | Ctx::ReadGlobals | Ctx::Globals => true, _ => false, }, } } fn is_mutating_unop(unop: &ast_defs::Uop) -> bool { use ast_defs::Uop::*; match unop { Upincr | Uincr | Updecr | Udecr => true, _ => false, } } // This distinguishes between contexts which explicitly do not have write_props and unspecified contexts which may implicitly lack write_props. // The latter is important because for e.g. a lambda without contexts, it should inherit context from its enclosing function. fn has_capability_with_inherited_val( c: &Context, ctxs: Option<&ast::Contexts>, capability: Ctx, ) -> bool { match ctxs { Some(_) => has_capability(ctxs, capability), None => match capability { Ctx::WriteProps => c.has_write_props(), Ctx::WriteThisProps => c.has_write_this_props(), Ctx::ReadGlobals => c.has_read_globals(), Ctx::Globals => c.has_access_globals(), _ => false, }, } } fn has_defaults_with_inherited_val(c: &Context, ctxs: Option<&ast::Contexts>) -> bool { match ctxs { Some(_) => has_defaults(ctxs), None => c.has_defaults(), } } fn has_defaults_implicitly(hints: &[Hint]) -> bool { for hint in hints { let Hint(_, h) = hint; match &**h { Hint_::Happly(ast_defs::Id(_, id), _) => { let (_, name) = utils::split_ns_from_name(id); match coeffects::ctx_str_to_enum(name) { Some(c) => match c { Ctx::Defaults => { return true; } _ => { continue; } }, None => { return true; } } } aast::Hint_::HfunContext(_) => { continue; } aast::Hint_::Haccess(Hint(_, hint), sids) => match &**hint { Hint_::Happly(ast_defs::Id(..), _) if !sids.is_empty() => { continue; } Hint_::Hvar(_) if sids.len() == 1 => { continue; } _ => { return true; } }, _ => { return true; } } } false } fn has_defaults(ctxs: Option<&ast::Contexts>) -> bool { match ctxs { None => true, Some(c) => { if c.1.is_empty() { false } else { has_defaults_implicitly(&c.1) } } } } fn is_constructor_or_clone(s: &ast_defs::Id) -> bool { let ast_defs::Id(_, name) = s; name == members::__CONSTRUCT || name == members::__CLONE } fn has_ignore_coeffect_local_errors_attr(attrs: &[aast::UserAttribute<(), ()>]) -> bool { for attr in attrs.iter() { let ast_defs::Id(_, name) = &attr.name; if user_attributes::ignore_coeffect_local_errors(name) { return true; } } false } bitflags! { pub struct ContextFlags: u16 { /// Hack, very roughly, has three contexts in which you can see an /// expression: /// - Expression Trees /// - Initializer positions /// - Everything else /// There are other rules that handle expr trees and initializer /// positions, so we really care about all the other contexts. This is /// mostly inside function bodies, but also includes the right-hand-side /// of an enum class initializer, which can contain function calls and /// other complex expressions. const IN_COMPLEX_EXPRESSION_CONTEXT = 1 << 0; const IS_TYPECHECKER = 1 << 1; const IS_CONSTRUCTOR_OR_CLONE = 1 << 2; const IGNORE_COEFFECT_LOCAL_ERRORS = 1 << 3; const HAS_DEFAULTS = 1 << 4; const HAS_WRITE_PROPS = 1 << 5; const HAS_WRITE_THIS_PROPS = 1 << 6; const HAS_READ_GLOBALS = 1 << 7; const HAS_ACCESS_GLOBALS = 1 << 8; } } struct Context { bitflags: ContextFlags, } impl Context { fn new() -> Self { Self { bitflags: ContextFlags::from_bits_truncate(0_u16), } } fn from_context(&self) -> Self { let mut c = Context::new(); c.set_in_complex_expression_context(self.in_complex_expression_context()); c.set_is_constructor_or_clone(self.is_constructor_or_clone()); c.set_ignore_coeffect_local_errors(self.ignore_coeffect_local_errors()); c.set_is_typechecker(self.is_typechecker()); c.set_has_defaults(self.has_defaults()); c.set_has_write_props(self.has_write_props()); c.set_has_write_this_props(self.has_write_this_props()); c } fn in_complex_expression_context(&self) -> bool { self.bitflags .contains(ContextFlags::IN_COMPLEX_EXPRESSION_CONTEXT) } fn is_constructor_or_clone(&self) -> bool { self.bitflags .contains(ContextFlags::IS_CONSTRUCTOR_OR_CLONE) } fn ignore_coeffect_local_errors(&self) -> bool { self.bitflags .contains(ContextFlags::IGNORE_COEFFECT_LOCAL_ERRORS) } fn has_defaults(&self) -> bool { self.bitflags.contains(ContextFlags::HAS_DEFAULTS) } fn is_typechecker(&self) -> bool { self.bitflags.contains(ContextFlags::IS_TYPECHECKER) } fn has_write_props(&self) -> bool { self.bitflags.contains(ContextFlags::HAS_WRITE_PROPS) } fn has_write_this_props(&self) -> bool { self.bitflags.contains(ContextFlags::HAS_WRITE_THIS_PROPS) } fn has_read_globals(&self) -> bool { self.bitflags.contains(ContextFlags::HAS_READ_GLOBALS) } fn has_access_globals(&self) -> bool { self.bitflags.contains(ContextFlags::HAS_ACCESS_GLOBALS) } fn set_in_complex_expression_context(&mut self, in_complex_expression_context: bool) { self.bitflags.set( ContextFlags::IN_COMPLEX_EXPRESSION_CONTEXT, in_complex_expression_context, ); } fn set_is_constructor_or_clone(&mut self, is_constructor_or_clone: bool) { self.bitflags.set( ContextFlags::IS_CONSTRUCTOR_OR_CLONE, is_constructor_or_clone, ); } fn set_ignore_coeffect_local_errors(&mut self, ignore_coeffect_local_errors: bool) { self.bitflags.set( ContextFlags::IGNORE_COEFFECT_LOCAL_ERRORS, ignore_coeffect_local_errors, ); } fn set_has_defaults(&mut self, has_defaults: bool) { self.bitflags.set(ContextFlags::HAS_DEFAULTS, has_defaults); } fn set_is_typechecker(&mut self, is_typechecker: bool) { self.bitflags .set(ContextFlags::IS_TYPECHECKER, is_typechecker); } fn set_has_write_props(&mut self, has_write_props: bool) { self.bitflags .set(ContextFlags::HAS_WRITE_PROPS, has_write_props); } fn set_has_write_this_props(&mut self, has_write_this_props: bool) { self.bitflags .set(ContextFlags::HAS_WRITE_THIS_PROPS, has_write_this_props); } fn set_has_read_globals(&mut self, has_read_globals: bool) { self.bitflags .set(ContextFlags::HAS_READ_GLOBALS, has_read_globals); } fn set_has_access_globals(&mut self, has_access_globals: bool) { self.bitflags .set(ContextFlags::HAS_ACCESS_GLOBALS, has_access_globals); } } struct Checker { errors: Vec<SyntaxError>, } impl Checker { fn new() -> Self { Self { errors: vec![] } } fn add_error(&mut self, pos: &Pos, msg: ErrorMsg) { let (start_offset, end_offset) = pos.info_raw(); self.errors .push(SyntaxError::make(start_offset, end_offset, msg, vec![])); } fn do_write_props_check(&mut self, e: &aast::Expr<(), ()>) { if let Some(Binop { bop: ast_defs::Bop::Eq(_), lhs, .. }) = e.2.as_binop() { self.check_is_obj_property_write_expr(e, lhs, true /* ignore_this_writes */); } if let Some((unop, expr)) = e.2.as_unop() { if is_mutating_unop(unop) { self.check_is_obj_property_write_expr(e, expr, true /* ignore_this_writes */); } } } fn do_write_this_props_check(&mut self, c: &mut Context, e: &aast::Expr<(), ()>) { if c.is_constructor_or_clone() { return; } if let Some(aast::Binop { bop: ast_defs::Bop::Eq(_), lhs, .. }) = e.2.as_binop() { self.check_is_obj_property_write_expr(e, lhs, false /* ignore_this_writes */); } if let Some((unop, expr)) = e.2.as_unop() { if is_mutating_unop(unop) { self.check_is_obj_property_write_expr(e, expr, false /* ignore_this_writes */); } } } fn check_is_obj_property_write_expr( &mut self, top_level_expr: &aast::Expr<(), ()>, expr: &aast::Expr<(), ()>, ignore_this_writes: bool, ) { if let Some((lhs, ..)) = expr.2.as_obj_get() { if let Some(v) = lhs.2.as_lvar() { if local_id::get_name(&v.1) == special_idents::THIS { if ignore_this_writes { return; } else { self.add_error( &top_level_expr.1, syntax_error::write_props_without_capability, ); } } } self.add_error( &top_level_expr.1, syntax_error::write_props_without_capability, ); } else if let Some((arr, _)) = expr.2.as_array_get() { self.check_is_obj_property_write_expr(top_level_expr, arr, ignore_this_writes); } } } impl<'ast> Visitor<'ast> for Checker { type Params = AstParams<Context, ()>; fn object(&mut self) -> &mut dyn Visitor<'ast, Params = Self::Params> { self } fn visit_class_(&mut self, c: &mut Context, cls: &aast::Class_<(), ()>) -> Result<(), ()> { let mut new_context = Context::from_context(c); if cls.enum_.is_some() { // If we're in an enum class, we need to ensure that the following // is illegal: // // enum class Foo: _ { // _ BAR = Baz::$bing; // } // new_context.set_in_complex_expression_context(true); } cls.recurse(&mut new_context, self) } fn visit_method_(&mut self, c: &mut Context, m: &aast::Method_<(), ()>) -> Result<(), ()> { let mut new_context = Context::from_context(c); new_context.set_in_complex_expression_context(true); new_context.set_is_constructor_or_clone(is_constructor_or_clone(&m.name)); new_context.set_ignore_coeffect_local_errors(has_ignore_coeffect_local_errors_attr( &m.user_attributes, )); let ctxs = m.ctxs.as_ref(); new_context.set_has_defaults(has_defaults(ctxs)); new_context.set_has_write_props(has_capability(ctxs, Ctx::WriteProps)); new_context.set_has_write_this_props(has_capability(ctxs, Ctx::WriteThisProps)); new_context.set_has_read_globals(has_capability(ctxs, Ctx::ReadGlobals)); new_context.set_has_access_globals(has_capability(ctxs, Ctx::Globals)); m.recurse(&mut new_context, self) } fn visit_fun_def(&mut self, c: &mut Context, d: &aast::FunDef<(), ()>) -> Result<(), ()> { let mut new_context = Context::from_context(c); let ctxs = d.fun.ctxs.as_ref(); new_context.set_has_defaults(has_defaults(ctxs)); new_context.set_is_constructor_or_clone(is_constructor_or_clone(&d.name)); new_context.set_has_write_props(has_capability(ctxs, Ctx::WriteProps)); new_context.set_has_write_this_props(has_capability(ctxs, Ctx::WriteThisProps)); new_context.set_has_read_globals(has_capability(ctxs, Ctx::ReadGlobals)); new_context.set_has_access_globals(has_capability(ctxs, Ctx::Globals)); d.recurse(&mut new_context, self) } fn visit_fun_(&mut self, c: &mut Context, f: &aast::Fun_<(), ()>) -> Result<(), ()> { let mut new_context = Context::from_context(c); new_context.set_in_complex_expression_context(true); new_context.set_ignore_coeffect_local_errors(has_ignore_coeffect_local_errors_attr( &f.user_attributes, )); let ctxs = f.ctxs.as_ref(); new_context.set_has_defaults(has_defaults_with_inherited_val(c, ctxs)); new_context.set_has_write_props(has_capability_with_inherited_val( c, ctxs, Ctx::WriteProps, )); new_context.set_has_write_this_props(has_capability_with_inherited_val( c, ctxs, Ctx::WriteThisProps, )); new_context.set_has_read_globals(has_capability_with_inherited_val( c, ctxs, Ctx::ReadGlobals, )); new_context.set_has_access_globals(has_capability_with_inherited_val( c, ctxs, Ctx::Globals, )); f.recurse(&mut new_context, self) } fn visit_expr(&mut self, c: &mut Context, p: &aast::Expr<(), ()>) -> Result<(), ()> { if c.in_complex_expression_context() && !c.ignore_coeffect_local_errors() && !c.has_defaults() { if !c.has_write_props() { self.do_write_props_check(p); if !c.has_write_this_props() { self.do_write_this_props_check(c, p); } } if !c.has_access_globals() { // Do access globals check e.g. C::$x = 5; if let Some(Binop { bop: ast_defs::Bop::Eq(_), lhs, rhs, }) = p.2.as_binop() { if let Some((_, _, ast_defs::PropOrMethod::IsProp)) = lhs.2.as_class_get() { self.add_error(&lhs.1, syntax_error::access_globals_without_capability); // Skipping one level of recursion when read_globals are present // ensures the left hand side global is not subject to read_global // enforcement, thus duplicating the error message. if c.has_read_globals() { return rhs.recurse(c, self); } } } // Skipping one level of recursion for a readonly expression when // read_globals are present ensures globals enclosed in read_globals // are not subject to enforcement. if let Some(e) = p.2.as_readonly_expr() { if c.has_read_globals() { // Do not subject the readonly static itself to read_globals check, // only its potential children return e.recurse(c, self); } } if let Some((_, _, ast_defs::PropOrMethod::IsProp)) = p.2.as_class_get() { if !c.has_read_globals() { self.add_error(&p.1, syntax_error::read_globals_without_capability) } else { self.add_error(&p.1, syntax_error::read_globals_without_readonly) } } } } p.recurse(c, self) } } pub fn check_program(program: &aast::Program<(), ()>, is_typechecker: bool) -> Vec<SyntaxError> { let mut checker = Checker::new(); let mut context = Context::new(); context.set_is_typechecker(is_typechecker); visit(&mut checker, &mut context, program).unwrap(); checker.errors }
Rust
hhvm/hphp/hack/src/parser/compact_token.rs
// Copyright (c) 2019, Facebook, Inc. // All rights reserved. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use crate::compact_trivia::CompactTrivia; use crate::compact_trivia::TriviaKinds; use crate::lexable_token::LexableToken; use crate::source_text::SourceText; use crate::token_factory::SimpleTokenFactory; use crate::token_kind::TokenKind; use crate::trivia_kind::TriviaKind; /// A compact version of parser_core_types::PositionedToken. Most tokens will be /// represented inline in 16 bytes (the same size as a slice). Tokens which do /// not fit in that representation will allocate a Box for their contents. #[derive(Debug, Clone, PartialEq)] pub struct CompactToken { repr: CompactTokenRepr, } #[derive(Debug, Clone, PartialEq)] enum CompactTokenRepr { Small(SmallToken), Large(Box<LargeToken>), } use CompactTokenRepr::*; #[derive(Debug, Clone, PartialEq)] struct SmallToken { kind: TokenKind, offset: u32, // Points to the first byte of the first leading trivium leading_width: u16, width: u16, // Width of actual token, not counting trivia trailing_width: u8, leading: TriviaKinds, trailing: TriviaKinds, } #[derive(Debug, Clone, PartialEq)] struct LargeToken { kind: TokenKind, offset: usize, // Points to the first byte of the first leading trivium leading_width: usize, width: usize, // Width of actual token, not counting trivia trailing_width: usize, leading: TriviaKinds, trailing: TriviaKinds, } impl CompactToken { pub fn new( kind: TokenKind, offset: usize, width: usize, leading: CompactTrivia, trailing: CompactTrivia, ) -> Self { let leading_width = leading.width; let leading = leading.kinds; let trailing_width = trailing.width; let trailing = trailing.kinds; match ( offset.try_into(), leading_width.try_into(), width.try_into(), trailing_width.try_into(), ) { (Ok(o), Ok(lw), Ok(w), Ok(tw)) => Self { repr: Small(SmallToken { kind, offset: o, leading_width: lw, width: w, trailing_width: tw, leading, trailing, }), }, _ => Self { repr: Large(Box::new(LargeToken { kind, offset, leading_width, width, trailing_width, leading, trailing, })), }, } } pub fn kind(&self) -> TokenKind { match &self.repr { &Small(SmallToken { kind, .. }) => kind, Large(token) => token.kind, } } /// Private because of the ambiguous name. This is the offset field on /// SmallToken and LargeToken--the byte offset of the first leading trivium. fn offset(&self) -> usize { match &self.repr { &Small(SmallToken { offset, .. }) => offset as usize, Large(token) => token.offset, } } pub fn width(&self) -> usize { match &self.repr { &Small(SmallToken { width, .. }) => width as usize, Large(token) => token.width, } } pub fn leading_width(&self) -> usize { match &self.repr { &Small(SmallToken { leading_width, .. }) => leading_width as usize, Large(token) => token.leading_width, } } pub fn trailing_width(&self) -> usize { match &self.repr { &Small(SmallToken { trailing_width, .. }) => trailing_width as usize, Large(token) => token.trailing_width, } } pub fn leading_trivia(&self) -> CompactTrivia { match &self.repr { Small(token) => CompactTrivia::make(token.leading, token.leading_width as usize), Large(token) => CompactTrivia::make(token.leading, token.leading_width), } } pub fn trailing_trivia(&self) -> CompactTrivia { match &self.repr { Small(token) => CompactTrivia::make(token.trailing, token.trailing_width as usize), Large(token) => CompactTrivia::make(token.trailing, token.trailing_width), } } pub fn leading_is_empty(&self) -> bool { match &self.repr { Small(token) => token.leading.is_empty(), Large(token) => token.leading.is_empty(), } } pub fn trailing_is_empty(&self) -> bool { match &self.repr { Small(token) => token.trailing.is_empty(), Large(token) => token.trailing.is_empty(), } } pub fn start_offset(&self) -> usize { self.offset() + self.leading_width() } pub fn end_offset(&self) -> usize { self.start_offset() + self.width() } pub fn leading_start_offset(&self) -> usize { self.offset() } pub fn trailing_start_offset(&self) -> usize { self.end_offset() } pub fn leading_text<'a>(&self, source_text: &SourceText<'a>) -> &'a [u8] { source_text.sub(self.leading_start_offset(), self.leading_width()) } pub fn trailing_text<'a>(&self, source_text: &SourceText<'a>) -> &'a [u8] { source_text.sub(self.trailing_start_offset(), self.trailing_width()) } pub fn text<'a>(&self, source_text: &SourceText<'a>) -> &'a [u8] { source_text.sub(self.start_offset(), self.width()) } pub fn has_leading_trivia_kind(&self, kind: TriviaKind) -> bool { match &self.repr { Small(token) => token.leading.has_kind(kind), Large(token) => token.leading.has_kind(kind), } } pub fn has_trailing_trivia_kind(&self, kind: TriviaKind) -> bool { match &self.repr { Small(token) => token.trailing.has_kind(kind), Large(token) => token.trailing.has_kind(kind), } } } impl LexableToken for CompactToken { type Trivia = CompactTrivia; fn kind(&self) -> TokenKind { self.kind() } fn leading_start_offset(&self) -> Option<usize> { Some(self.leading_start_offset()) } fn width(&self) -> usize { self.width() } fn leading_width(&self) -> usize { self.leading_width() } fn trailing_width(&self) -> usize { self.trailing_width() } fn full_width(&self) -> usize { self.leading_width() + self.width() + self.trailing_width() } fn clone_leading(&self) -> CompactTrivia { self.leading_trivia() } fn clone_trailing(&self) -> CompactTrivia { self.trailing_trivia() } fn leading_is_empty(&self) -> bool { self.leading_is_empty() } fn trailing_is_empty(&self) -> bool { self.trailing_is_empty() } fn has_leading_trivia_kind(&self, kind: TriviaKind) -> bool { self.has_leading_trivia_kind(kind) } fn has_trailing_trivia_kind(&self, kind: TriviaKind) -> bool { self.has_trailing_trivia_kind(kind) } fn into_trivia_and_width(self) -> (Self::Trivia, usize, Self::Trivia) { match self.repr { Small(t) => ( CompactTrivia::make(t.leading, t.leading_width as usize), t.width as usize, CompactTrivia::make(t.trailing, t.trailing_width as usize), ), Large(t) => ( CompactTrivia::make(t.leading, t.leading_width), t.width, CompactTrivia::make(t.trailing, t.trailing_width), ), } } } impl SimpleTokenFactory for CompactToken { fn make( kind: TokenKind, offset: usize, width: usize, leading: CompactTrivia, trailing: CompactTrivia, ) -> Self { Self::new(kind, offset, width, leading, trailing) } fn with_leading(mut self, leading: CompactTrivia) -> Self { match &mut self.repr { Large(token) => { let token_start_offset = token.offset + token.leading_width; token.offset = token_start_offset - leading.width; token.leading_width = leading.width; token.leading = leading.kinds; } Small(token) => { let token_start_offset = token.offset as usize + token.leading_width as usize; let new_leading_start_offset = token_start_offset - leading.width; if let (Ok(offset), Ok(leading_width)) = ( new_leading_start_offset.try_into(), leading.width.try_into(), ) { token.offset = offset; token.leading_width = leading_width; token.leading = leading.kinds; } else { return Self { repr: Large(Box::new(LargeToken { kind: token.kind, offset: token.offset as usize, leading_width: leading.width, width: token.width as usize, trailing_width: token.trailing_width as usize, leading: leading.kinds, trailing: token.trailing, })), }; } } } self } fn with_trailing(mut self, trailing: CompactTrivia) -> Self { match &mut self.repr { Large(token) => { token.trailing_width = trailing.width; token.trailing = trailing.kinds; } Small(token) => { if let Ok(trailing_width) = trailing.width.try_into() { token.trailing_width = trailing_width; token.trailing = trailing.kinds; } else { return Self { repr: Large(Box::new(LargeToken { kind: token.kind, offset: token.offset as usize, leading_width: token.leading_width as usize, width: token.width as usize, trailing_width: trailing.width, leading: token.leading, trailing: trailing.kinds, })), }; } } } self } fn with_kind(mut self, kind: TokenKind) -> Self { match &mut self.repr { Small(t) => t.kind = kind, Large(t) => t.kind = kind, } self } } #[cfg(test)] mod test { use super::*; #[test] fn test_size() { // CompactToken is 16 bytes, the same size as a slice (on a 64-bit // architecture). If we end up needing to change this size, we should // carefully consider the performance impact on the direct decl parser. assert_eq!(std::mem::size_of::<CompactToken>(), 16); } }
Rust
hhvm/hphp/hack/src/parser/compact_trivia.rs
// Copyright (c) 2019, Facebook, Inc. // All rights reserved. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use bitflags::bitflags; use crate::lexable_trivia::LexableTrivia; use crate::minimal_trivia::MinimalTrivium; use crate::trivia_factory::SimpleTriviaFactory; use crate::trivia_kind::TriviaKind; bitflags! { pub struct TriviaKinds : u8 { const WHITE_SPACE = 1 << TriviaKind::WhiteSpace as u8; const END_OF_LINE = 1 << TriviaKind::EndOfLine as u8; const DELIMITED_COMMENT = 1 << TriviaKind::DelimitedComment as u8; const SINGLELINE_COMMENT = 1 << TriviaKind::SingleLineComment as u8; const FIX_ME = 1 << TriviaKind::FixMe as u8; const IGNORE_ERROR = 1 << TriviaKind::IgnoreError as u8; const FALL_THROUGH = 1 << TriviaKind::FallThrough as u8; const EXTRA_TOKEN_ERROR = 1 << TriviaKind::ExtraTokenError as u8; // NB: There are currently exactly 8 TriviaKinds, so we cannot add more // without changing the representation of this bitflags type. Making it // larger would require changing CompactToken too, since it currently // depends upon TriviaKinds fitting into a u8. } } impl TriviaKinds { pub fn from_kind(kind: TriviaKind) -> Self { match kind { TriviaKind::WhiteSpace => Self::WHITE_SPACE, TriviaKind::EndOfLine => Self::END_OF_LINE, TriviaKind::DelimitedComment => Self::DELIMITED_COMMENT, TriviaKind::SingleLineComment => Self::SINGLELINE_COMMENT, TriviaKind::FixMe => Self::FIX_ME, TriviaKind::IgnoreError => Self::IGNORE_ERROR, TriviaKind::FallThrough => Self::FALL_THROUGH, TriviaKind::ExtraTokenError => Self::EXTRA_TOKEN_ERROR, // NB: See above note about adding more TriviaKind variants } } pub fn has_kind(self, kind: TriviaKind) -> bool { self.contains(Self::from_kind(kind)) } } #[derive(Copy, Clone, Debug)] pub struct CompactTrivia { pub kinds: TriviaKinds, pub width: usize, } impl CompactTrivia { pub fn make(kinds: TriviaKinds, width: usize) -> Self { Self { kinds, width } } } impl LexableTrivia for CompactTrivia { type Trivium = MinimalTrivium; fn is_empty(&self) -> bool { self.kinds.is_empty() } fn has_kind(&self, kind: TriviaKind) -> bool { self.kinds.has_kind(kind) } fn push(&mut self, trivium: MinimalTrivium) { self.kinds |= TriviaKinds::from_kind(trivium.kind); self.width += trivium.width; } fn extend(&mut self, other: Self) { self.kinds |= other.kinds; self.width += other.width; } } impl SimpleTriviaFactory for CompactTrivia { fn make() -> Self { Self { kinds: TriviaKinds::empty(), width: 0, } } }
Rust
hhvm/hphp/hack/src/parser/decl_mode_smart_constructors.rs
// Copyright (c) 2019, Facebook, Inc. // All rights reserved. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. mod decl_mode_smart_constructors_generated; use bumpalo::Bump; use ocamlrep::Allocator; use ocamlrep::ToOcamlRep; use parser_core_types::lexable_token::LexableToken; use parser_core_types::source_text::SourceText; use parser_core_types::syntax::SyntaxTypeBase; use parser_core_types::syntax::SyntaxValueType; use parser_core_types::syntax_by_ref::has_arena::HasArena; use parser_core_types::syntax_by_ref::syntax::Syntax; use parser_core_types::syntax_by_ref::syntax_variant_generated::SyntaxVariant; use parser_core_types::syntax_type::SyntaxType; use parser_core_types::token_factory::TokenFactory; use parser_core_types::token_kind::TokenKind; use parser_core_types::trivia_factory::TriviaFactory; use syntax_smart_constructors::StateType; use syntax_smart_constructors::SyntaxSmartConstructors; pub struct State<'s, 'a, S> { arena: &'a Bump, source: SourceText<'s>, stack: Vec<bool>, phantom_s: std::marker::PhantomData<*const S>, } impl<'s, 'a, S> State<'s, 'a, S> { fn new(source: &SourceText<'s>, arena: &'a Bump) -> Self { Self { arena, source: source.clone(), stack: vec![], phantom_s: std::marker::PhantomData, } } } impl<S> Clone for State<'_, '_, S> { fn clone(&self) -> Self { Self { arena: self.arena, source: self.source.clone(), stack: self.stack.clone(), phantom_s: self.phantom_s, } } } impl<S> State<'_, '_, S> { /// Pops n times and returns the first popped element fn pop_n(&mut self, n: usize) -> bool { if self.stack.len() < n { panic!("invalid state"); } let head = self.stack.pop().unwrap(); self.stack.truncate(self.stack.len() - (n - 1)); // pop n-1 times efficiently head } fn push(&mut self, s: bool) { self.stack.push(s); } pub fn stack(&self) -> &Vec<bool> { &self.stack } } impl<S> StateType<S> for State<'_, '_, S> { fn next(&mut self, inputs: &[&S]) { let st_todo = if self.stack.len() > inputs.len() { self.stack.split_off(self.stack.len() - inputs.len()) } else { std::mem::take(&mut self.stack) }; let res = st_todo.into_iter().any(|b2| b2); self.push(res); } } impl<'a, S> HasArena<'a> for State<'_, 'a, S> { fn get_arena(&self) -> &'a Bump { self.arena } } pub use crate::decl_mode_smart_constructors_generated::*; pub struct DeclModeSmartConstructors<'s, 'a, S, T, V, TF> { pub state: State<'s, 'a, S>, pub token_factory: TF, phantom_value: std::marker::PhantomData<(V, T)>, } impl<'s, 'a, T, V, TF> DeclModeSmartConstructors<'s, 'a, Syntax<'a, T, V>, T, V, TF> { pub fn new(src: &SourceText<'s>, token_factory: TF, arena: &'a Bump) -> Self { Self { state: State::new(src, arena), token_factory, phantom_value: std::marker::PhantomData, } } } impl<'s, S, T, V, TF: Clone> Clone for DeclModeSmartConstructors<'s, '_, S, T, V, TF> { fn clone(&self) -> Self { Self { state: self.state.clone(), token_factory: self.token_factory.clone(), phantom_value: self.phantom_value, } } } type SyntaxToken<'s, 'a, T, V> = <Syntax<'a, T, V> as SyntaxTypeBase<State<'s, 'a, Syntax<'a, T, V>>>>::Token; impl<'s, 'a, T, V, TF> SyntaxSmartConstructors<Syntax<'a, T, V>, TF, State<'s, 'a, Syntax<'a, T, V>>> for DeclModeSmartConstructors<'s, 'a, Syntax<'a, T, V>, T, V, TF> where TF: TokenFactory<Token = SyntaxToken<'s, 'a, T, V>>, T: LexableToken + Copy, V: SyntaxValueType<T> + Clone, Syntax<'a, T, V>: SyntaxType<State<'s, 'a, Syntax<'a, T, V>>>, { fn make_yield_expression(&mut self, _r1: Self::Output, _r2: Self::Output) -> Self::Output { self.state.pop_n(2); self.state.push(true); Self::Output::make_missing(0) } fn make_lambda_expression( &mut self, r1: Self::Output, r2: Self::Output, r3: Self::Output, r4: Self::Output, body: Self::Output, ) -> Self::Output { let saw_yield = self.state.pop_n(5); let body = replace_body(&mut self.token_factory, &mut self.state, body, saw_yield); self.state.push(false); Self::Output::make_lambda_expression(&self.state, r1, r2, r3, r4, body) } fn make_anonymous_function( &mut self, r1: Self::Output, r2: Self::Output, r3: Self::Output, r4: Self::Output, r5: Self::Output, r6: Self::Output, r7: Self::Output, r8: Self::Output, r9: Self::Output, r10: Self::Output, r11: Self::Output, body: Self::Output, ) -> Self::Output { let saw_yield = self.state.pop_n(11); let body = replace_body(&mut self.token_factory, &mut self.state, body, saw_yield); self.state.push(false); Self::Output::make_anonymous_function( &self.state, r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11, body, ) } fn make_awaitable_creation_expression( &mut self, r1: Self::Output, r2: Self::Output, body: Self::Output, ) -> Self::Output { let saw_yield = self.state.pop_n(3); let body = replace_body(&mut self.token_factory, &mut self.state, body, saw_yield); self.state.push(false); Self::Output::make_awaitable_creation_expression(&self.state, r1, r2, body) } fn make_methodish_declaration( &mut self, r1: Self::Output, r2: Self::Output, body: Self::Output, r3: Self::Output, ) -> Self::Output { self.state.pop_n(1); let saw_yield = self.state.pop_n(3); let body = replace_body(&mut self.token_factory, &mut self.state, body, saw_yield); self.state.push(false); Self::Output::make_methodish_declaration(&self.state, r1, r2, body, r3) } fn make_function_declaration( &mut self, r1: Self::Output, r2: Self::Output, body: Self::Output, ) -> Self::Output { let saw_yield = self.state.pop_n(3); let body = replace_body(&mut self.token_factory, &mut self.state, body, saw_yield); self.state.push(false); Self::Output::make_function_declaration(&self.state, r1, r2, body) } } fn replace_body<'s, 'a, T, V, TF>( token_factory: &mut TF, st: &mut State<'s, 'a, Syntax<'a, T, V>>, body: Syntax<'a, T, V>, saw_yield: bool, ) -> Syntax<'a, T, V> where T: LexableToken + Copy, V: SyntaxValueType<T> + Clone, TF: TokenFactory<Token = SyntaxToken<'s, 'a, T, V>>, { match body.children { SyntaxVariant::CompoundStatement(children) => { let stmts = if saw_yield { let leading = token_factory.trivia_factory_mut().make(); let trailing = token_factory.trivia_factory_mut().make(); let token = token_factory.make(TokenKind::Yield, 0, 0, leading, trailing); let yield_ = Syntax::<T, V>::make_token(token); Syntax::make_list(st, vec![yield_], 0) } else { Syntax::make_missing(0) }; let left_brace = children.left_brace.clone(); let right_brace = children.right_brace.clone(); Syntax::make_compound_statement(st, left_brace, stmts, right_brace) } _ => body, } } impl<S> ToOcamlRep for State<'_, '_, S> { fn to_ocamlrep<'a, A: Allocator>(&'a self, alloc: &'a A) -> ocamlrep::Value<'a> { self.stack().to_ocamlrep(alloc) } }
Rust
hhvm/hphp/hack/src/parser/decl_mode_smart_constructors_generated.rs
/** * 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. An additional * directory. * ** * * THIS FILE IS @generated; DO NOT EDIT IT * To regenerate this file, run * * buck run //hphp/hack/src:generate_full_fidelity * ** * */ use parser_core_types::{ lexable_token::LexableToken, syntax::SyntaxValueType, syntax_by_ref::syntax::Syntax, token_factory::TokenFactory, }; use smart_constructors::SmartConstructors; use syntax_smart_constructors::SyntaxSmartConstructors; use crate::*; impl<'s, 'a, Token, Value, TF> SmartConstructors for DeclModeSmartConstructors<'s, 'a, Syntax<'a, Token, Value>, Token, Value, TF> where TF: TokenFactory<Token = SyntaxToken<'s, 'a, Token, Value>>, Token: LexableToken + Copy, Value: SyntaxValueType<Token> + Clone, { type State = State<'s, 'a, Syntax<'a, Token, Value>>; type Factory = TF; type Output = Syntax<'a, Token, Value>; fn state_mut(&mut self) -> &mut State<'s, 'a, Syntax<'a, Token, Value>> { &mut self.state } fn into_state(self) -> State<'s, 'a, Syntax<'a, Token, Value>> { self.state } fn token_factory_mut(&mut self) -> &mut Self::Factory { &mut self.token_factory } fn make_missing(&mut self, o: usize) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_missing(self, o) } fn make_token(&mut self, token: <Self::Factory as TokenFactory>::Token) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_token(self, token) } fn make_list(&mut self, items: Vec<Self::Output>, offset: usize) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_list(self, items, offset) } fn make_end_of_file(&mut self, arg0: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_end_of_file(self, arg0) } fn make_script(&mut self, arg0: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_script(self, arg0) } fn make_qualified_name(&mut self, arg0: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_qualified_name(self, arg0) } fn make_module_name(&mut self, arg0: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_module_name(self, arg0) } fn make_simple_type_specifier(&mut self, arg0: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_simple_type_specifier(self, arg0) } fn make_literal_expression(&mut self, arg0: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_literal_expression(self, arg0) } fn make_prefixed_string_expression(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_prefixed_string_expression(self, arg0, arg1) } fn make_prefixed_code_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_prefixed_code_expression(self, arg0, arg1, arg2, arg3) } fn make_variable_expression(&mut self, arg0: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_variable_expression(self, arg0) } fn make_pipe_variable_expression(&mut self, arg0: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_pipe_variable_expression(self, arg0) } fn make_file_attribute_specification(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_file_attribute_specification(self, arg0, arg1, arg2, arg3, arg4) } fn make_enum_declaration(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output, arg6: Self::Output, arg7: Self::Output, arg8: Self::Output, arg9: Self::Output, arg10: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_enum_declaration(self, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10) } fn make_enum_use(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_enum_use(self, arg0, arg1, arg2) } fn make_enumerator(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_enumerator(self, arg0, arg1, arg2, arg3) } fn make_enum_class_declaration(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output, arg6: Self::Output, arg7: Self::Output, arg8: Self::Output, arg9: Self::Output, arg10: Self::Output, arg11: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_enum_class_declaration(self, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11) } fn make_enum_class_enumerator(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_enum_class_enumerator(self, arg0, arg1, arg2, arg3, arg4) } fn make_alias_declaration(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output, arg6: Self::Output, arg7: Self::Output, arg8: Self::Output, arg9: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_alias_declaration(self, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9) } fn make_context_alias_declaration(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output, arg6: Self::Output, arg7: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_context_alias_declaration(self, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7) } fn make_case_type_declaration(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output, arg6: Self::Output, arg7: Self::Output, arg8: Self::Output, arg9: Self::Output, arg10: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_case_type_declaration(self, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10) } fn make_case_type_variant(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_case_type_variant(self, arg0, arg1) } fn make_property_declaration(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_property_declaration(self, arg0, arg1, arg2, arg3, arg4) } fn make_property_declarator(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_property_declarator(self, arg0, arg1) } fn make_namespace_declaration(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_namespace_declaration(self, arg0, arg1) } fn make_namespace_declaration_header(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_namespace_declaration_header(self, arg0, arg1) } fn make_namespace_body(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_namespace_body(self, arg0, arg1, arg2) } fn make_namespace_empty_body(&mut self, arg0: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_namespace_empty_body(self, arg0) } fn make_namespace_use_declaration(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_namespace_use_declaration(self, arg0, arg1, arg2, arg3) } fn make_namespace_group_use_declaration(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output, arg6: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_namespace_group_use_declaration(self, arg0, arg1, arg2, arg3, arg4, arg5, arg6) } fn make_namespace_use_clause(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_namespace_use_clause(self, arg0, arg1, arg2, arg3) } fn make_function_declaration(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_function_declaration(self, arg0, arg1, arg2) } fn make_function_declaration_header(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output, arg6: Self::Output, arg7: Self::Output, arg8: Self::Output, arg9: Self::Output, arg10: Self::Output, arg11: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_function_declaration_header(self, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11) } fn make_contexts(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_contexts(self, arg0, arg1, arg2) } fn make_where_clause(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_where_clause(self, arg0, arg1) } fn make_where_constraint(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_where_constraint(self, arg0, arg1, arg2) } fn make_methodish_declaration(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_methodish_declaration(self, arg0, arg1, arg2, arg3) } fn make_methodish_trait_resolution(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_methodish_trait_resolution(self, arg0, arg1, arg2, arg3, arg4) } fn make_classish_declaration(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output, arg6: Self::Output, arg7: Self::Output, arg8: Self::Output, arg9: Self::Output, arg10: Self::Output, arg11: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_classish_declaration(self, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11) } fn make_classish_body(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_classish_body(self, arg0, arg1, arg2) } fn make_trait_use(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_trait_use(self, arg0, arg1, arg2) } fn make_require_clause(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_require_clause(self, arg0, arg1, arg2, arg3) } fn make_const_declaration(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_const_declaration(self, arg0, arg1, arg2, arg3, arg4, arg5) } fn make_constant_declarator(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_constant_declarator(self, arg0, arg1) } fn make_type_const_declaration(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output, arg6: Self::Output, arg7: Self::Output, arg8: Self::Output, arg9: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_type_const_declaration(self, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9) } fn make_context_const_declaration(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output, arg6: Self::Output, arg7: Self::Output, arg8: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_context_const_declaration(self, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8) } fn make_decorated_expression(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_decorated_expression(self, arg0, arg1) } fn make_parameter_declaration(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output, arg6: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_parameter_declaration(self, arg0, arg1, arg2, arg3, arg4, arg5, arg6) } fn make_variadic_parameter(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_variadic_parameter(self, arg0, arg1, arg2) } fn make_old_attribute_specification(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_old_attribute_specification(self, arg0, arg1, arg2) } fn make_attribute_specification(&mut self, arg0: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_attribute_specification(self, arg0) } fn make_attribute(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_attribute(self, arg0, arg1) } fn make_inclusion_expression(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_inclusion_expression(self, arg0, arg1) } fn make_inclusion_directive(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_inclusion_directive(self, arg0, arg1) } fn make_compound_statement(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_compound_statement(self, arg0, arg1, arg2) } fn make_expression_statement(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_expression_statement(self, arg0, arg1) } fn make_markup_section(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_markup_section(self, arg0, arg1) } fn make_markup_suffix(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_markup_suffix(self, arg0, arg1) } fn make_unset_statement(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_unset_statement(self, arg0, arg1, arg2, arg3, arg4) } fn make_declare_local_statement(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_declare_local_statement(self, arg0, arg1, arg2, arg3, arg4, arg5) } fn make_using_statement_block_scoped(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_using_statement_block_scoped(self, arg0, arg1, arg2, arg3, arg4, arg5) } fn make_using_statement_function_scoped(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_using_statement_function_scoped(self, arg0, arg1, arg2, arg3) } fn make_while_statement(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_while_statement(self, arg0, arg1, arg2, arg3, arg4) } fn make_if_statement(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_if_statement(self, arg0, arg1, arg2, arg3, arg4, arg5) } fn make_else_clause(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_else_clause(self, arg0, arg1) } fn make_try_statement(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_try_statement(self, arg0, arg1, arg2, arg3) } fn make_catch_clause(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_catch_clause(self, arg0, arg1, arg2, arg3, arg4, arg5) } fn make_finally_clause(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_finally_clause(self, arg0, arg1) } fn make_do_statement(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output, arg6: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_do_statement(self, arg0, arg1, arg2, arg3, arg4, arg5, arg6) } fn make_for_statement(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output, arg6: Self::Output, arg7: Self::Output, arg8: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_for_statement(self, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8) } fn make_foreach_statement(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output, arg6: Self::Output, arg7: Self::Output, arg8: Self::Output, arg9: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_foreach_statement(self, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9) } fn make_switch_statement(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output, arg6: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_switch_statement(self, arg0, arg1, arg2, arg3, arg4, arg5, arg6) } fn make_switch_section(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_switch_section(self, arg0, arg1, arg2) } fn make_switch_fallthrough(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_switch_fallthrough(self, arg0, arg1) } fn make_case_label(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_case_label(self, arg0, arg1, arg2) } fn make_default_label(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_default_label(self, arg0, arg1) } fn make_match_statement(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output, arg6: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_match_statement(self, arg0, arg1, arg2, arg3, arg4, arg5, arg6) } fn make_match_statement_arm(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_match_statement_arm(self, arg0, arg1, arg2) } fn make_return_statement(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_return_statement(self, arg0, arg1, arg2) } fn make_yield_break_statement(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_yield_break_statement(self, arg0, arg1, arg2) } fn make_throw_statement(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_throw_statement(self, arg0, arg1, arg2) } fn make_break_statement(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_break_statement(self, arg0, arg1) } fn make_continue_statement(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_continue_statement(self, arg0, arg1) } fn make_echo_statement(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_echo_statement(self, arg0, arg1, arg2) } fn make_concurrent_statement(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_concurrent_statement(self, arg0, arg1) } fn make_simple_initializer(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_simple_initializer(self, arg0, arg1) } fn make_anonymous_class(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output, arg6: Self::Output, arg7: Self::Output, arg8: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_anonymous_class(self, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8) } fn make_anonymous_function(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output, arg6: Self::Output, arg7: Self::Output, arg8: Self::Output, arg9: Self::Output, arg10: Self::Output, arg11: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_anonymous_function(self, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11) } fn make_anonymous_function_use_clause(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_anonymous_function_use_clause(self, arg0, arg1, arg2, arg3) } fn make_variable_pattern(&mut self, arg0: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_variable_pattern(self, arg0) } fn make_constructor_pattern(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_constructor_pattern(self, arg0, arg1, arg2, arg3) } fn make_refinement_pattern(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_refinement_pattern(self, arg0, arg1, arg2) } fn make_lambda_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_lambda_expression(self, arg0, arg1, arg2, arg3, arg4) } fn make_lambda_signature(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output, arg6: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_lambda_signature(self, arg0, arg1, arg2, arg3, arg4, arg5, arg6) } fn make_cast_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_cast_expression(self, arg0, arg1, arg2, arg3) } fn make_scope_resolution_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_scope_resolution_expression(self, arg0, arg1, arg2) } fn make_member_selection_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_member_selection_expression(self, arg0, arg1, arg2) } fn make_safe_member_selection_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_safe_member_selection_expression(self, arg0, arg1, arg2) } fn make_embedded_member_selection_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_embedded_member_selection_expression(self, arg0, arg1, arg2) } fn make_yield_expression(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_yield_expression(self, arg0, arg1) } fn make_prefix_unary_expression(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_prefix_unary_expression(self, arg0, arg1) } fn make_postfix_unary_expression(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_postfix_unary_expression(self, arg0, arg1) } fn make_binary_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_binary_expression(self, arg0, arg1, arg2) } fn make_is_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_is_expression(self, arg0, arg1, arg2) } fn make_as_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_as_expression(self, arg0, arg1, arg2) } fn make_nullable_as_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_nullable_as_expression(self, arg0, arg1, arg2) } fn make_upcast_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_upcast_expression(self, arg0, arg1, arg2) } fn make_conditional_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_conditional_expression(self, arg0, arg1, arg2, arg3, arg4) } fn make_eval_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_eval_expression(self, arg0, arg1, arg2, arg3) } fn make_isset_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_isset_expression(self, arg0, arg1, arg2, arg3) } fn make_function_call_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_function_call_expression(self, arg0, arg1, arg2, arg3, arg4) } fn make_function_pointer_expression(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_function_pointer_expression(self, arg0, arg1) } fn make_parenthesized_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_parenthesized_expression(self, arg0, arg1, arg2) } fn make_braced_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_braced_expression(self, arg0, arg1, arg2) } fn make_et_splice_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_et_splice_expression(self, arg0, arg1, arg2, arg3) } fn make_embedded_braced_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_embedded_braced_expression(self, arg0, arg1, arg2) } fn make_list_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_list_expression(self, arg0, arg1, arg2, arg3) } fn make_collection_literal_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_collection_literal_expression(self, arg0, arg1, arg2, arg3) } fn make_object_creation_expression(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_object_creation_expression(self, arg0, arg1) } fn make_constructor_call(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_constructor_call(self, arg0, arg1, arg2, arg3) } fn make_darray_intrinsic_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_darray_intrinsic_expression(self, arg0, arg1, arg2, arg3, arg4) } fn make_dictionary_intrinsic_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_dictionary_intrinsic_expression(self, arg0, arg1, arg2, arg3, arg4) } fn make_keyset_intrinsic_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_keyset_intrinsic_expression(self, arg0, arg1, arg2, arg3, arg4) } fn make_varray_intrinsic_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_varray_intrinsic_expression(self, arg0, arg1, arg2, arg3, arg4) } fn make_vector_intrinsic_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_vector_intrinsic_expression(self, arg0, arg1, arg2, arg3, arg4) } fn make_element_initializer(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_element_initializer(self, arg0, arg1, arg2) } fn make_subscript_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_subscript_expression(self, arg0, arg1, arg2, arg3) } fn make_embedded_subscript_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_embedded_subscript_expression(self, arg0, arg1, arg2, arg3) } fn make_awaitable_creation_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_awaitable_creation_expression(self, arg0, arg1, arg2) } fn make_xhp_children_declaration(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_xhp_children_declaration(self, arg0, arg1, arg2) } fn make_xhp_children_parenthesized_list(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_xhp_children_parenthesized_list(self, arg0, arg1, arg2) } fn make_xhp_category_declaration(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_xhp_category_declaration(self, arg0, arg1, arg2) } fn make_xhp_enum_type(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_xhp_enum_type(self, arg0, arg1, arg2, arg3, arg4) } fn make_xhp_lateinit(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_xhp_lateinit(self, arg0, arg1) } fn make_xhp_required(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_xhp_required(self, arg0, arg1) } fn make_xhp_class_attribute_declaration(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_xhp_class_attribute_declaration(self, arg0, arg1, arg2) } fn make_xhp_class_attribute(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_xhp_class_attribute(self, arg0, arg1, arg2, arg3) } fn make_xhp_simple_class_attribute(&mut self, arg0: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_xhp_simple_class_attribute(self, arg0) } fn make_xhp_simple_attribute(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_xhp_simple_attribute(self, arg0, arg1, arg2) } fn make_xhp_spread_attribute(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_xhp_spread_attribute(self, arg0, arg1, arg2, arg3) } fn make_xhp_open(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_xhp_open(self, arg0, arg1, arg2, arg3) } fn make_xhp_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_xhp_expression(self, arg0, arg1, arg2) } fn make_xhp_close(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_xhp_close(self, arg0, arg1, arg2) } fn make_type_constant(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_type_constant(self, arg0, arg1, arg2) } fn make_vector_type_specifier(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_vector_type_specifier(self, arg0, arg1, arg2, arg3, arg4) } fn make_keyset_type_specifier(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_keyset_type_specifier(self, arg0, arg1, arg2, arg3, arg4) } fn make_tuple_type_explicit_specifier(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_tuple_type_explicit_specifier(self, arg0, arg1, arg2, arg3) } fn make_varray_type_specifier(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_varray_type_specifier(self, arg0, arg1, arg2, arg3, arg4) } fn make_function_ctx_type_specifier(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_function_ctx_type_specifier(self, arg0, arg1) } fn make_type_parameter(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_type_parameter(self, arg0, arg1, arg2, arg3, arg4, arg5) } fn make_type_constraint(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_type_constraint(self, arg0, arg1) } fn make_context_constraint(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_context_constraint(self, arg0, arg1) } fn make_darray_type_specifier(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output, arg6: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_darray_type_specifier(self, arg0, arg1, arg2, arg3, arg4, arg5, arg6) } fn make_dictionary_type_specifier(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_dictionary_type_specifier(self, arg0, arg1, arg2, arg3) } fn make_closure_type_specifier(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output, arg6: Self::Output, arg7: Self::Output, arg8: Self::Output, arg9: Self::Output, arg10: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_closure_type_specifier(self, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10) } fn make_closure_parameter_type_specifier(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_closure_parameter_type_specifier(self, arg0, arg1, arg2) } fn make_type_refinement(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_type_refinement(self, arg0, arg1, arg2, arg3, arg4) } fn make_type_in_refinement(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_type_in_refinement(self, arg0, arg1, arg2, arg3, arg4, arg5) } fn make_ctx_in_refinement(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_ctx_in_refinement(self, arg0, arg1, arg2, arg3, arg4, arg5) } fn make_classname_type_specifier(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_classname_type_specifier(self, arg0, arg1, arg2, arg3, arg4) } fn make_field_specifier(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_field_specifier(self, arg0, arg1, arg2, arg3) } fn make_field_initializer(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_field_initializer(self, arg0, arg1, arg2) } fn make_shape_type_specifier(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_shape_type_specifier(self, arg0, arg1, arg2, arg3, arg4) } fn make_shape_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_shape_expression(self, arg0, arg1, arg2, arg3) } fn make_tuple_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_tuple_expression(self, arg0, arg1, arg2, arg3) } fn make_generic_type_specifier(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_generic_type_specifier(self, arg0, arg1) } fn make_nullable_type_specifier(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_nullable_type_specifier(self, arg0, arg1) } fn make_like_type_specifier(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_like_type_specifier(self, arg0, arg1) } fn make_soft_type_specifier(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_soft_type_specifier(self, arg0, arg1) } fn make_attributized_specifier(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_attributized_specifier(self, arg0, arg1) } fn make_reified_type_argument(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_reified_type_argument(self, arg0, arg1) } fn make_type_arguments(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_type_arguments(self, arg0, arg1, arg2) } fn make_type_parameters(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_type_parameters(self, arg0, arg1, arg2) } fn make_tuple_type_specifier(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_tuple_type_specifier(self, arg0, arg1, arg2) } fn make_union_type_specifier(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_union_type_specifier(self, arg0, arg1, arg2) } fn make_intersection_type_specifier(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_intersection_type_specifier(self, arg0, arg1, arg2) } fn make_error(&mut self, arg0: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_error(self, arg0) } fn make_list_item(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_list_item(self, arg0, arg1) } fn make_enum_class_label_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_enum_class_label_expression(self, arg0, arg1, arg2) } fn make_module_declaration(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output, arg6: Self::Output, arg7: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_module_declaration(self, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7) } fn make_module_exports(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_module_exports(self, arg0, arg1, arg2, arg3) } fn make_module_imports(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_module_imports(self, arg0, arg1, arg2, arg3) } fn make_module_membership_declaration(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_module_membership_declaration(self, arg0, arg1, arg2) } fn make_package_expression(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_package_expression(self, arg0, arg1) } }
OCaml
hhvm/hphp/hack/src/parser/docblock_finder.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 module Syntax = Full_fidelity_positioned_syntax module Trivia = Full_fidelity_positioned_trivia module TriviaKind = Full_fidelity_trivia_kind (** * This is a simple data structure that allows querying for the docblock * given a line in the source code. Rough description: * * 1. Find the last comment preceding the line of the definition. * We also make sure this doesn't overlap with the preceding definition. * If the last comment is more than 1 line away, it is ignored. * * 2. If the last comment is a block-style comment (/* */) just return it. * * 3. Otherwise (if it is a line style comment //) attempt to merge it with * preceding line comments, if they exist. * NOTE: We also enforce that line comments must be on the definition's * immediately preceding line. *) (* line, string, is_line_comment *) type comment = int * string * bool type finder = { comments: comment array } let make_docblock_finder (comments : (Pos.t * Prim_defs.comment) list) : finder = (* The Hack parser produces comments in reverse but sorted order. *) let comments = Array.of_list (List.rev_map comments ~f:(fun (pos, cmt) -> let str = Prim_defs.string_of_comment cmt in (Pos.end_line pos, str, Prim_defs.is_line_comment cmt))) in { comments } (* Binary search for the index of the last comment before a given line. *) (* Merge all consecutive line comments preceding prev_line. * Stop when we reach last_line. *) let rec merge_line_comments (finder : finder) (idx : int) (last_line : int) (prev_line : int) (acc : string list) : string list = if idx < 0 then acc else let (line, str, is_line_comment) = finder.comments.(idx) in if is_line_comment && line > last_line && line = prev_line - 1 then merge_line_comments finder (idx - 1) last_line line (("//" ^ str) :: acc) else acc let find_last_comment_index finder line = Utils.infimum finder.comments line (fun (comment_line, _, _) line -> comment_line - line) let open_multiline = Str.regexp "^/\\*\\(\\*?\\) *" let close_multiline = Str.regexp " *\\*/$" (** Tidies up a delimited comment. 1. Strip the leading `/*` and trailing `*/`. 2. Remove leading whitespace equal to the least amount of whitespace before any comment lines after the first (since the first line is on the same line as the opening `/*`, it will almost always have only a single leading space). We remove leading whitespace equal to the least amount rather than removing all leading whitespace in order to preserve manual indentation of text in the doc block. 3. Remove leading `*` characters to properly handle box-style multiline doc blocks. Without this they would be formatted as Markdown lists. Known failure cases: 1. A doc block which is legitimately just a list of items will need at least one non-list item which is under-indented compared to the list in order to not strip all of the whitespace from the list items. The easiest way to do this is to write a little one line summary before the list and place it on its own line instead of directly after the `/*`. *) let tidy_delimited_comment comment = let comment = comment |> Str.replace_first open_multiline "" |> Str.replace_first close_multiline "" in let lines = String_utils.split_into_lines comment in let line_trimmer = match lines with | [] | [_] -> Caml.String.trim | _hd :: tail -> let get_whitespace_count x = String_utils.index_not_opt x " " in let counts = List.filter_map ~f:get_whitespace_count tail in let min = List.min_elt counts ~compare:(fun a b -> a - b) |> Option.value ~default:0 in let removal = Str.regexp (Printf.sprintf "^%s\\(\\* ?\\)?" (String.make min ' ')) in Str.replace_first removal "" in lines |> List.map ~f:line_trimmer |> String.concat ~sep:"\n" let find_docblock (finder : finder) (last_line : int) (line : int) : string option = match find_last_comment_index finder line with | Some comment_index -> let (comment_line, str, is_line_comment) = finder.comments.(comment_index) in if is_line_comment then match merge_line_comments finder comment_index last_line line [] with | [] -> None | lines -> Some (Caml.String.trim (String.concat ~sep:"" lines)) else if comment_line > last_line && comment_line >= line - 2 then Some ("/*" ^ str ^ "*/") else None | None -> None (* Find the last comment on `line` if it exists. *) let find_inline_comment (finder : finder) (line : int) : string option = match find_last_comment_index finder (line + 1) with | Some last_comment_index -> let (comment_line, str, is_line_comment) = finder.comments.(last_comment_index) in if comment_line = line then if is_line_comment then Some (Caml.String.trim ("//" ^ str)) else Some ("/*" ^ str ^ "*/") else None | None -> None (* Regexp matching single-line comments, either # foo or // foo . *) let line_comment_prefix = Str.regexp "^\\(//\\|#\\) ?" (** * Extract a // comment docblock that is directly before this node. * * // A function. * // It is useful. * function foo(): void {} * * In this example, we return "A function.\nIt is useful." *) let get_single_lines_docblock (node : Syntax.t) : string option = let rec aux trivia_list acc (seen_newline : bool) : string list = match trivia_list with | [] -> acc | hd :: tail -> (match Trivia.kind hd with | TriviaKind.SingleLineComment -> aux tail (Trivia.text hd :: acc) false | TriviaKind.WhiteSpace -> (* Step over whitespace. *) aux tail acc seen_newline | TriviaKind.EndOfLine -> (* Stop if we've seen consecutive newlines, as that means we've reached a blank line. *) if seen_newline then acc else aux tail acc true | TriviaKind.FixMe | TriviaKind.IgnoreError -> (* Step over HH_FIXME comments. *) aux tail acc false | TriviaKind.DelimitedComment | TriviaKind.FallThrough | TriviaKind.ExtraTokenError -> (* Stop if we see a /* ... */ comment, a FALLTHROUGH comment, or a syntax error. *) acc) in match aux (List.rev (Syntax.leading_trivia node)) [] false with | [] -> None | comment_lines -> Some (comment_lines |> List.map ~f:(Str.replace_first line_comment_prefix "") |> String.concat ~sep:"\n" |> Caml.String.trim) (** * Extract a /* ... */ comment docblock that is before this node, * even if there are blank lines present. * *) let get_delimited_docblock (node : Syntax.t) : string option = let rec aux trivia_list : string option = match trivia_list with | [] -> None | hd :: tail -> (match Trivia.kind hd with | TriviaKind.DelimitedComment -> (* We've found the comment. *) Some (tidy_delimited_comment (Trivia.text hd)) | TriviaKind.WhiteSpace | TriviaKind.EndOfLine | TriviaKind.FixMe | TriviaKind.IgnoreError -> (* Step over whitespace and HH_FIXME comments. *) aux tail | TriviaKind.SingleLineComment -> (* Give up if we have a // comment. *) None | TriviaKind.FallThrough | TriviaKind.ExtraTokenError -> (* Give up if we have a // FALLTHROUGH comment or syntax error. *) None) in aux (List.rev (Syntax.leading_trivia node)) let get_docblock (node : Syntax.t) : string option = Option.first_some (get_single_lines_docblock node) (get_delimited_docblock node)
OCaml Interface
hhvm/hphp/hack/src/parser/docblock_finder.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. * *) (** * This is a simple data structure that allows querying for the docblock * given a line in the source code. Rough description: * * 1. Find the last comment preceding the line of the definition. * We also make sure this doesn't overlap with the preceding definition. * If the last comment is more than 1 line away, it is ignored. * * 2. If the last comment is a block-style comment (/* */) just return it. * * 3. Otherwise (if it is a line style comment //) attempt to merge it with * preceding line comments, if they exist. * NOTE: We also enforce that line comments must be on the definition's * immediately preceding line. *) type finder val make_docblock_finder : (Pos.t * Prim_defs.comment) list -> finder val find_docblock : finder -> int -> int -> string option (** Find the last comment on `line` if it exists. *) val find_inline_comment : finder -> int -> string option (** Returns the docblock for the passed in syntax node. *) val get_docblock : Full_fidelity_positioned_syntax.t -> string option
OCaml
hhvm/hphp/hack/src/parser/docblock_parser.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 param_doc_re_str = {|@param[ ]+\([^ ]+\)[ ]+\(.+\)|} let param_doc_re = Str.regexp param_doc_re_str type param_info = { param_name: string; param_desc: string; } let parse_param_docs (line : string) : param_info option = if Str.string_match param_doc_re line 0 then let param_name = Str.matched_group 1 line in let param_desc = Str.matched_group 2 line in Some { param_name; param_desc } else None (* convert all multiline @attribute descriptions to singleline ones *) let parse_documentation_attributes (documentation_lines : string list) : string list = let attributes_info = List.fold ~init:([], None) ~f:(fun (documentation_attributes, current_attribute) line -> let trimmed_line = Caml.String.trim line in if Str.string_match (Str.regexp "@.*") trimmed_line 0 then (* new attribute *) match current_attribute with | Some current_attribute -> (* add previous attribute to the list and start building up this one *) (current_attribute :: documentation_attributes, Some trimmed_line) | None -> (documentation_attributes, Some trimmed_line) else (* either continuing attribute or not related to attributes *) match current_attribute with | Some current_attribute -> let new_current_attribute = current_attribute ^ " " ^ trimmed_line in (documentation_attributes, Some new_current_attribute) | None -> (documentation_attributes, None)) documentation_lines in match snd @@ attributes_info with | Some current_attribute -> (* add final attribute *) current_attribute :: (fst @@ attributes_info) | None -> fst @@ attributes_info let get_param_docs ~(docblock : string) : string String.Map.t = let documentation_lines = Str.split (Str.regexp "\n") docblock in let documentation_attributes = parse_documentation_attributes documentation_lines in List.fold ~init:String.Map.empty ~f:(fun param_docs line -> let split = parse_param_docs line in match split with | Some param_info -> let param_name = if String.is_prefix param_info.param_name ~prefix:"$" then param_info.param_name else "$" ^ param_info.param_name in Map.set ~key:param_name ~data:param_info.param_desc param_docs | None -> param_docs) documentation_attributes
OCaml Interface
hhvm/hphp/hack/src/parser/docblock_parser.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 Hh_prelude (** Takes a docblock with asterisks and leading/ending slashes removed. Returns the parameters mentioned in the docblock (with @param) and their descriptions with newlines removed. Parameters can be mentioned with the leading '$' or not: they will be indexed in the map with the '$' regardless. *) val get_param_docs : docblock:string -> string String.Map.t
hhvm/hphp/hack/src/parser/dune
(data_only_dirs api cargo core ffi_bridge lowerer bench js smart_constructors syntax_by_ref rust_parser_errors_ffi) (library (name positioned_by_ref_parser_ffi) (modules) (wrapped false) (c_library_flags -lpthread) (foreign_archives positioned_by_ref_parser_ffi)) (rule (targets libpositioned_by_ref_parser_ffi.a) (deps (source_tree %{workspace_root}/hack/src)) (locks /cargo) (action (run %{workspace_root}/hack/scripts/invoke_cargo.sh positioned_by_ref_parser_ffi positioned_by_ref_parser_ffi))) (library (name aast_parser_ffi) (modules) (wrapped false) (c_library_flags -lpthread) (foreign_archives aast_parser_ffi)) (rule (targets libaast_parser_ffi.a) (deps (source_tree %{workspace_root}/hack/src)) (locks /cargo) (action (run %{workspace_root}/hack/scripts/invoke_cargo.sh aast_parser_ffi aast_parser_ffi))) (library (name rust_parser_ffi) (modules) (wrapped false) (c_library_flags -lpthread) (foreign_archives rust_parser_ffi)) (rule (targets librust_parser_ffi.a) (deps (source_tree %{workspace_root}/hack/src)) (locks /cargo) (action (run %{workspace_root}/hack/scripts/invoke_cargo.sh rust_parser_ffi rust_parser_ffi))) (library (name rust_parser_errors_ffi) (modules) (wrapped false) (c_library_flags -lpthread) (foreign_archives rust_parser_errors_ffi)) (rule (targets librust_parser_errors_ffi.a) (deps (source_tree %{workspace_root}/hack/src)) (locks /cargo) (action (run %{workspace_root}/hack/scripts/invoke_cargo.sh rust_parser_errors_ffi rust_parser_errors_ffi))) (copy_files (files smart_constructors/*.ml)) (library (name full_fidelity) (wrapped false) (modules full_fidelity_parser_env full_fidelity_editable_positioned_original_source_data full_fidelity_editable_positioned_syntax full_fidelity_editable_positioned_token full_fidelity_editable_syntax full_fidelity_editable_token full_fidelity_editable_trivia full_fidelity_operator_generated full_fidelity_operator full_fidelity_parser full_fidelity_parser_errors full_fidelity_parser_profiling full_fidelity_positioned_syntax full_fidelity_positioned_token full_fidelity_positioned_trivia full_fidelity_rewriter full_fidelity_source_text full_fidelity_token_kind full_fidelity_syntax full_fidelity_syntax_error full_fidelity_syntax_kind full_fidelity_syntax_tree full_fidelity_syntax_type full_fidelity_trivia_kind lambda_analyzer lexable_trivia_sig lexable_token_sig lexable_positioned_token_sig positioned_parser positioned_syntax_sig syntax_sig rust_pointer rust_parser_ffi rust_lazy_trivia_ffi syntaxTransforms ; from smart_constructors smartConstructors smartConstructorsWrappers syntaxSmartConstructors) (libraries common file_info hh_autoimport naming_special_names parser_options parser_schema parser_schema_def positioned_by_ref_parser_ffi relative_path rust_parser_errors_ffi rust_parser_ffi sexplib) (preprocess (pps ppx_sexp_conv visitors.ppx ppx_deriving.std))) (library (name parsing_error) (wrapped false) (modules parsing_error) (libraries error_codes user_error pos_or_decl)) (library (name parser) (wrapped false) (modules docblock_finder docblock_parser full_fidelity_ast scoured_comments rust_aast_parser_types ide_parser_cache limited_width_pretty_printing_library namespaces parser_return pretty_printing_library pretty_printing_library_sig) (preprocess (pps visitors.ppx ppx_deriving.std)) (libraries ast direct_decl_parser fixme_provider full_fidelity heap_shared_mem hh_autoimport logging namespace_env nast aast_parser_ffi rust_parser_ffi parsing_error typing_ast utils_lint utils_php_escape)) (library (name hh_autoimport) (wrapped false) (modules hh_autoimport) (preprocess (pps visitors.ppx ppx_deriving.std)) (libraries collections core_kernel naming_special_names)) (library (name ast_and_decl_service) (modules ast_and_decl_service) (preprocess (pps ppx_deriving.std)) (libraries annotated_ast decl parser procs_procs rust_decl_ffi utils_core))
Rust
hhvm/hphp/hack/src/parser/expression_tree_check.rs
// Copyright (c) 2020, Facebook, Inc. // All rights reserved. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use oxidized::aast::Expr; use oxidized::aast::Expr_; use oxidized::aast::Program; use oxidized::aast_visitor::visit; use oxidized::aast_visitor::AstParams; use oxidized::aast_visitor::Node; use oxidized::aast_visitor::Visitor; use parser_core_types::syntax_error::SyntaxError; struct Checker { errors: Vec<SyntaxError>, } impl<'ast> Visitor<'ast> for Checker { type Params = AstParams<(), ()>; fn object(&mut self) -> &mut dyn Visitor<'ast, Params = Self::Params> { self } fn visit_expr(&mut self, c: &mut (), e: &Expr<(), ()>) -> Result<(), ()> { match &e.2 { Expr_::ExpressionTree(_) => {} Expr_::ETSplice(_) => { let msg = "Splice syntax ${...} can only occur inside expression trees Foo``...``."; let p = e.1.clone(); let (start_offset, end_offset) = p.info_raw(); self.errors.push(SyntaxError::make( start_offset, end_offset, msg.into(), vec![], )); // Don't recurse further on this subtree, to prevent // cascading errors that are all the same issue. return Ok(()); } _ => e.recurse(c, self)?, } Ok(()) } } /// Check for splice syntax ${...} outside of an expression tree literal. pub fn check_splices(program: &Program<(), ()>) -> Vec<SyntaxError> { let mut checker = Checker { errors: vec![] }; visit(&mut checker, &mut (), program).expect("Unexpected error when checking nested splices"); checker.errors }
Rust
hhvm/hphp/hack/src/parser/flatten_smart_constructors.rs
/** * 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. An additional * directory. * ** * * THIS FILE IS @generated; DO NOT EDIT IT * To regenerate this file, run * * buck run //hphp/hack/src:generate_full_fidelity * ** * */ use smart_constructors::SmartConstructors; use parser_core_types::{ lexable_token::LexableToken, syntax_kind::SyntaxKind, token_factory::TokenFactory, }; pub trait FlattenSmartConstructors: SmartConstructors { fn is_zero(s: &Self::Output) -> bool; fn zero(kind: SyntaxKind) -> Self::Output; fn flatten(&self, kind: SyntaxKind, lst: Vec<Self::Output>) -> Self::Output; fn make_missing(&mut self, _: usize) -> Self::Output { Self::zero(SyntaxKind::Missing) } fn make_token(&mut self, token: <Self::Factory as TokenFactory>::Token) -> Self::Output { Self::zero(SyntaxKind::Token(token.kind())) } fn make_list(&mut self, _: Vec<Self::Output>, _: usize) -> Self::Output { Self::zero(SyntaxKind::SyntaxList) } fn begin_enumerator(&mut self) {} fn begin_enum_class_enumerator(&mut self) {} fn begin_constant_declarator(&mut self) {} fn make_end_of_file(&mut self, arg0: Self::Output) -> Self::Output { if Self::is_zero(&arg0) { Self::zero(SyntaxKind::EndOfFile) } else { self.flatten(SyntaxKind::EndOfFile, vec!(arg0)) } } fn make_script(&mut self, arg0: Self::Output) -> Self::Output { if Self::is_zero(&arg0) { Self::zero(SyntaxKind::Script) } else { self.flatten(SyntaxKind::Script, vec!(arg0)) } } fn make_qualified_name(&mut self, arg0: Self::Output) -> Self::Output { if Self::is_zero(&arg0) { Self::zero(SyntaxKind::QualifiedName) } else { self.flatten(SyntaxKind::QualifiedName, vec!(arg0)) } } fn make_module_name(&mut self, arg0: Self::Output) -> Self::Output { if Self::is_zero(&arg0) { Self::zero(SyntaxKind::ModuleName) } else { self.flatten(SyntaxKind::ModuleName, vec!(arg0)) } } fn make_simple_type_specifier(&mut self, arg0: Self::Output) -> Self::Output { if Self::is_zero(&arg0) { Self::zero(SyntaxKind::SimpleTypeSpecifier) } else { self.flatten(SyntaxKind::SimpleTypeSpecifier, vec!(arg0)) } } fn make_literal_expression(&mut self, arg0: Self::Output) -> Self::Output { if Self::is_zero(&arg0) { Self::zero(SyntaxKind::LiteralExpression) } else { self.flatten(SyntaxKind::LiteralExpression, vec!(arg0)) } } fn make_prefixed_string_expression(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) { Self::zero(SyntaxKind::PrefixedStringExpression) } else { self.flatten(SyntaxKind::PrefixedStringExpression, vec!(arg0, arg1)) } } fn make_prefixed_code_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) { Self::zero(SyntaxKind::PrefixedCodeExpression) } else { self.flatten(SyntaxKind::PrefixedCodeExpression, vec!(arg0, arg1, arg2, arg3)) } } fn make_variable_expression(&mut self, arg0: Self::Output) -> Self::Output { if Self::is_zero(&arg0) { Self::zero(SyntaxKind::VariableExpression) } else { self.flatten(SyntaxKind::VariableExpression, vec!(arg0)) } } fn make_pipe_variable_expression(&mut self, arg0: Self::Output) -> Self::Output { if Self::is_zero(&arg0) { Self::zero(SyntaxKind::PipeVariableExpression) } else { self.flatten(SyntaxKind::PipeVariableExpression, vec!(arg0)) } } fn make_file_attribute_specification(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) { Self::zero(SyntaxKind::FileAttributeSpecification) } else { self.flatten(SyntaxKind::FileAttributeSpecification, vec!(arg0, arg1, arg2, arg3, arg4)) } } fn make_enum_declaration(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output, arg6: Self::Output, arg7: Self::Output, arg8: Self::Output, arg9: Self::Output, arg10: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) && Self::is_zero(&arg5) && Self::is_zero(&arg6) && Self::is_zero(&arg7) && Self::is_zero(&arg8) && Self::is_zero(&arg9) && Self::is_zero(&arg10) { Self::zero(SyntaxKind::EnumDeclaration) } else { self.flatten(SyntaxKind::EnumDeclaration, vec!(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10)) } } fn make_enum_use(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::EnumUse) } else { self.flatten(SyntaxKind::EnumUse, vec!(arg0, arg1, arg2)) } } fn make_enumerator(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) { Self::zero(SyntaxKind::Enumerator) } else { self.flatten(SyntaxKind::Enumerator, vec!(arg0, arg1, arg2, arg3)) } } fn make_enum_class_declaration(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output, arg6: Self::Output, arg7: Self::Output, arg8: Self::Output, arg9: Self::Output, arg10: Self::Output, arg11: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) && Self::is_zero(&arg5) && Self::is_zero(&arg6) && Self::is_zero(&arg7) && Self::is_zero(&arg8) && Self::is_zero(&arg9) && Self::is_zero(&arg10) && Self::is_zero(&arg11) { Self::zero(SyntaxKind::EnumClassDeclaration) } else { self.flatten(SyntaxKind::EnumClassDeclaration, vec!(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11)) } } fn make_enum_class_enumerator(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) { Self::zero(SyntaxKind::EnumClassEnumerator) } else { self.flatten(SyntaxKind::EnumClassEnumerator, vec!(arg0, arg1, arg2, arg3, arg4)) } } fn make_alias_declaration(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output, arg6: Self::Output, arg7: Self::Output, arg8: Self::Output, arg9: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) && Self::is_zero(&arg5) && Self::is_zero(&arg6) && Self::is_zero(&arg7) && Self::is_zero(&arg8) && Self::is_zero(&arg9) { Self::zero(SyntaxKind::AliasDeclaration) } else { self.flatten(SyntaxKind::AliasDeclaration, vec!(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9)) } } fn make_context_alias_declaration(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output, arg6: Self::Output, arg7: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) && Self::is_zero(&arg5) && Self::is_zero(&arg6) && Self::is_zero(&arg7) { Self::zero(SyntaxKind::ContextAliasDeclaration) } else { self.flatten(SyntaxKind::ContextAliasDeclaration, vec!(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7)) } } fn make_case_type_declaration(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output, arg6: Self::Output, arg7: Self::Output, arg8: Self::Output, arg9: Self::Output, arg10: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) && Self::is_zero(&arg5) && Self::is_zero(&arg6) && Self::is_zero(&arg7) && Self::is_zero(&arg8) && Self::is_zero(&arg9) && Self::is_zero(&arg10) { Self::zero(SyntaxKind::CaseTypeDeclaration) } else { self.flatten(SyntaxKind::CaseTypeDeclaration, vec!(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10)) } } fn make_case_type_variant(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) { Self::zero(SyntaxKind::CaseTypeVariant) } else { self.flatten(SyntaxKind::CaseTypeVariant, vec!(arg0, arg1)) } } fn make_property_declaration(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) { Self::zero(SyntaxKind::PropertyDeclaration) } else { self.flatten(SyntaxKind::PropertyDeclaration, vec!(arg0, arg1, arg2, arg3, arg4)) } } fn make_property_declarator(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) { Self::zero(SyntaxKind::PropertyDeclarator) } else { self.flatten(SyntaxKind::PropertyDeclarator, vec!(arg0, arg1)) } } fn make_namespace_declaration(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) { Self::zero(SyntaxKind::NamespaceDeclaration) } else { self.flatten(SyntaxKind::NamespaceDeclaration, vec!(arg0, arg1)) } } fn make_namespace_declaration_header(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) { Self::zero(SyntaxKind::NamespaceDeclarationHeader) } else { self.flatten(SyntaxKind::NamespaceDeclarationHeader, vec!(arg0, arg1)) } } fn make_namespace_body(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::NamespaceBody) } else { self.flatten(SyntaxKind::NamespaceBody, vec!(arg0, arg1, arg2)) } } fn make_namespace_empty_body(&mut self, arg0: Self::Output) -> Self::Output { if Self::is_zero(&arg0) { Self::zero(SyntaxKind::NamespaceEmptyBody) } else { self.flatten(SyntaxKind::NamespaceEmptyBody, vec!(arg0)) } } fn make_namespace_use_declaration(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) { Self::zero(SyntaxKind::NamespaceUseDeclaration) } else { self.flatten(SyntaxKind::NamespaceUseDeclaration, vec!(arg0, arg1, arg2, arg3)) } } fn make_namespace_group_use_declaration(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output, arg6: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) && Self::is_zero(&arg5) && Self::is_zero(&arg6) { Self::zero(SyntaxKind::NamespaceGroupUseDeclaration) } else { self.flatten(SyntaxKind::NamespaceGroupUseDeclaration, vec!(arg0, arg1, arg2, arg3, arg4, arg5, arg6)) } } fn make_namespace_use_clause(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) { Self::zero(SyntaxKind::NamespaceUseClause) } else { self.flatten(SyntaxKind::NamespaceUseClause, vec!(arg0, arg1, arg2, arg3)) } } fn make_function_declaration(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::FunctionDeclaration) } else { self.flatten(SyntaxKind::FunctionDeclaration, vec!(arg0, arg1, arg2)) } } fn make_function_declaration_header(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output, arg6: Self::Output, arg7: Self::Output, arg8: Self::Output, arg9: Self::Output, arg10: Self::Output, arg11: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) && Self::is_zero(&arg5) && Self::is_zero(&arg6) && Self::is_zero(&arg7) && Self::is_zero(&arg8) && Self::is_zero(&arg9) && Self::is_zero(&arg10) && Self::is_zero(&arg11) { Self::zero(SyntaxKind::FunctionDeclarationHeader) } else { self.flatten(SyntaxKind::FunctionDeclarationHeader, vec!(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11)) } } fn make_contexts(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::Contexts) } else { self.flatten(SyntaxKind::Contexts, vec!(arg0, arg1, arg2)) } } fn make_where_clause(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) { Self::zero(SyntaxKind::WhereClause) } else { self.flatten(SyntaxKind::WhereClause, vec!(arg0, arg1)) } } fn make_where_constraint(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::WhereConstraint) } else { self.flatten(SyntaxKind::WhereConstraint, vec!(arg0, arg1, arg2)) } } fn make_methodish_declaration(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) { Self::zero(SyntaxKind::MethodishDeclaration) } else { self.flatten(SyntaxKind::MethodishDeclaration, vec!(arg0, arg1, arg2, arg3)) } } fn make_methodish_trait_resolution(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) { Self::zero(SyntaxKind::MethodishTraitResolution) } else { self.flatten(SyntaxKind::MethodishTraitResolution, vec!(arg0, arg1, arg2, arg3, arg4)) } } fn make_classish_declaration(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output, arg6: Self::Output, arg7: Self::Output, arg8: Self::Output, arg9: Self::Output, arg10: Self::Output, arg11: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) && Self::is_zero(&arg5) && Self::is_zero(&arg6) && Self::is_zero(&arg7) && Self::is_zero(&arg8) && Self::is_zero(&arg9) && Self::is_zero(&arg10) && Self::is_zero(&arg11) { Self::zero(SyntaxKind::ClassishDeclaration) } else { self.flatten(SyntaxKind::ClassishDeclaration, vec!(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11)) } } fn make_classish_body(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::ClassishBody) } else { self.flatten(SyntaxKind::ClassishBody, vec!(arg0, arg1, arg2)) } } fn make_trait_use(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::TraitUse) } else { self.flatten(SyntaxKind::TraitUse, vec!(arg0, arg1, arg2)) } } fn make_require_clause(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) { Self::zero(SyntaxKind::RequireClause) } else { self.flatten(SyntaxKind::RequireClause, vec!(arg0, arg1, arg2, arg3)) } } fn make_const_declaration(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) && Self::is_zero(&arg5) { Self::zero(SyntaxKind::ConstDeclaration) } else { self.flatten(SyntaxKind::ConstDeclaration, vec!(arg0, arg1, arg2, arg3, arg4, arg5)) } } fn make_constant_declarator(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) { Self::zero(SyntaxKind::ConstantDeclarator) } else { self.flatten(SyntaxKind::ConstantDeclarator, vec!(arg0, arg1)) } } fn make_type_const_declaration(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output, arg6: Self::Output, arg7: Self::Output, arg8: Self::Output, arg9: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) && Self::is_zero(&arg5) && Self::is_zero(&arg6) && Self::is_zero(&arg7) && Self::is_zero(&arg8) && Self::is_zero(&arg9) { Self::zero(SyntaxKind::TypeConstDeclaration) } else { self.flatten(SyntaxKind::TypeConstDeclaration, vec!(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9)) } } fn make_context_const_declaration(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output, arg6: Self::Output, arg7: Self::Output, arg8: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) && Self::is_zero(&arg5) && Self::is_zero(&arg6) && Self::is_zero(&arg7) && Self::is_zero(&arg8) { Self::zero(SyntaxKind::ContextConstDeclaration) } else { self.flatten(SyntaxKind::ContextConstDeclaration, vec!(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8)) } } fn make_decorated_expression(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) { Self::zero(SyntaxKind::DecoratedExpression) } else { self.flatten(SyntaxKind::DecoratedExpression, vec!(arg0, arg1)) } } fn make_parameter_declaration(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output, arg6: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) && Self::is_zero(&arg5) && Self::is_zero(&arg6) { Self::zero(SyntaxKind::ParameterDeclaration) } else { self.flatten(SyntaxKind::ParameterDeclaration, vec!(arg0, arg1, arg2, arg3, arg4, arg5, arg6)) } } fn make_variadic_parameter(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::VariadicParameter) } else { self.flatten(SyntaxKind::VariadicParameter, vec!(arg0, arg1, arg2)) } } fn make_old_attribute_specification(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::OldAttributeSpecification) } else { self.flatten(SyntaxKind::OldAttributeSpecification, vec!(arg0, arg1, arg2)) } } fn make_attribute_specification(&mut self, arg0: Self::Output) -> Self::Output { if Self::is_zero(&arg0) { Self::zero(SyntaxKind::AttributeSpecification) } else { self.flatten(SyntaxKind::AttributeSpecification, vec!(arg0)) } } fn make_attribute(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) { Self::zero(SyntaxKind::Attribute) } else { self.flatten(SyntaxKind::Attribute, vec!(arg0, arg1)) } } fn make_inclusion_expression(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) { Self::zero(SyntaxKind::InclusionExpression) } else { self.flatten(SyntaxKind::InclusionExpression, vec!(arg0, arg1)) } } fn make_inclusion_directive(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) { Self::zero(SyntaxKind::InclusionDirective) } else { self.flatten(SyntaxKind::InclusionDirective, vec!(arg0, arg1)) } } fn make_compound_statement(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::CompoundStatement) } else { self.flatten(SyntaxKind::CompoundStatement, vec!(arg0, arg1, arg2)) } } fn make_expression_statement(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) { Self::zero(SyntaxKind::ExpressionStatement) } else { self.flatten(SyntaxKind::ExpressionStatement, vec!(arg0, arg1)) } } fn make_markup_section(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) { Self::zero(SyntaxKind::MarkupSection) } else { self.flatten(SyntaxKind::MarkupSection, vec!(arg0, arg1)) } } fn make_markup_suffix(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) { Self::zero(SyntaxKind::MarkupSuffix) } else { self.flatten(SyntaxKind::MarkupSuffix, vec!(arg0, arg1)) } } fn make_unset_statement(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) { Self::zero(SyntaxKind::UnsetStatement) } else { self.flatten(SyntaxKind::UnsetStatement, vec!(arg0, arg1, arg2, arg3, arg4)) } } fn make_declare_local_statement(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) && Self::is_zero(&arg5) { Self::zero(SyntaxKind::DeclareLocalStatement) } else { self.flatten(SyntaxKind::DeclareLocalStatement, vec!(arg0, arg1, arg2, arg3, arg4, arg5)) } } fn make_using_statement_block_scoped(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) && Self::is_zero(&arg5) { Self::zero(SyntaxKind::UsingStatementBlockScoped) } else { self.flatten(SyntaxKind::UsingStatementBlockScoped, vec!(arg0, arg1, arg2, arg3, arg4, arg5)) } } fn make_using_statement_function_scoped(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) { Self::zero(SyntaxKind::UsingStatementFunctionScoped) } else { self.flatten(SyntaxKind::UsingStatementFunctionScoped, vec!(arg0, arg1, arg2, arg3)) } } fn make_while_statement(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) { Self::zero(SyntaxKind::WhileStatement) } else { self.flatten(SyntaxKind::WhileStatement, vec!(arg0, arg1, arg2, arg3, arg4)) } } fn make_if_statement(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) && Self::is_zero(&arg5) { Self::zero(SyntaxKind::IfStatement) } else { self.flatten(SyntaxKind::IfStatement, vec!(arg0, arg1, arg2, arg3, arg4, arg5)) } } fn make_else_clause(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) { Self::zero(SyntaxKind::ElseClause) } else { self.flatten(SyntaxKind::ElseClause, vec!(arg0, arg1)) } } fn make_try_statement(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) { Self::zero(SyntaxKind::TryStatement) } else { self.flatten(SyntaxKind::TryStatement, vec!(arg0, arg1, arg2, arg3)) } } fn make_catch_clause(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) && Self::is_zero(&arg5) { Self::zero(SyntaxKind::CatchClause) } else { self.flatten(SyntaxKind::CatchClause, vec!(arg0, arg1, arg2, arg3, arg4, arg5)) } } fn make_finally_clause(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) { Self::zero(SyntaxKind::FinallyClause) } else { self.flatten(SyntaxKind::FinallyClause, vec!(arg0, arg1)) } } fn make_do_statement(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output, arg6: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) && Self::is_zero(&arg5) && Self::is_zero(&arg6) { Self::zero(SyntaxKind::DoStatement) } else { self.flatten(SyntaxKind::DoStatement, vec!(arg0, arg1, arg2, arg3, arg4, arg5, arg6)) } } fn make_for_statement(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output, arg6: Self::Output, arg7: Self::Output, arg8: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) && Self::is_zero(&arg5) && Self::is_zero(&arg6) && Self::is_zero(&arg7) && Self::is_zero(&arg8) { Self::zero(SyntaxKind::ForStatement) } else { self.flatten(SyntaxKind::ForStatement, vec!(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8)) } } fn make_foreach_statement(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output, arg6: Self::Output, arg7: Self::Output, arg8: Self::Output, arg9: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) && Self::is_zero(&arg5) && Self::is_zero(&arg6) && Self::is_zero(&arg7) && Self::is_zero(&arg8) && Self::is_zero(&arg9) { Self::zero(SyntaxKind::ForeachStatement) } else { self.flatten(SyntaxKind::ForeachStatement, vec!(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9)) } } fn make_switch_statement(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output, arg6: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) && Self::is_zero(&arg5) && Self::is_zero(&arg6) { Self::zero(SyntaxKind::SwitchStatement) } else { self.flatten(SyntaxKind::SwitchStatement, vec!(arg0, arg1, arg2, arg3, arg4, arg5, arg6)) } } fn make_switch_section(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::SwitchSection) } else { self.flatten(SyntaxKind::SwitchSection, vec!(arg0, arg1, arg2)) } } fn make_switch_fallthrough(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) { Self::zero(SyntaxKind::SwitchFallthrough) } else { self.flatten(SyntaxKind::SwitchFallthrough, vec!(arg0, arg1)) } } fn make_case_label(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::CaseLabel) } else { self.flatten(SyntaxKind::CaseLabel, vec!(arg0, arg1, arg2)) } } fn make_default_label(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) { Self::zero(SyntaxKind::DefaultLabel) } else { self.flatten(SyntaxKind::DefaultLabel, vec!(arg0, arg1)) } } fn make_match_statement(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output, arg6: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) && Self::is_zero(&arg5) && Self::is_zero(&arg6) { Self::zero(SyntaxKind::MatchStatement) } else { self.flatten(SyntaxKind::MatchStatement, vec!(arg0, arg1, arg2, arg3, arg4, arg5, arg6)) } } fn make_match_statement_arm(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::MatchStatementArm) } else { self.flatten(SyntaxKind::MatchStatementArm, vec!(arg0, arg1, arg2)) } } fn make_return_statement(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::ReturnStatement) } else { self.flatten(SyntaxKind::ReturnStatement, vec!(arg0, arg1, arg2)) } } fn make_yield_break_statement(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::YieldBreakStatement) } else { self.flatten(SyntaxKind::YieldBreakStatement, vec!(arg0, arg1, arg2)) } } fn make_throw_statement(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::ThrowStatement) } else { self.flatten(SyntaxKind::ThrowStatement, vec!(arg0, arg1, arg2)) } } fn make_break_statement(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) { Self::zero(SyntaxKind::BreakStatement) } else { self.flatten(SyntaxKind::BreakStatement, vec!(arg0, arg1)) } } fn make_continue_statement(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) { Self::zero(SyntaxKind::ContinueStatement) } else { self.flatten(SyntaxKind::ContinueStatement, vec!(arg0, arg1)) } } fn make_echo_statement(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::EchoStatement) } else { self.flatten(SyntaxKind::EchoStatement, vec!(arg0, arg1, arg2)) } } fn make_concurrent_statement(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) { Self::zero(SyntaxKind::ConcurrentStatement) } else { self.flatten(SyntaxKind::ConcurrentStatement, vec!(arg0, arg1)) } } fn make_simple_initializer(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) { Self::zero(SyntaxKind::SimpleInitializer) } else { self.flatten(SyntaxKind::SimpleInitializer, vec!(arg0, arg1)) } } fn make_anonymous_class(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output, arg6: Self::Output, arg7: Self::Output, arg8: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) && Self::is_zero(&arg5) && Self::is_zero(&arg6) && Self::is_zero(&arg7) && Self::is_zero(&arg8) { Self::zero(SyntaxKind::AnonymousClass) } else { self.flatten(SyntaxKind::AnonymousClass, vec!(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8)) } } fn make_anonymous_function(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output, arg6: Self::Output, arg7: Self::Output, arg8: Self::Output, arg9: Self::Output, arg10: Self::Output, arg11: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) && Self::is_zero(&arg5) && Self::is_zero(&arg6) && Self::is_zero(&arg7) && Self::is_zero(&arg8) && Self::is_zero(&arg9) && Self::is_zero(&arg10) && Self::is_zero(&arg11) { Self::zero(SyntaxKind::AnonymousFunction) } else { self.flatten(SyntaxKind::AnonymousFunction, vec!(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11)) } } fn make_anonymous_function_use_clause(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) { Self::zero(SyntaxKind::AnonymousFunctionUseClause) } else { self.flatten(SyntaxKind::AnonymousFunctionUseClause, vec!(arg0, arg1, arg2, arg3)) } } fn make_variable_pattern(&mut self, arg0: Self::Output) -> Self::Output { if Self::is_zero(&arg0) { Self::zero(SyntaxKind::VariablePattern) } else { self.flatten(SyntaxKind::VariablePattern, vec!(arg0)) } } fn make_constructor_pattern(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) { Self::zero(SyntaxKind::ConstructorPattern) } else { self.flatten(SyntaxKind::ConstructorPattern, vec!(arg0, arg1, arg2, arg3)) } } fn make_refinement_pattern(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::RefinementPattern) } else { self.flatten(SyntaxKind::RefinementPattern, vec!(arg0, arg1, arg2)) } } fn make_lambda_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) { Self::zero(SyntaxKind::LambdaExpression) } else { self.flatten(SyntaxKind::LambdaExpression, vec!(arg0, arg1, arg2, arg3, arg4)) } } fn make_lambda_signature(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output, arg6: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) && Self::is_zero(&arg5) && Self::is_zero(&arg6) { Self::zero(SyntaxKind::LambdaSignature) } else { self.flatten(SyntaxKind::LambdaSignature, vec!(arg0, arg1, arg2, arg3, arg4, arg5, arg6)) } } fn make_cast_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) { Self::zero(SyntaxKind::CastExpression) } else { self.flatten(SyntaxKind::CastExpression, vec!(arg0, arg1, arg2, arg3)) } } fn make_scope_resolution_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::ScopeResolutionExpression) } else { self.flatten(SyntaxKind::ScopeResolutionExpression, vec!(arg0, arg1, arg2)) } } fn make_member_selection_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::MemberSelectionExpression) } else { self.flatten(SyntaxKind::MemberSelectionExpression, vec!(arg0, arg1, arg2)) } } fn make_safe_member_selection_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::SafeMemberSelectionExpression) } else { self.flatten(SyntaxKind::SafeMemberSelectionExpression, vec!(arg0, arg1, arg2)) } } fn make_embedded_member_selection_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::EmbeddedMemberSelectionExpression) } else { self.flatten(SyntaxKind::EmbeddedMemberSelectionExpression, vec!(arg0, arg1, arg2)) } } fn make_yield_expression(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) { Self::zero(SyntaxKind::YieldExpression) } else { self.flatten(SyntaxKind::YieldExpression, vec!(arg0, arg1)) } } fn make_prefix_unary_expression(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) { Self::zero(SyntaxKind::PrefixUnaryExpression) } else { self.flatten(SyntaxKind::PrefixUnaryExpression, vec!(arg0, arg1)) } } fn make_postfix_unary_expression(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) { Self::zero(SyntaxKind::PostfixUnaryExpression) } else { self.flatten(SyntaxKind::PostfixUnaryExpression, vec!(arg0, arg1)) } } fn make_binary_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::BinaryExpression) } else { self.flatten(SyntaxKind::BinaryExpression, vec!(arg0, arg1, arg2)) } } fn make_is_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::IsExpression) } else { self.flatten(SyntaxKind::IsExpression, vec!(arg0, arg1, arg2)) } } fn make_as_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::AsExpression) } else { self.flatten(SyntaxKind::AsExpression, vec!(arg0, arg1, arg2)) } } fn make_nullable_as_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::NullableAsExpression) } else { self.flatten(SyntaxKind::NullableAsExpression, vec!(arg0, arg1, arg2)) } } fn make_upcast_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::UpcastExpression) } else { self.flatten(SyntaxKind::UpcastExpression, vec!(arg0, arg1, arg2)) } } fn make_conditional_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) { Self::zero(SyntaxKind::ConditionalExpression) } else { self.flatten(SyntaxKind::ConditionalExpression, vec!(arg0, arg1, arg2, arg3, arg4)) } } fn make_eval_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) { Self::zero(SyntaxKind::EvalExpression) } else { self.flatten(SyntaxKind::EvalExpression, vec!(arg0, arg1, arg2, arg3)) } } fn make_isset_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) { Self::zero(SyntaxKind::IssetExpression) } else { self.flatten(SyntaxKind::IssetExpression, vec!(arg0, arg1, arg2, arg3)) } } fn make_function_call_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) { Self::zero(SyntaxKind::FunctionCallExpression) } else { self.flatten(SyntaxKind::FunctionCallExpression, vec!(arg0, arg1, arg2, arg3, arg4)) } } fn make_function_pointer_expression(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) { Self::zero(SyntaxKind::FunctionPointerExpression) } else { self.flatten(SyntaxKind::FunctionPointerExpression, vec!(arg0, arg1)) } } fn make_parenthesized_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::ParenthesizedExpression) } else { self.flatten(SyntaxKind::ParenthesizedExpression, vec!(arg0, arg1, arg2)) } } fn make_braced_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::BracedExpression) } else { self.flatten(SyntaxKind::BracedExpression, vec!(arg0, arg1, arg2)) } } fn make_et_splice_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) { Self::zero(SyntaxKind::ETSpliceExpression) } else { self.flatten(SyntaxKind::ETSpliceExpression, vec!(arg0, arg1, arg2, arg3)) } } fn make_embedded_braced_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::EmbeddedBracedExpression) } else { self.flatten(SyntaxKind::EmbeddedBracedExpression, vec!(arg0, arg1, arg2)) } } fn make_list_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) { Self::zero(SyntaxKind::ListExpression) } else { self.flatten(SyntaxKind::ListExpression, vec!(arg0, arg1, arg2, arg3)) } } fn make_collection_literal_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) { Self::zero(SyntaxKind::CollectionLiteralExpression) } else { self.flatten(SyntaxKind::CollectionLiteralExpression, vec!(arg0, arg1, arg2, arg3)) } } fn make_object_creation_expression(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) { Self::zero(SyntaxKind::ObjectCreationExpression) } else { self.flatten(SyntaxKind::ObjectCreationExpression, vec!(arg0, arg1)) } } fn make_constructor_call(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) { Self::zero(SyntaxKind::ConstructorCall) } else { self.flatten(SyntaxKind::ConstructorCall, vec!(arg0, arg1, arg2, arg3)) } } fn make_darray_intrinsic_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) { Self::zero(SyntaxKind::DarrayIntrinsicExpression) } else { self.flatten(SyntaxKind::DarrayIntrinsicExpression, vec!(arg0, arg1, arg2, arg3, arg4)) } } fn make_dictionary_intrinsic_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) { Self::zero(SyntaxKind::DictionaryIntrinsicExpression) } else { self.flatten(SyntaxKind::DictionaryIntrinsicExpression, vec!(arg0, arg1, arg2, arg3, arg4)) } } fn make_keyset_intrinsic_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) { Self::zero(SyntaxKind::KeysetIntrinsicExpression) } else { self.flatten(SyntaxKind::KeysetIntrinsicExpression, vec!(arg0, arg1, arg2, arg3, arg4)) } } fn make_varray_intrinsic_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) { Self::zero(SyntaxKind::VarrayIntrinsicExpression) } else { self.flatten(SyntaxKind::VarrayIntrinsicExpression, vec!(arg0, arg1, arg2, arg3, arg4)) } } fn make_vector_intrinsic_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) { Self::zero(SyntaxKind::VectorIntrinsicExpression) } else { self.flatten(SyntaxKind::VectorIntrinsicExpression, vec!(arg0, arg1, arg2, arg3, arg4)) } } fn make_element_initializer(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::ElementInitializer) } else { self.flatten(SyntaxKind::ElementInitializer, vec!(arg0, arg1, arg2)) } } fn make_subscript_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) { Self::zero(SyntaxKind::SubscriptExpression) } else { self.flatten(SyntaxKind::SubscriptExpression, vec!(arg0, arg1, arg2, arg3)) } } fn make_embedded_subscript_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) { Self::zero(SyntaxKind::EmbeddedSubscriptExpression) } else { self.flatten(SyntaxKind::EmbeddedSubscriptExpression, vec!(arg0, arg1, arg2, arg3)) } } fn make_awaitable_creation_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::AwaitableCreationExpression) } else { self.flatten(SyntaxKind::AwaitableCreationExpression, vec!(arg0, arg1, arg2)) } } fn make_xhp_children_declaration(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::XHPChildrenDeclaration) } else { self.flatten(SyntaxKind::XHPChildrenDeclaration, vec!(arg0, arg1, arg2)) } } fn make_xhp_children_parenthesized_list(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::XHPChildrenParenthesizedList) } else { self.flatten(SyntaxKind::XHPChildrenParenthesizedList, vec!(arg0, arg1, arg2)) } } fn make_xhp_category_declaration(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::XHPCategoryDeclaration) } else { self.flatten(SyntaxKind::XHPCategoryDeclaration, vec!(arg0, arg1, arg2)) } } fn make_xhp_enum_type(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) { Self::zero(SyntaxKind::XHPEnumType) } else { self.flatten(SyntaxKind::XHPEnumType, vec!(arg0, arg1, arg2, arg3, arg4)) } } fn make_xhp_lateinit(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) { Self::zero(SyntaxKind::XHPLateinit) } else { self.flatten(SyntaxKind::XHPLateinit, vec!(arg0, arg1)) } } fn make_xhp_required(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) { Self::zero(SyntaxKind::XHPRequired) } else { self.flatten(SyntaxKind::XHPRequired, vec!(arg0, arg1)) } } fn make_xhp_class_attribute_declaration(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::XHPClassAttributeDeclaration) } else { self.flatten(SyntaxKind::XHPClassAttributeDeclaration, vec!(arg0, arg1, arg2)) } } fn make_xhp_class_attribute(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) { Self::zero(SyntaxKind::XHPClassAttribute) } else { self.flatten(SyntaxKind::XHPClassAttribute, vec!(arg0, arg1, arg2, arg3)) } } fn make_xhp_simple_class_attribute(&mut self, arg0: Self::Output) -> Self::Output { if Self::is_zero(&arg0) { Self::zero(SyntaxKind::XHPSimpleClassAttribute) } else { self.flatten(SyntaxKind::XHPSimpleClassAttribute, vec!(arg0)) } } fn make_xhp_simple_attribute(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::XHPSimpleAttribute) } else { self.flatten(SyntaxKind::XHPSimpleAttribute, vec!(arg0, arg1, arg2)) } } fn make_xhp_spread_attribute(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) { Self::zero(SyntaxKind::XHPSpreadAttribute) } else { self.flatten(SyntaxKind::XHPSpreadAttribute, vec!(arg0, arg1, arg2, arg3)) } } fn make_xhp_open(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) { Self::zero(SyntaxKind::XHPOpen) } else { self.flatten(SyntaxKind::XHPOpen, vec!(arg0, arg1, arg2, arg3)) } } fn make_xhp_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::XHPExpression) } else { self.flatten(SyntaxKind::XHPExpression, vec!(arg0, arg1, arg2)) } } fn make_xhp_close(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::XHPClose) } else { self.flatten(SyntaxKind::XHPClose, vec!(arg0, arg1, arg2)) } } fn make_type_constant(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::TypeConstant) } else { self.flatten(SyntaxKind::TypeConstant, vec!(arg0, arg1, arg2)) } } fn make_vector_type_specifier(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) { Self::zero(SyntaxKind::VectorTypeSpecifier) } else { self.flatten(SyntaxKind::VectorTypeSpecifier, vec!(arg0, arg1, arg2, arg3, arg4)) } } fn make_keyset_type_specifier(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) { Self::zero(SyntaxKind::KeysetTypeSpecifier) } else { self.flatten(SyntaxKind::KeysetTypeSpecifier, vec!(arg0, arg1, arg2, arg3, arg4)) } } fn make_tuple_type_explicit_specifier(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) { Self::zero(SyntaxKind::TupleTypeExplicitSpecifier) } else { self.flatten(SyntaxKind::TupleTypeExplicitSpecifier, vec!(arg0, arg1, arg2, arg3)) } } fn make_varray_type_specifier(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) { Self::zero(SyntaxKind::VarrayTypeSpecifier) } else { self.flatten(SyntaxKind::VarrayTypeSpecifier, vec!(arg0, arg1, arg2, arg3, arg4)) } } fn make_function_ctx_type_specifier(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) { Self::zero(SyntaxKind::FunctionCtxTypeSpecifier) } else { self.flatten(SyntaxKind::FunctionCtxTypeSpecifier, vec!(arg0, arg1)) } } fn make_type_parameter(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) && Self::is_zero(&arg5) { Self::zero(SyntaxKind::TypeParameter) } else { self.flatten(SyntaxKind::TypeParameter, vec!(arg0, arg1, arg2, arg3, arg4, arg5)) } } fn make_type_constraint(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) { Self::zero(SyntaxKind::TypeConstraint) } else { self.flatten(SyntaxKind::TypeConstraint, vec!(arg0, arg1)) } } fn make_context_constraint(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) { Self::zero(SyntaxKind::ContextConstraint) } else { self.flatten(SyntaxKind::ContextConstraint, vec!(arg0, arg1)) } } fn make_darray_type_specifier(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output, arg6: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) && Self::is_zero(&arg5) && Self::is_zero(&arg6) { Self::zero(SyntaxKind::DarrayTypeSpecifier) } else { self.flatten(SyntaxKind::DarrayTypeSpecifier, vec!(arg0, arg1, arg2, arg3, arg4, arg5, arg6)) } } fn make_dictionary_type_specifier(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) { Self::zero(SyntaxKind::DictionaryTypeSpecifier) } else { self.flatten(SyntaxKind::DictionaryTypeSpecifier, vec!(arg0, arg1, arg2, arg3)) } } fn make_closure_type_specifier(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output, arg6: Self::Output, arg7: Self::Output, arg8: Self::Output, arg9: Self::Output, arg10: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) && Self::is_zero(&arg5) && Self::is_zero(&arg6) && Self::is_zero(&arg7) && Self::is_zero(&arg8) && Self::is_zero(&arg9) && Self::is_zero(&arg10) { Self::zero(SyntaxKind::ClosureTypeSpecifier) } else { self.flatten(SyntaxKind::ClosureTypeSpecifier, vec!(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10)) } } fn make_closure_parameter_type_specifier(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::ClosureParameterTypeSpecifier) } else { self.flatten(SyntaxKind::ClosureParameterTypeSpecifier, vec!(arg0, arg1, arg2)) } } fn make_type_refinement(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) { Self::zero(SyntaxKind::TypeRefinement) } else { self.flatten(SyntaxKind::TypeRefinement, vec!(arg0, arg1, arg2, arg3, arg4)) } } fn make_type_in_refinement(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) && Self::is_zero(&arg5) { Self::zero(SyntaxKind::TypeInRefinement) } else { self.flatten(SyntaxKind::TypeInRefinement, vec!(arg0, arg1, arg2, arg3, arg4, arg5)) } } fn make_ctx_in_refinement(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) && Self::is_zero(&arg5) { Self::zero(SyntaxKind::CtxInRefinement) } else { self.flatten(SyntaxKind::CtxInRefinement, vec!(arg0, arg1, arg2, arg3, arg4, arg5)) } } fn make_classname_type_specifier(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) { Self::zero(SyntaxKind::ClassnameTypeSpecifier) } else { self.flatten(SyntaxKind::ClassnameTypeSpecifier, vec!(arg0, arg1, arg2, arg3, arg4)) } } fn make_field_specifier(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) { Self::zero(SyntaxKind::FieldSpecifier) } else { self.flatten(SyntaxKind::FieldSpecifier, vec!(arg0, arg1, arg2, arg3)) } } fn make_field_initializer(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::FieldInitializer) } else { self.flatten(SyntaxKind::FieldInitializer, vec!(arg0, arg1, arg2)) } } fn make_shape_type_specifier(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) { Self::zero(SyntaxKind::ShapeTypeSpecifier) } else { self.flatten(SyntaxKind::ShapeTypeSpecifier, vec!(arg0, arg1, arg2, arg3, arg4)) } } fn make_shape_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) { Self::zero(SyntaxKind::ShapeExpression) } else { self.flatten(SyntaxKind::ShapeExpression, vec!(arg0, arg1, arg2, arg3)) } } fn make_tuple_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) { Self::zero(SyntaxKind::TupleExpression) } else { self.flatten(SyntaxKind::TupleExpression, vec!(arg0, arg1, arg2, arg3)) } } fn make_generic_type_specifier(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) { Self::zero(SyntaxKind::GenericTypeSpecifier) } else { self.flatten(SyntaxKind::GenericTypeSpecifier, vec!(arg0, arg1)) } } fn make_nullable_type_specifier(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) { Self::zero(SyntaxKind::NullableTypeSpecifier) } else { self.flatten(SyntaxKind::NullableTypeSpecifier, vec!(arg0, arg1)) } } fn make_like_type_specifier(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) { Self::zero(SyntaxKind::LikeTypeSpecifier) } else { self.flatten(SyntaxKind::LikeTypeSpecifier, vec!(arg0, arg1)) } } fn make_soft_type_specifier(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) { Self::zero(SyntaxKind::SoftTypeSpecifier) } else { self.flatten(SyntaxKind::SoftTypeSpecifier, vec!(arg0, arg1)) } } fn make_attributized_specifier(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) { Self::zero(SyntaxKind::AttributizedSpecifier) } else { self.flatten(SyntaxKind::AttributizedSpecifier, vec!(arg0, arg1)) } } fn make_reified_type_argument(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) { Self::zero(SyntaxKind::ReifiedTypeArgument) } else { self.flatten(SyntaxKind::ReifiedTypeArgument, vec!(arg0, arg1)) } } fn make_type_arguments(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::TypeArguments) } else { self.flatten(SyntaxKind::TypeArguments, vec!(arg0, arg1, arg2)) } } fn make_type_parameters(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::TypeParameters) } else { self.flatten(SyntaxKind::TypeParameters, vec!(arg0, arg1, arg2)) } } fn make_tuple_type_specifier(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::TupleTypeSpecifier) } else { self.flatten(SyntaxKind::TupleTypeSpecifier, vec!(arg0, arg1, arg2)) } } fn make_union_type_specifier(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::UnionTypeSpecifier) } else { self.flatten(SyntaxKind::UnionTypeSpecifier, vec!(arg0, arg1, arg2)) } } fn make_intersection_type_specifier(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::IntersectionTypeSpecifier) } else { self.flatten(SyntaxKind::IntersectionTypeSpecifier, vec!(arg0, arg1, arg2)) } } fn make_error(&mut self, arg0: Self::Output) -> Self::Output { if Self::is_zero(&arg0) { Self::zero(SyntaxKind::ErrorSyntax) } else { self.flatten(SyntaxKind::ErrorSyntax, vec!(arg0)) } } fn make_list_item(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) { Self::zero(SyntaxKind::ListItem) } else { self.flatten(SyntaxKind::ListItem, vec!(arg0, arg1)) } } fn make_enum_class_label_expression(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::EnumClassLabelExpression) } else { self.flatten(SyntaxKind::EnumClassLabelExpression, vec!(arg0, arg1, arg2)) } } fn make_module_declaration(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output, arg4: Self::Output, arg5: Self::Output, arg6: Self::Output, arg7: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) && Self::is_zero(&arg4) && Self::is_zero(&arg5) && Self::is_zero(&arg6) && Self::is_zero(&arg7) { Self::zero(SyntaxKind::ModuleDeclaration) } else { self.flatten(SyntaxKind::ModuleDeclaration, vec!(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7)) } } fn make_module_exports(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) { Self::zero(SyntaxKind::ModuleExports) } else { self.flatten(SyntaxKind::ModuleExports, vec!(arg0, arg1, arg2, arg3)) } } fn make_module_imports(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output, arg3: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) && Self::is_zero(&arg3) { Self::zero(SyntaxKind::ModuleImports) } else { self.flatten(SyntaxKind::ModuleImports, vec!(arg0, arg1, arg2, arg3)) } } fn make_module_membership_declaration(&mut self, arg0: Self::Output, arg1: Self::Output, arg2: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) && Self::is_zero(&arg2) { Self::zero(SyntaxKind::ModuleMembershipDeclaration) } else { self.flatten(SyntaxKind::ModuleMembershipDeclaration, vec!(arg0, arg1, arg2)) } } fn make_package_expression(&mut self, arg0: Self::Output, arg1: Self::Output) -> Self::Output { if Self::is_zero(&arg0) && Self::is_zero(&arg1) { Self::zero(SyntaxKind::PackageExpression) } else { self.flatten(SyntaxKind::PackageExpression, vec!(arg0, arg1)) } } }
OCaml
hhvm/hphp/hack/src/parser/full_fidelity_ast.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 SyntaxError = Full_fidelity_syntax_error module Lint = Lints_core open Hh_prelude open Scoured_comments (* Context of the file being parsed, as (hopefully some day read-only) state. *) type env = { codegen: bool; php5_compat_mode: bool; elaborate_namespaces: bool; include_line_comments: bool; quick_mode: bool; (* Show errors even in quick mode. * Hotfix until we can properly set up saved states to surface parse errors during * typechecking properly. *) show_all_errors: bool; parser_options: ParserOptions.t; file: Relative_path.t; is_systemlib: bool; } [@@deriving show] let make_env ?(codegen = false) ?(php5_compat_mode = false) ?(elaborate_namespaces = true) ?(include_line_comments = false) ?(quick_mode = false) ?(show_all_errors = false) ?(parser_options = ParserOptions.default) ?(is_systemlib = false) (file : Relative_path.t) : env = let parser_options = ParserOptions.with_codegen parser_options codegen in { codegen; php5_compat_mode; elaborate_namespaces; include_line_comments; quick_mode = (not codegen) && quick_mode; show_all_errors; parser_options; file; is_systemlib; } let should_surface_errors env = (* env.show_all_errors is a hotfix until we can retool how saved states handle * parse errors. *) (not env.quick_mode) || env.show_all_errors type aast_result = { fi_mode: FileInfo.mode; ast: (unit, unit) Aast.program; content: string; comments: Scoured_comments.t; } (* TODO: Make these not default to positioned_syntax *) module SourceText = Full_fidelity_source_text (* Creates a relative position out of the error and the given path and source text. *) let pos_of_error path source_text error = SourceText.relative_pos path source_text (SyntaxError.start_offset error) (SyntaxError.end_offset error) let process_scour_comments (env : env) (sc : Scoured_comments.t) = List.iter sc.sc_error_pos ~f:(fun pos -> Errors.add_error Parsing_error.(to_user_error @@ Fixme_format pos)); List.iter sc.sc_bad_ignore_pos ~f:(fun pos -> Errors.add_error Parsing_error.(to_user_error @@ Hh_ignore_comment pos)); Fixme_provider.provide_disallowed_fixmes env.file sc.sc_misuses; if env.quick_mode then Fixme_provider.provide_decl_hh_fixmes env.file sc.sc_fixmes else Fixme_provider.provide_hh_fixmes env.file sc.sc_fixmes let process_lowerer_parsing_errors (env : env) (lowerer_parsing_errors : (Pos.t * string) list) = if should_surface_errors env then List.iter ~f:(fun (pos, msg) -> Errors.add_error Parsing_error.( to_user_error @@ Parsing_error { pos; msg; quickfixes = [] })) lowerer_parsing_errors let process_non_syntax_errors (_ : env) (errors : Errors.error list) = List.iter ~f:Errors.add_error errors let process_lint_errors (_ : env) (errors : Pos.t Lint.t list) = List.iter ~f:Lint.add_lint errors external rust_from_text_ffi : Rust_aast_parser_types.env -> SourceText.t -> (Rust_aast_parser_types.result, Rust_aast_parser_types.error) result = "from_text" (** Note: this doesn't respect deregister_php_stdlib *) external parse_ast_and_decls_ffi : Rust_aast_parser_types.env -> SourceText.t -> (Rust_aast_parser_types.result, Rust_aast_parser_types.error) result * Direct_decl_parser.parsed_file_with_hashes = "hh_parse_ast_and_decls_ffi" let process_syntax_errors (env : env) (source_text : SourceText.t) (errors : Full_fidelity_syntax_error.t list) = let relative_pos = pos_of_error env.file source_text in let pos_of_offsets start_offset end_offset = SourceText.relative_pos env.file source_text start_offset end_offset in let report_error e = let quickfixes = List.map e.Full_fidelity_syntax_error.quickfixes ~f:(fun qf -> let { Full_fidelity_syntax_error.title; edits } = qf in let edits = List.map edits ~f:(fun (start_offset, end_offset, new_text) -> (new_text, pos_of_offsets start_offset end_offset)) in Quickfix.make_with_edits ~title ~edits) in Errors.add_error Parsing_error.( to_user_error @@ Parsing_error { pos = relative_pos e; msg = SyntaxError.message e; quickfixes }) in List.iter ~f:report_error errors let make_rust_env (env : env) : Rust_aast_parser_types.env = Rust_aast_parser_types. { codegen = env.codegen; elaborate_namespaces = env.elaborate_namespaces; php5_compat_mode = env.php5_compat_mode; include_line_comments = env.include_line_comments; quick_mode = env.quick_mode; show_all_errors = env.show_all_errors; is_systemlib = env.is_systemlib; for_debugger_eval = false; parser_options = env.parser_options; scour_comments = true; } let unwrap_rust_parser_result st (rust_result : (Rust_aast_parser_types.result, Rust_aast_parser_types.error) result) : Rust_aast_parser_types.result = match rust_result with | Ok r -> r | Error Rust_aast_parser_types.NotAHackFile -> failwith ("Not a Hack file: " ^ Relative_path.to_absolute (SourceText.file_path st)) | Error (Rust_aast_parser_types.ParserFatal (e, p)) -> raise @@ SyntaxError.ParserFatal (e, p) | Error (Rust_aast_parser_types.Other msg) -> failwith msg let from_text_rust (env : env) (source_text : SourceText.t) : Rust_aast_parser_types.result = let rust_env = make_rust_env env in unwrap_rust_parser_result source_text (rust_from_text_ffi rust_env source_text) (** note: this doesn't respect deregister_php_stdlib *) let ast_and_decls_from_text_rust (env : env) (source_text : SourceText.t) : Rust_aast_parser_types.result * Direct_decl_parser.parsed_file_with_hashes = let rust_env = make_rust_env env in let (ast_result, decls) = parse_ast_and_decls_ffi rust_env source_text in let ast_result = unwrap_rust_parser_result source_text ast_result in (ast_result, decls) let process_lowerer_result (env : env) (source_text : SourceText.t) (r : Rust_aast_parser_types.result) : aast_result = Rust_aast_parser_types.( process_scour_comments env r.scoured_comments; process_syntax_errors env source_text r.syntax_errors; process_lowerer_parsing_errors env r.lowerer_parsing_errors; process_non_syntax_errors env r.errors; process_lint_errors env r.lint_errors; { fi_mode = r.file_mode; ast = r.aast; content = (if env.codegen then "" else SourceText.text source_text); comments = r.scoured_comments; }) let from_text (env : env) (source_text : SourceText.t) : aast_result = process_lowerer_result env source_text (from_text_rust env source_text) (** note: this doesn't respect deregister_php_stdlib *) let ast_and_decls_from_text (env : env) (source_text : SourceText.t) : aast_result * Direct_decl_parser.parsed_file_with_hashes = let (ast_result, decls) = ast_and_decls_from_text_rust env source_text in let ast_result = process_lowerer_result env source_text ast_result in (ast_result, decls) let from_file (env : env) : aast_result = let source_text = SourceText.from_file env.file in from_text env source_text (*****************************************************************************( * Backward compatibility matter (should be short-lived) )*****************************************************************************) let legacy (x : aast_result) : Parser_return.t = { Parser_return.file_mode = Some x.fi_mode; Parser_return.comments = x.comments.sc_comments; Parser_return.ast = x.ast; Parser_return.content = x.content; } let from_source_text_with_legacy (env : env) (source_text : Full_fidelity_source_text.t) : Parser_return.t = legacy @@ from_text env source_text (** note: this doesn't respect deregister_php_stdlib *) let ast_and_decls_from_source_text_with_legacy (env : env) (source_text : Full_fidelity_source_text.t) : Parser_return.t * Direct_decl_parser.parsed_file_with_hashes = let (ast_result, decls) = ast_and_decls_from_text env source_text in (legacy ast_result, decls) let from_text_with_legacy (env : env) (content : string) : Parser_return.t = let source_text = SourceText.make env.file content in from_source_text_with_legacy env source_text let from_file_with_legacy env = legacy (from_file env) (******************************************************************************( * For cut-over purposes only; this should be removed as soon as Parser_hack * is removed. )******************************************************************************) let defensive_program ?(quick = false) ?(show_all_errors = false) ?(elaborate_namespaces = true) ?(include_line_comments = false) parser_options fn content = try let source = Full_fidelity_source_text.make fn content in let env = make_env ~quick_mode:quick ~show_all_errors ~elaborate_namespaces ~parser_options ~include_line_comments fn in legacy @@ from_text env source with | e -> Rust_pointer.free_leaked_pointer (); (* If we fail to lower, try to just make a source text and get the file mode *) (* If even THAT fails, we just have to give up and return an empty php file*) let mode = try let source = Full_fidelity_source_text.make fn content in Full_fidelity_parser.parse_mode source with | _ -> None in let err = Exn.to_string e in let fn = Relative_path.suffix fn in (* If we've already found a parsing error, it's okay for lowering to fail *) if not (Errors.currently_has_errors ()) then Hh_logger.log "Warning, lowering failed for %s\n - error: %s\n" fn err; { Parser_return.file_mode = mode; Parser_return.comments = []; Parser_return.ast = []; Parser_return.content; } let defensive_from_file ?quick ?show_all_errors popt fn = let content = try Sys_utils.cat (Relative_path.to_absolute fn) with | _ -> "" in defensive_program ?quick ?show_all_errors popt fn content (** note: this doesn't respect deregister_php_stdlib *) let ast_and_decls_from_file ?(quick = false) ?(show_all_errors = false) parser_options fn = let content = try Sys_utils.cat (Relative_path.to_absolute fn) with | _ -> "" in try let source = Full_fidelity_source_text.make fn content in let env = make_env ~quick_mode:quick ~show_all_errors ~elaborate_namespaces:true ~parser_options ~include_line_comments:false fn in ast_and_decls_from_source_text_with_legacy env source with | e -> (* If we fail to lower, try to just make a source text and get the file mode *) (* If even THAT fails, we just have to give up and return an empty php file*) let mode = try let source = Full_fidelity_source_text.make fn content in Full_fidelity_parser.parse_mode source with | _ -> None in let err = Exn.to_string e in let fn = Relative_path.suffix fn in (* If we've already found a parsing error, it's okay for lowering to fail *) if not (Errors.currently_has_errors ()) then Hh_logger.log "Warning, lowering failed for %s\n - error: %s\n" fn err; ( { Parser_return.file_mode = mode; Parser_return.comments = []; Parser_return.ast = []; Parser_return.content; }, Direct_decl_parser. { pfh_mode = mode; pfh_hash = Int64.zero; pfh_decls = [] } )
OCaml Interface
hhvm/hphp/hack/src/parser/full_fidelity_ast.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. * *) (** * The `env` of the lowerer is "full request." It provides all the settings the * lowerer needs to produce an AST. *) type env [@@deriving show] val make_env (* Optional parts *) : ?codegen:bool -> ?php5_compat_mode:bool -> ?elaborate_namespaces:bool -> ?include_line_comments:bool -> ?quick_mode:bool -> ?show_all_errors:bool -> ?parser_options:ParserOptions.t (* Required parts *) -> ?is_systemlib:bool -> Relative_path.t -> env val from_source_text_with_legacy : env -> Full_fidelity_source_text.t -> Parser_return.t val from_text_with_legacy : env -> string -> Parser_return.t (** * Here only for backward compatibility. Consider these deprecated. *) val from_file_with_legacy : env -> Parser_return.t val defensive_program : ?quick:bool -> ?show_all_errors:bool -> ?elaborate_namespaces:bool -> ?include_line_comments:bool -> ParserOptions.t -> Relative_path.t -> string -> Parser_return.t val defensive_from_file : ?quick:bool -> ?show_all_errors:bool -> ParserOptions.t -> Relative_path.t -> Parser_return.t (* from_text_rust are only used for testing *) val from_text_rust : env -> Full_fidelity_source_text.t -> Rust_aast_parser_types.result (** note: this doesn't respect deregister_php_stdlib *) val ast_and_decls_from_file : ?quick:bool -> ?show_all_errors:bool -> ParserOptions.t -> Relative_path.t -> Parser_return.t * Direct_decl_parser.parsed_file_with_hashes
OCaml
hhvm/hphp/hack/src/parser/full_fidelity_editable_positioned_original_source_data.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. * *) open Sexplib.Std (** * SourceData represents information with relation to the original SourceText. *) module SourceText = Full_fidelity_source_text module Syntax = Full_fidelity_positioned_syntax module Token = Full_fidelity_positioned_token module Trivia = Full_fidelity_positioned_trivia (** * Data about the token with respect to the original source text. *) type t = { source_text: SourceText.t; offset: int; (* Beginning of first trivia *) leading_width: int; width: int; (* Width of actual token, not counting trivia *) trailing_width: int; leading: Trivia.t list; trailing: Trivia.t list; } [@@deriving show, eq, sexp_of] let empty = { source_text = SourceText.empty; offset = 0; leading_width = 0; width = 0; trailing_width = 0; leading = []; trailing = []; } let from_positioned_token positioned_token = { source_text = Token.source_text positioned_token; offset = Token.leading_start_offset positioned_token; leading_width = Token.leading_width positioned_token; width = Token.width positioned_token; trailing_width = Token.trailing_width positioned_token; leading = Token.leading positioned_token; trailing = Token.trailing positioned_token; } let from_positioned_syntax syntax = { source_text = Syntax.source_text syntax; offset = Syntax.leading_start_offset syntax; leading_width = Syntax.leading_width syntax; width = Syntax.width syntax; trailing_width = Syntax.trailing_width syntax; leading = []; trailing = []; } let source_text data = data.source_text let leading_width data = data.leading_width let width data = data.width let trailing_width data = data.trailing_width let leading_start_offset data = data.offset let leading data = data.leading let with_leading leading data = (* TODO: Do we need to update leading_width and offset? *) { data with leading } let trailing data = data.trailing let with_trailing trailing data = (* TODO: Do we need to update trailing_width and offset? *) { data with trailing } let start_offset data = leading_start_offset data + leading_width data let end_offset data = let w = width data - 1 in let w = if w < 0 then 0 else w in start_offset data + w let full_width data = leading_width data + width data + trailing_width data let text data = SourceText.sub (source_text data) (start_offset data) (width data) (** * Merges two SourceDatas by computing the span between them. * * The resulting SourceData will have: * These properties of the beginning SourceData: * - SourceText * - offset * - leading_width * - leading * These properties of the ending SourceData: * - trailing_width * - trailing * * The width will be computed as the distance from the beginning SourceData's * start_offset to the ending SourceData's end_offset. *) let spanning_between b e = { source_text = b.source_text; offset = b.offset; leading_width = b.leading_width; width = end_offset e + 1 - start_offset b; trailing_width = e.trailing_width; leading = b.leading; trailing = e.trailing; } let to_json data = Hh_json.( JSON_Object [ ("offset", int_ data.offset); ("leading_width", int_ data.leading_width); ("width", int_ data.width); ("trailing_width", int_ data.trailing_width); ])
OCaml
hhvm/hphp/hack/src/parser/full_fidelity_editable_positioned_syntax.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. * *) (** * An EditablePositionedSyntax represents a syntax that comes from a positioned * source but may have been modified. The syntax may have had its children * changed, or may have been moved to a new location in the AST. An * EditablePositionedSyntax falls into one of these categories: * * - Positioned. The syntax was positioned in the original source text. It or * its children may have been modified. * - Synthetic. The syntax never existed in the original SourceText. It was * synthesized during the AST computation process (colloquially, * "lowering"). Note that this does not imply that all of its children are * synthetic. *) open Hh_prelude module Token = Full_fidelity_editable_positioned_token module PositionedSyntax = Full_fidelity_positioned_syntax module SourceData = Full_fidelity_editable_positioned_original_source_data module SourceText = Full_fidelity_source_text module Value = struct type t = | Positioned of SourceData.t | Synthetic [@@deriving show, eq, sexp_of] let from_positioned_syntax syntax = Positioned (SourceData.from_positioned_syntax syntax) let from_token token = match token.Token.token_data with | Token.Original original_source_data | Token.SynthesizedFromOriginal (_, original_source_data) -> Positioned original_source_data | Token.Synthetic _ -> Synthetic let to_json value = Hh_json.( SourceData.( match value with | Positioned { offset; leading_width; width; trailing_width; _ } -> JSON_Object [ ("offset", int_ offset); ("leading_width", int_ leading_width); ("width", int_ width); ("trailing_width", int_ trailing_width); ] | Synthetic -> JSON_String "synthetic")) end module SyntaxWithToken = Full_fidelity_syntax.WithToken (Token) module Syntax = SyntaxWithToken.WithSyntaxValue (Value) include Syntax (** * Recursively reconstructs a PositionedSyntax as a hierarchy of * EditablePositionedSyntaxes, each of which is Positioned. *) let rec from_positioned_syntax node = let syntax = match PositionedSyntax.syntax node with | PositionedSyntax.Token token -> Token (Token.from_positioned_token token) | _ -> node |> PositionedSyntax.children |> List.map ~f:from_positioned_syntax |> syntax_from_children (PositionedSyntax.kind node) in make syntax (Value.from_positioned_syntax node) let synthesize_from editable_positioned_syntax syntax = { editable_positioned_syntax with syntax } (** * Computes the text from constituent tokens. *) let text node = match all_tokens node with | [] -> "" | [hd] -> Token.text hd | hd :: tl -> (match List.rev tl with | [] -> assert false | last :: interior_tokens_rev -> let interior_full_text = interior_tokens_rev |> List.rev |> List.map ~f:Token.full_text |> String.concat ~sep:"" in Token.text hd ^ Token.trailing_text hd ^ interior_full_text ^ Token.leading_text last ^ Token.text last) let leading_text node = Option.value_map ~default:"" ~f:Token.leading_text (leading_token node) let trailing_text node = Option.value_map ~default:"" ~f:Token.trailing_text (trailing_token node) let full_text node = node |> all_tokens |> List.map ~f:Token.full_text |> String.concat ~sep:"" let original_source_data_or_default node = match value node with | Value.Positioned source_data -> source_data | Value.Synthetic -> SourceData.empty let source_text node = SourceData.source_text (original_source_data_or_default node) let leading_width node = SourceData.leading_width (original_source_data_or_default node) let width node = SourceData.width (original_source_data_or_default node) let trailing_width node = SourceData.trailing_width (original_source_data_or_default node) let full_width node = SourceData.full_width (original_source_data_or_default node) let leading_start_offset node = SourceData.leading_start_offset (original_source_data_or_default node) let start_offset node = SourceData.start_offset (original_source_data_or_default node) let end_offset node = SourceData.end_offset (original_source_data_or_default node) let trailing_start_offset node = leading_start_offset node + leading_width node + width node let offset node = match value node with | Value.Positioned source_data -> Some (SourceData.start_offset source_data) | Value.Synthetic -> None let position file node = match value node with | Value.Positioned source_data -> let source_text = SourceData.source_text source_data in let start_offset = SourceData.start_offset source_data in let end_offset = SourceData.end_offset source_data in Some (SourceText.relative_pos file source_text start_offset end_offset) | Value.Synthetic -> None let position_exclusive file node = match value node with | Value.Positioned source_data -> let source_text = SourceData.source_text source_data in let start_offset = SourceData.start_offset source_data in let end_offset = SourceData.end_offset source_data + 1 in Some (SourceText.relative_pos file source_text start_offset end_offset) | Value.Synthetic -> None let extract_text node = Some (text node) module ValueBuilder = struct open Value let value_from_children _source _offset _kind = function | [] -> (* Missing node case: we consider Missing to be Synthetic. *) Synthetic | hd :: tl -> (match (value hd, Option.map ~f:value (List.last tl)) with | (_, None) -> (* Single node case: use that node's value. *) value hd | (Positioned b, Some (Positioned e)) -> (* First and last child are positioned: Reconstruct source data. *) Positioned (SourceData.spanning_between b e) | (_, Some _) -> (* Otherwise: Not enough information to position this node. *) Synthetic) let value_from_token token = from_token token let value_from_syntax syntax = let pr first last = match (first, last) with | (Value.Synthetic, Value.Synthetic) -> Synthetic | (f, Value.Synthetic) -> f | (Positioned f, Positioned l) -> Positioned (SourceData.spanning_between f l) | (_, _) -> Synthetic in let folder (sum : Value.t * Value.t) child : Value.t * Value.t = match sum with | (Value.Synthetic, Value.Synthetic) -> (value child, Value.Synthetic) | (f, _) -> (f, value child) in let (first, last) = Syntax.fold_over_children folder (Value.Synthetic, Value.Synthetic) syntax in pr first last end (* TODO: This code is duplicated in the positioned syntax; consider pulling it out into its own module. *) (* Takes a node and an offset; produces the descent through the parse tree to that position. *) let parentage node position = let rec aux nodes position acc = match nodes with | [] -> acc | h :: t -> let width = full_width h in if position < width then aux (children h) position (h :: acc) else aux t (position - width) acc in aux [node] position [] let is_in_body node position = let rec aux parents = match parents with | [] -> false | h1 :: h2 :: _ when is_compound_statement h1 && (is_methodish_declaration h2 || is_function_declaration h2) -> true | _ :: rest -> aux rest in let parents = parentage node position in aux parents let is_synthetic node = match value node with | Value.Synthetic -> true | Value.Positioned _ -> false include Syntax.WithValueBuilder (ValueBuilder) let rust_parse _ _ = failwith "not implemented" let rust_parser_errors _ _ _ = failwith "not implemented"
OCaml
hhvm/hphp/hack/src/parser/full_fidelity_editable_positioned_token.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. * *) open Sexplib.Std (** * An EditablePositionedToken represents a token that comes from a positioned * source but may have been modified. The token may have had its text or kind * changed, or may have been moved to a new location in the AST. An * EditablePositionedToken falls into one of these categories: * * - Original. The token was positioned in the original source text and not * modified. * - SynthesizedFromOriginal. The token was positioned in the original * SourceText and modified. It may have had its text or kind changed, and it * may now be positioned in a location that does not logically correspond to * its location in the original SourceText. * - Synthetic. The token never existed in the original SourceText. It was * synthesized during the AST computation process (colloquially, * "lowering"). *) module PositionedToken = Full_fidelity_positioned_token module SourceData = Full_fidelity_editable_positioned_original_source_data module TokenKind = Full_fidelity_token_kind module Trivia = Full_fidelity_positioned_trivia (** * Data about the token with respect to the original source text. *) type synthetic_token_data = { text: string } [@@deriving show, eq, sexp_of] type token_data = | Original of SourceData.t | SynthesizedFromOriginal of synthetic_token_data * SourceData.t | Synthetic of synthetic_token_data [@@deriving show, eq, sexp_of] (** * Data common to all EditablePositionedTokens. *) type t = { kind: TokenKind.t; leading_text: string; trailing_text: string; token_data: token_data; } [@@deriving show, eq, sexp_of] let from_positioned_token positioned_token = { kind = PositionedToken.kind positioned_token; leading_text = PositionedToken.leading_text positioned_token; trailing_text = PositionedToken.trailing_text positioned_token; token_data = Original (SourceData.from_positioned_token positioned_token); } let make kind source_text offset width leading trailing = from_positioned_token (PositionedToken.make kind source_text offset width leading trailing) (** * Retains the original_source_data and trivia from the existing * EditablePositionedToken if present. *) let synthesize_from editable_positioned_token kind text = let synthetic_token_data = { text } in let token_data = match editable_positioned_token.token_data with | Original original_source_data | SynthesizedFromOriginal (_, original_source_data) -> SynthesizedFromOriginal (synthetic_token_data, original_source_data) | Synthetic _ -> Synthetic synthetic_token_data in { editable_positioned_token with kind; token_data } let synthesize_new kind text leading_text trailing_text = { kind; leading_text; trailing_text; token_data = Synthetic { text } } let text token = match token.token_data with | Original original_source_data -> SourceData.text original_source_data | SynthesizedFromOriginal ({ text; _ }, _) | Synthetic { text; _ } -> text let leading_text token = token.leading_text let trailing_text token = token.trailing_text let filter_leading_trivia_by_kind token kind = match token.token_data with | Original orig_token | SynthesizedFromOriginal (_, orig_token) -> List.filter (fun t -> Trivia.kind t = kind) (SourceData.leading orig_token) | _ -> [] let has_trivia_kind token kind = match token.token_data with | Original orig_token | SynthesizedFromOriginal (_, orig_token) -> let kind_of = Trivia.kind in List.exists (fun t -> kind_of t = kind) (SourceData.leading orig_token) || List.exists (fun t -> kind_of t = kind) (SourceData.trailing orig_token) | _ -> (* Assume we don't introduce well-formed trivia *) false let full_text token = leading_text token ^ text token ^ trailing_text token let original_source_data_or_default token = match token.token_data with | Original original_source_data | SynthesizedFromOriginal (_, original_source_data) -> original_source_data | Synthetic _ -> SourceData.empty let kind token = token.kind let source_text token = SourceData.source_text (original_source_data_or_default token) let leading_width token = SourceData.leading_width (original_source_data_or_default token) let width token = SourceData.width (original_source_data_or_default token) let trailing_width token = SourceData.trailing_width (original_source_data_or_default token) let leading_start_offset token = SourceData.leading_start_offset (original_source_data_or_default token) let start_offset token = SourceData.start_offset (original_source_data_or_default token) let leading token = SourceData.leading (original_source_data_or_default token) let trailing token = SourceData.trailing (original_source_data_or_default token) let with_updated_original_source_data token update_original_source_data = let token_data = match token.token_data with | Original original_source_data -> Original (update_original_source_data original_source_data) | SynthesizedFromOriginal (synthetic_token_data, original_source_data) -> SynthesizedFromOriginal (synthetic_token_data, update_original_source_data original_source_data) | Synthetic _ -> token.token_data in { token with token_data } let with_leading leading token = with_updated_original_source_data token (SourceData.with_leading leading) let with_kind token kind = { token with kind } let with_trailing trailing token = with_updated_original_source_data token (SourceData.with_trailing trailing) let with_trailing_text trailing_text token = { token with trailing_text } let concatenate b e = let token_data = match (b.token_data, e.token_data) with | (Original b_source_data, Original e_source_data) -> Original (SourceData.spanning_between b_source_data e_source_data) | ( (SynthesizedFromOriginal (_, b_source_data) | Original b_source_data), (SynthesizedFromOriginal (_, e_source_data) | Original e_source_data) ) -> SynthesizedFromOriginal ( { text = text b ^ text e }, SourceData.spanning_between b_source_data e_source_data ) | (Synthetic _, _) | (_, Synthetic _) -> Synthetic { text = text b ^ text e } in { kind = kind b; leading_text = leading_text b; trailing_text = trailing_text e; token_data; } let trim_left ~n t = with_updated_original_source_data t SourceData.( fun t -> { t with leading_width = leading_width t + n; width = width t - n }) let trim_right ~n t = with_updated_original_source_data t SourceData.( fun t -> { t with trailing_width = trailing_width t + n; width = width t - n }) let to_json token = let original_source_data = original_source_data_or_default token in Hh_json.( JSON_Object [ ("kind", JSON_String (TokenKind.to_string token.kind)); ("leading_text", JSON_String token.leading_text); ("trailing_text", JSON_String token.trailing_text); ("original_source_data", SourceData.to_json original_source_data); ("text", JSON_String (text token)); ])
OCaml
hhvm/hphp/hack/src/parser/full_fidelity_editable_syntax.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. * *) (** Editable syntax tree * * Every token and trivia in the tree knows its text. Therefore we can add * new nodes without having to back them with a source text. *) module Token = Full_fidelity_editable_token module Trivia = Full_fidelity_editable_trivia module SyntaxKind = Full_fidelity_syntax_kind module TokenKind = Full_fidelity_token_kind module SyntaxWithToken = Full_fidelity_syntax.WithToken (Token) (** * Ironically, an editable syntax tree needs even less per-node information * than the "positioned" syntax tree, which needs to know the width of the node. **) module Value = struct type t = NoValue [@@deriving show, eq, sexp_of] let to_json _value = Hh_json.(JSON_Object []) end module EditableSyntax = SyntaxWithToken.WithSyntaxValue (Value) module EditableValueBuilder = struct let value_from_children _ _ _ _ = Value.NoValue let value_from_token _ = Value.NoValue let value_from_syntax _ = Value.NoValue end include EditableSyntax include EditableSyntax.WithValueBuilder (EditableValueBuilder) let text node = let buffer = Buffer.create 100 in let aux token = Buffer.add_string buffer (Token.full_text token) in List.iter aux (all_tokens node); Buffer.contents buffer let extract_text node = Some (text node) let width node = String.length (text node) (* Takes a node and an offset; produces the descent through the parse tree to that position. *) let parentage root position = let rec aux nodes position acc = match nodes with | [] -> acc | h :: t -> let width = String.length @@ text h in if position < width then aux (children h) position (h :: acc) else aux t (position - width) acc in aux [root] position [] let leading_trivia node = let token = leading_token node in match token with | None -> [] | Some t -> Token.leading t let leading_width node = leading_trivia node |> List.fold_left (fun sum t -> sum + Trivia.width t) 0 let trailing_trivia node = let token = trailing_token node in match token with | None -> [] | Some t -> Token.trailing t let trailing_width node = trailing_trivia node |> List.fold_left (fun sum t -> sum + Trivia.width t) 0 let full_width node = leading_width node + width node + trailing_width node let is_in_body node position = let rec aux parents = match parents with | [] -> false | h1 :: h2 :: _ when is_compound_statement h1 && (is_methodish_declaration h2 || is_function_declaration h2) -> true | _ :: rest -> aux rest in let parents = parentage node position in aux parents (* This function takes a parse tree and renders it in the GraphViz DOT language; this is a small domain-specific language for visualizing graphs. You can use www.webgraphviz.com to render it in a browser, or the "dot" command line tool to turn DOT text into image files. Edge labels can make the graph hard to read, so they can be enabled or disabled as you like. Use hh_parse --full-fidelity-dot or --full-fidelity-dot-edges to parse a Hack file and display it in DOT form. TODO: There's nothing here that's unique to editable trees; this could be auto-generated as part of full_fidelity_syntax.ml. *) let to_dot node with_labels = (* returns new current_id, accumulator *) let rec aux node current_id parent_id edge_label acc = let kind = SyntaxKind.to_string (kind node) in let new_id = current_id + 1 in let label = if with_labels then Printf.sprintf " [label=\"%s\"]" edge_label else "" in let new_edge = Printf.sprintf " %d -> %d%s" parent_id current_id label in match node.syntax with | Token t -> (* TODO: Trivia *) let kind = TokenKind.to_string (Token.kind t) in let new_node = Printf.sprintf " %d [label=\"%s\"];" current_id kind in let new_acc = new_edge :: new_node :: acc in (new_id, new_acc) | SyntaxList x -> let new_node = Printf.sprintf " %d [label=\"%s\"];" current_id kind in let new_acc = new_edge :: new_node :: acc in let folder (c, a) n = aux n c current_id "" a in List.fold_left folder (new_id, new_acc) x | _ -> let folder (c, a) n l = aux n c current_id l a in let new_node = Printf.sprintf " %d [label=\"%s\"];" current_id kind in let new_acc = new_edge :: new_node :: acc in List.fold_left2 folder (new_id, new_acc) (children node) (children_names node) in let (_, acc) = aux node 1001 1000 "" [" 1000 [label=\"root\"]"; "digraph {"] in let acc = "}" :: acc in String.concat "\n" (List.rev acc) let offset _ = None let position _ _ = None let to_json ?with_value:_ ?ignore_missing:_ node = let version = Full_fidelity_schema.full_fidelity_schema_version_number in let tree = EditableSyntax.to_json node in Hh_json.JSON_Object [("parse_tree", tree); ("version", Hh_json.JSON_String version)] let rust_parse _ _ = failwith "not implemented" let rust_parser_errors _ _ _ = failwith "not implemented"
OCaml
hhvm/hphp/hack/src/parser/full_fidelity_editable_token.ml
(* * Copyright (c) 2016, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Sexplib.Std (** * An editable token contains the text of the token; these tokens are not * backed by a source text, like the positioned tokens are. *) module Trivia = Full_fidelity_editable_trivia module SourceText = Full_fidelity_source_text module TokenKind = Full_fidelity_token_kind type t = { kind: TokenKind.t; text: string; leading: Trivia.t list; trailing: Trivia.t list; } [@@deriving show, eq, sexp_of] let create kind text leading trailing = { kind; text; leading; trailing } let make kind source_text offset width leading trailing = let leading_width = List.fold_left (fun sum t -> sum + Trivia.width t) 0 leading in let text = SourceText.sub source_text (offset + leading_width) width in { kind; text; leading; trailing } let leading_width token = let folder sum t = sum + Trivia.width t in List.fold_left folder 0 token.leading let trailing_width token = let folder sum t = sum + Trivia.width t in List.fold_left folder 0 token.trailing let width token = String.length token.text let full_width token = leading_width token + width token + trailing_width token let kind token = token.kind let with_kind token kind = { token with kind } let leading token = token.leading let with_leading leading token = { token with leading } let trailing token = token.trailing let with_trailing trailing token = { token with trailing } let filter_leading_trivia_by_kind token kind = token.leading |> List.filter (fun trivia -> trivia.Trivia.kind = kind) let has_trivia_kind token kind = [token.leading; token.trailing] |> List.exists (List.exists (fun trivia -> trivia.Trivia.kind = kind)) let text token = token.text let leading_text token = Trivia.text_from_trivia_list (leading token) let trailing_text token = Trivia.text_from_trivia_list (trailing token) let full_text token = leading_text token ^ text token ^ trailing_text token let to_json token = Hh_json.( JSON_Object [ ("kind", JSON_String (TokenKind.to_string token.kind)); ("text", JSON_String token.text); ("leading", JSON_Array (List.map Trivia.to_json token.leading)); ("trailing", JSON_Array (List.map Trivia.to_json token.trailing)); ]) let source_text _ = raise (Invalid_argument "Editable token doesn't support source_text") let leading_start_offset _ = raise (Invalid_argument "Editable token doesn't support leading_start_offset")
OCaml
hhvm/hphp/hack/src/parser/full_fidelity_editable_trivia.ml
(* * Copyright (c) 2016, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Sexplib.Std (** * An editable trivia contains the text of the trivia; these trivia are not * backed by a source text, like the positioned trivia are. *) module TriviaKind = Full_fidelity_trivia_kind module PositionedTrivia = Full_fidelity_positioned_trivia module SourceText = Full_fidelity_source_text type t = { kind: TriviaKind.t; text: string; } [@@deriving show, eq, sexp_of] let make_ignore_error source_text offset width = { kind = TriviaKind.IgnoreError; text = SourceText.sub source_text offset width; } let make_extra_token_error source_text offset width = { kind = TriviaKind.ExtraTokenError; text = SourceText.sub source_text offset width; } let make_fallthrough source_text offset width = { kind = TriviaKind.FallThrough; text = SourceText.sub source_text offset width; } let make_fix_me source_text offset width = { kind = TriviaKind.FixMe; text = SourceText.sub source_text offset width } let make_whitespace source_text offset width = { kind = TriviaKind.WhiteSpace; text = SourceText.sub source_text offset width; } let make_eol source_text offset width = { kind = TriviaKind.EndOfLine; text = SourceText.sub source_text offset width; } let make_single_line_comment source_text offset width = { kind = TriviaKind.SingleLineComment; text = SourceText.sub source_text offset width; } let make_delimited_comment source_text offset width = { kind = TriviaKind.DelimitedComment; text = SourceText.sub source_text offset width; } (* HackFormat is using this to create trivia. It's deeply manipulating strings * so it was easier to create this helper function to avoid ad-hoc * SourceText construction.*) let create_delimited_comment text = { kind = TriviaKind.DelimitedComment; text } let width trivia = String.length trivia.text let kind trivia = trivia.kind let text trivia = trivia.text let text_from_trivia_list trivia_list = (* TODO: Better way to accumulate a string? *) let folder str trivia = str ^ text trivia in List.fold_left folder "" trivia_list let from_positioned source_text positioned_trivia offset = let kind = PositionedTrivia.kind positioned_trivia in let width = PositionedTrivia.width positioned_trivia in let text = SourceText.sub source_text offset width in { kind; text } let from_positioned_list source_text ts offset = let rec aux acc ts offset = match ts with | [] -> acc | h :: t -> let et = from_positioned source_text h offset in aux (et :: acc) t (offset + PositionedTrivia.width h) in List.rev (aux [] ts offset) let to_json trivia = Hh_json.( JSON_Object [ ("kind", JSON_String (TriviaKind.to_string trivia.kind)); ("text", JSON_String trivia.text); ])
OCaml
hhvm/hphp/hack/src/parser/full_fidelity_operator.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 TokenKind = Full_fidelity_token_kind include Full_fidelity_operator_generated.Impl type assoc = | LeftAssociative | RightAssociative | NotAssociative (* helper functions for Rust forwarding *) external rust_precedence_helper : t -> int = "rust_precedence_helper" external rust_precedence_for_assignment_in_expressions_helper : unit -> int = "rust_precedence_for_assignment_in_expressions_helper" external rust_associativity_helper : t -> assoc = "rust_associativity_helper" (* NOTE: rust_precedence_helper does not use Full_fidelity_parser_env '_env'. * This call must be updated if operator::precedence in operator.rs starts to depend on * the env parameter *) let precedence _env operator = rust_precedence_helper operator let precedence_for_assignment_in_expressions : int = rust_precedence_for_assignment_in_expressions_helper () (* NOTE: rust_associativity_helper does not use Full_fidelity_parser_env '_env'. * This call must be updated if operator::associativity in operator.rs starts to depend on * the env parameter *) let associativity _env operator = rust_associativity_helper operator external prefix_unary_from_token : TokenKind.t -> t = "prefix_unary_from_token" (* Is this a token that can appear after an expression? *) external is_trailing_operator_token : TokenKind.t -> bool = "is_trailing_operator_token" external trailing_from_token : TokenKind.t -> t = "trailing_from_token" external is_binary_operator_token : TokenKind.t -> bool = "is_binary_operator_token" external is_assignment : t -> bool = "is_assignment" external is_comparison : t -> bool = "is_comparison"
OCaml Interface
hhvm/hphp/hack/src/parser/full_fidelity_operator.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. * *) module TokenKind : sig type t = Full_fidelity_token_kind.t end include Full_fidelity_operator_generated.Sig type assoc = | LeftAssociative | RightAssociative | NotAssociative val precedence : Full_fidelity_parser_env.t -> t -> int val precedence_for_assignment_in_expressions : int val associativity : Full_fidelity_parser_env.t -> t -> assoc val prefix_unary_from_token : TokenKind.t -> t val is_trailing_operator_token : TokenKind.t -> bool val trailing_from_token : TokenKind.t -> t val is_binary_operator_token : TokenKind.t -> bool val is_assignment : t -> bool val is_comparison : t -> bool
OCaml
hhvm/hphp/hack/src/parser/full_fidelity_operator_generated.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. An additional * directory. * ** * * THIS FILE IS @generated; DO NOT EDIT IT * To regenerate this file, run * * buck run //hphp/hack/src:generate_full_fidelity * ** * *) module type Sig = sig type t = | DollarOperator | ScopeResolutionOperator | IndexingOperator | NullSafeMemberSelectionOperator | MemberSelectionOperator | NewOperator | FunctionCallOperator | CloneOperator | PostfixIncrementOperator | PostfixDecrementOperator | PrefixIncrementOperator | PrefixDecrementOperator | ExponentOperator | ErrorControlOperator | CastOperator | NullableAsOperator | IsOperator | InstanceofOperator | AsOperator | UpcastOperator | UnaryPlusOperator | UnaryMinusOperator | NotOperator | LogicalNotOperator | RemainderOperator | MultiplicationOperator | DivisionOperator | SubtractionOperator | ConcatenationOperator | AdditionOperator | RightShiftOperator | LeftShiftOperator | SpaceshipOperator | LessThanOrEqualOperator | LessThanOperator | GreaterThanOrEqualOperator | GreaterThanOperator | StrictNotEqualOperator | StrictEqualOperator | NotEqualOperator | EqualOperator | AndOperator | ExclusiveOrOperator | OrOperator | LogicalAndOperator | LogicalOrOperator | CoalesceOperator | DegenerateConditionalOperator | ConditionalQuestionOperator | ConditionalColonOperator | PipeOperator | SubtractionAssignmentOperator | RightShiftAssignmentOperator | RemainderAssignmentOperator | OrAssignmentOperator | MultiplicationAssignmentOperator | LeftShiftAssignmentOperator | ExponentiationAssignmentOperator | ExclusiveOrAssignmentOperator | DivisionAssignmentOperator | ConcatenationAssignmentOperator | CoalesceAssignmentOperator | AssignmentOperator | AndAssignmentOperator | AdditionAssignmentOperator | PrintOperator | RequireOperator | RequireOnceOperator | IncludeOperator | IncludeOnceOperator | AwaitOperator | ReadonlyOperator | EnumClassLabelOperator | PackageOperator end module Impl : Sig = struct type t = | DollarOperator | ScopeResolutionOperator | IndexingOperator | NullSafeMemberSelectionOperator | MemberSelectionOperator | NewOperator | FunctionCallOperator | CloneOperator | PostfixIncrementOperator | PostfixDecrementOperator | PrefixIncrementOperator | PrefixDecrementOperator | ExponentOperator | ErrorControlOperator | CastOperator | NullableAsOperator | IsOperator | InstanceofOperator | AsOperator | UpcastOperator | UnaryPlusOperator | UnaryMinusOperator | NotOperator | LogicalNotOperator | RemainderOperator | MultiplicationOperator | DivisionOperator | SubtractionOperator | ConcatenationOperator | AdditionOperator | RightShiftOperator | LeftShiftOperator | SpaceshipOperator | LessThanOrEqualOperator | LessThanOperator | GreaterThanOrEqualOperator | GreaterThanOperator | StrictNotEqualOperator | StrictEqualOperator | NotEqualOperator | EqualOperator | AndOperator | ExclusiveOrOperator | OrOperator | LogicalAndOperator | LogicalOrOperator | CoalesceOperator | DegenerateConditionalOperator | ConditionalQuestionOperator | ConditionalColonOperator | PipeOperator | SubtractionAssignmentOperator | RightShiftAssignmentOperator | RemainderAssignmentOperator | OrAssignmentOperator | MultiplicationAssignmentOperator | LeftShiftAssignmentOperator | ExponentiationAssignmentOperator | ExclusiveOrAssignmentOperator | DivisionAssignmentOperator | ConcatenationAssignmentOperator | CoalesceAssignmentOperator | AssignmentOperator | AndAssignmentOperator | AdditionAssignmentOperator | PrintOperator | RequireOperator | RequireOnceOperator | IncludeOperator | IncludeOnceOperator | AwaitOperator | ReadonlyOperator | EnumClassLabelOperator | PackageOperator end
OCaml
hhvm/hphp/hack/src/parser/full_fidelity_parser.ml
(* * Copyright (c) 2016, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Sexplib.Std module Env = Full_fidelity_parser_env module type SC_S = SmartConstructors.SmartConstructors_S module type SCWithToken_S = SmartConstructorsWrappers.SyntaxKind_S [@@@ocaml.warning "-60"] (* https://caml.inria.fr/mantis/view.php?id=7522 *) module WithSyntax (Syntax : Syntax_sig.Syntax_S) = struct module WithSmartConstructors (SCI : SC_S with module Token = Syntax.Token) : sig type t [@@deriving sexp_of] val make : Env.t -> Full_fidelity_source_text.t -> t val errors : t -> Full_fidelity_syntax_error.t list val env : t -> Env.t val sc_state : t -> SCI.t val parse_script : t -> t * SCI.r * Rust_pointer.t option end = struct module SCWithToken = SmartConstructorsWrappers.SyntaxKind (SCI) module SourceText = Full_fidelity_source_text module SyntaxError = Full_fidelity_syntax_error type t = { text: SourceText.t; errors: SyntaxError.t list; env: Env.t; sc_state: SCWithToken.t; } [@@deriving sexp_of] let make (env : Env.t) text = { text; errors = []; env; sc_state = SCWithToken.initial_state env } let errors parser = parser.errors let env parser = parser.env let sc_state parser = parser.sc_state let rust_parse_script parser = let (sc_state, root, errors, rust_tree) = SCI.rust_parse parser.text parser.env in (match rust_tree with | Some tree -> Rust_pointer.register_leaked_pointer tree | None -> ()); ({ parser with errors; sc_state }, root, rust_tree) let parse_script parser = rust_parse_script parser end module SC = SyntaxSmartConstructors.WithSyntax (Syntax) include WithSmartConstructors (SC) end let parse_mode = Rust_parser_ffi.parse_mode let () = Rust_parser_ffi.init ()
OCaml
hhvm/hphp/hack/src/parser/full_fidelity_parser_env.ml
(* * Copyright (c) 2017, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Sexplib.Std type t = { hhvm_compat_mode: bool; php5_compat_mode: bool; codegen: bool; disable_lval_as_an_expression: bool; mode: FileInfo.mode option; rust: bool; disable_legacy_soft_typehints: bool; allow_new_attribute_syntax: bool; disable_legacy_attribute_syntax: bool; leak_rust_tree: bool; enable_xhp_class_modifier: bool; disable_xhp_element_mangling: bool; disable_xhp_children_declarations: bool; interpret_soft_types_as_like_types: bool; is_systemlib: bool; } [@@deriving show, sexp_of] let default = { hhvm_compat_mode = false; php5_compat_mode = false; codegen = false; disable_lval_as_an_expression = false; rust = true; mode = None; disable_legacy_soft_typehints = false; allow_new_attribute_syntax = false; disable_legacy_attribute_syntax = false; leak_rust_tree = false; enable_xhp_class_modifier = false; disable_xhp_element_mangling = false; disable_xhp_children_declarations = false; interpret_soft_types_as_like_types = false; is_systemlib = false; } let make ?(hhvm_compat_mode = default.hhvm_compat_mode) ?(php5_compat_mode = default.php5_compat_mode) ?(codegen = default.codegen) ?(disable_lval_as_an_expression = default.disable_lval_as_an_expression) ?mode ?(rust = default.rust) ?(disable_legacy_soft_typehints = default.disable_legacy_soft_typehints) ?(allow_new_attribute_syntax = default.allow_new_attribute_syntax) ?(disable_legacy_attribute_syntax = default.disable_legacy_attribute_syntax) ?((* DANGER: if you leak the root tree into OCaml, it's on you to ensure that * it's eventually disposed to avoid memory leak. *) leak_rust_tree = default.leak_rust_tree) ?(enable_xhp_class_modifier = default.enable_xhp_class_modifier) ?(disable_xhp_element_mangling = default.disable_xhp_element_mangling) ?(disable_xhp_children_declarations = default.disable_xhp_children_declarations) ?(interpret_soft_types_as_like_types = default.interpret_soft_types_as_like_types) ?(is_systemlib = default.is_systemlib) () = { hhvm_compat_mode; php5_compat_mode; codegen; disable_lval_as_an_expression; mode; rust; disable_legacy_soft_typehints; allow_new_attribute_syntax; disable_legacy_attribute_syntax; leak_rust_tree; enable_xhp_class_modifier; disable_xhp_element_mangling; disable_xhp_children_declarations; interpret_soft_types_as_like_types; is_systemlib; } let hhvm_compat_mode e = e.hhvm_compat_mode let php5_compat_mode e = e.php5_compat_mode let codegen e = e.codegen let disable_lval_as_an_expression e = e.disable_lval_as_an_expression let mode e = e.mode let is_strict e = e.mode = Some FileInfo.Mstrict let rust e = e.rust let disable_legacy_soft_typehints e = e.disable_legacy_soft_typehints let allow_new_attribute_syntax e = e.allow_new_attribute_syntax let disable_legacy_attribute_syntax e = e.disable_legacy_attribute_syntax let leak_rust_tree e = e.leak_rust_tree let enable_xhp_class_modifier e = e.enable_xhp_class_modifier let disable_xhp_element_mangling e = e.disable_xhp_element_mangling let disable_xhp_children_declarations e = e.disable_xhp_children_declarations let interpret_soft_types_as_like_types e = e.interpret_soft_types_as_like_types
OCaml
hhvm/hphp/hack/src/parser/full_fidelity_parser_errors.ml
(* * Copyright (c) 2016, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude module WithSyntax (Syntax : Syntax_sig.Syntax_S) = struct module WithSmartConstructors (SCI : SmartConstructors.SmartConstructors_S with type r = Syntax.t with module Token = Syntax.Token) = struct module SyntaxTree_ = Full_fidelity_syntax_tree.WithSyntax (Syntax) module SyntaxTree = SyntaxTree_.WithSmartConstructors (SCI) module SyntaxError = Full_fidelity_syntax_error type error_level = | Minimum | Typical | Maximum type hhvm_compat_mode = | NoCompat | HHVMCompat type env = { syntax_tree: SyntaxTree.t; level: error_level; hhvm_compat_mode: hhvm_compat_mode; codegen: bool; hhi_mode: bool; parser_options: ParserOptions.t; } let make_env ?(level = Typical) ?(hhvm_compat_mode = NoCompat) ?(hhi_mode = false) ~(parser_options : ParserOptions.t) (syntax_tree : SyntaxTree.t) ~(codegen : bool) : env = { syntax_tree; level; hhvm_compat_mode; codegen; hhi_mode; parser_options; } let start_offset n = let s = Syntax.position Relative_path.default n in let (s, _) = Pos.info_raw (Option.value ~default:Pos.none s) in s let end_offset n = let e = Syntax.position Relative_path.default n in let (_, e) = Pos.info_raw (Option.value ~default:Pos.none e) in e let make_error_from_nodes ?(error_type = SyntaxError.ParseError) start_node end_node error = let s = start_offset start_node in let e = end_offset end_node in SyntaxError.make ~error_type s e error let make_error_from_node ?(error_type = SyntaxError.ParseError) node error = make_error_from_nodes ~error_type node node error let find_syntax_errors env = match SyntaxTree.rust_tree env.syntax_tree with | Some rust_tree -> Rust_pointer.unregister_leaked_pointer rust_tree; Syntax.rust_parser_errors (SyntaxTree.text env.syntax_tree) rust_tree (ParserOptions.to_rust_ffi_t env.parser_options ~hhvm_compat_mode: (match env.hhvm_compat_mode with | NoCompat -> false | HHVMCompat -> true) ~hhi_mode:env.hhi_mode ~codegen:env.codegen) | None -> failwith "expected to find Rust tree. ~leak_rust_tree was not set correctly somwhere earlier" let parse_errors env = (* Minimum: suppress cascading errors; no second-pass errors if there are any first-pass errors. Typical: suppress cascading errors; give second pass errors always. Maximum: all errors *) try let errors1 = match env.level with | Maximum -> SyntaxTree.all_errors env.syntax_tree | _ -> SyntaxTree.errors env.syntax_tree in let errors2 = match env.level with | Minimum when not (List.is_empty errors1) -> [] | _ -> find_syntax_errors env in List.sort ~compare:SyntaxError.compare (List.append errors1 errors2) with | e -> let error_msg = "UNEXPECTED_ERROR: " ^ Exn.to_string e in [make_error_from_node (SyntaxTree.root env.syntax_tree) error_msg] end include WithSmartConstructors (SyntaxSmartConstructors.WithSyntax (Syntax)) end
OCaml Interface
hhvm/hphp/hack/src/parser/full_fidelity_parser_errors.mli
(* * 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 WithSyntax (Syntax : Syntax_sig.Syntax_S) : sig module WithSmartConstructors (SmartConstructors : SmartConstructors.SmartConstructors_S with type r = Syntax.t with module Token = Syntax.Token) : sig type error_level = | Minimum | Typical | Maximum type hhvm_compat_mode = | NoCompat | HHVMCompat type env val make_env : ?level:(* Optional parts *) error_level -> ?hhvm_compat_mode:hhvm_compat_mode -> ?hhi_mode:bool (* Required parts *) -> parser_options:ParserOptions.t -> Full_fidelity_syntax_tree.WithSyntax(Syntax).WithSmartConstructors (SmartConstructors) .t -> codegen:bool -> env val parse_errors : env -> Full_fidelity_syntax_error.t list end include module type of WithSmartConstructors (SyntaxSmartConstructors.WithSyntax (Syntax)) end
OCaml
hhvm/hphp/hack/src/parser/full_fidelity_parser_profiling.ml
(* * Copyright (c) 2018, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) let parse_count_ref = ref 0 let start_profiling () = parse_count_ref := 0 let record_parse () = incr parse_count_ref let stop_profiling () = !parse_count_ref
OCaml
hhvm/hphp/hack/src/parser/full_fidelity_positioned_syntax.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. An additional * directory. * ** * * Positioned syntax tree * * A positioned syntax tree stores the original source text, * the offset of the leading trivia, the width of the leading trivia, * node proper, and trailing trivia. From all this information we can * rapidly compute the absolute position of any portion of the node, * or the text. * *) open Hh_prelude module SourceText = Full_fidelity_source_text module Token = Full_fidelity_positioned_token module SyntaxWithPositionedToken = Full_fidelity_syntax.WithToken (Token) module PositionedSyntaxValue = struct type t = (* value for a token node is token itself *) | TokenValue of Token.t (* value for a range denoted by pair of tokens *) | TokenSpan of { left: Token.t; right: Token.t; } | Missing of { source_text: SourceText.t; offset: int; } [@@deriving show, eq, sexp_of] let source_text value = match value with | TokenValue t | TokenSpan { left = t; _ } -> Token.source_text t | Missing { source_text; _ } -> source_text let start_offset value = match value with | TokenValue t | TokenSpan { left = t; _ } -> Token.leading_start_offset t | Missing { offset; _ } -> offset let leading_width value = match value with | TokenValue t | TokenSpan { left = t; _ } -> Token.leading_width t | Missing _ -> 0 let width value = match value with | TokenValue t -> Token.width t | TokenSpan { left; right } -> Token.end_offset right - Token.start_offset left + 1 | Missing _ -> 0 let trailing_width value = match value with | TokenValue t | TokenSpan { right = t; _ } -> Token.trailing_width t | Missing _ -> 0 let to_json value = Hh_json.( JSON_Object [ ("offset", int_ (start_offset value)); ("leading_width", int_ (leading_width value)); ("width", int_ (width value)); ("trailing_width", int_ (trailing_width value)); ]) end module PositionedWithValue = SyntaxWithPositionedToken.WithSyntaxValue (PositionedSyntaxValue) include PositionedWithValue module PositionedValueBuilder = struct let value_from_token token = let is_end_of_file = function | Full_fidelity_token_kind.EndOfFile -> true | _ -> false in if is_end_of_file (Token.kind token) || Token.full_width token = 0 then PositionedSyntaxValue.Missing { source_text = Token.source_text token; offset = Token.end_offset token; } else PositionedSyntaxValue.TokenValue token let value_from_outer_children first last = let module PSV = PositionedSyntaxValue in match (value first, value last) with | (PSV.TokenValue l, PSV.TokenValue r) | (PSV.TokenValue l, PSV.TokenSpan { right = r; _ }) | (PSV.TokenSpan { left = l; _ }, PSV.TokenValue r) | (PSV.TokenSpan { left = l; _ }, PSV.TokenSpan { right = r; _ }) -> if phys_equal l r then PSV.TokenValue l else PSV.TokenSpan { left = l; right = r } (* can have two missing nodes if first and last child nodes of the node are missing - this means that entire node is missing. NOTE: offset must match otherwise it will mean that there is a real node in between that should be picked instead *) | (PSV.Missing { offset = o1; source_text }, PSV.Missing { offset = o2; _ }) when o1 = o2 -> PSV.Missing { offset = o1; source_text } | _ -> assert false let width n = PositionedSyntaxValue.width (value n) let value_from_children source_text offset _kind nodes = (* * We need to determine the offset, leading, middle and trailing widths of * the node to be constructed based on its children. If the children are * all of zero width -- including the case where there are no children at * all -- then we make a zero-width value at the given offset. * Otherwise, we can determine the associated value from the first and last * children that have width. *) let have_width = List.filter ~f:(fun x -> width x > 0) nodes in match have_width with | [] -> PositionedSyntaxValue.Missing { source_text; offset } | first :: _ -> value_from_outer_children first (List.last_exn have_width) let value_from_syntax syntax = let module PSV = PositionedSyntaxValue in (* We need to find the first and last nodes that are represented by tokens. If there are no such nodes then we can simply use the first and last nodes, period, since they will have an offset and source text we can use. *) let f (first, first_not_zero, last_not_zero, _last) node = match (first, first_not_zero, value node) with | (None, None, (PSV.TokenValue _ | PSV.TokenSpan _)) -> (* first iteration and first node has some token representation - record it as first, first_non_zero, last and last_non_zero *) (Some node, Some node, Some node, Some node) | (None, None, _) -> (* first iteration - first node is missing - record it as first and last *) (Some node, None, None, Some node) | (Some _, None, (PSV.TokenValue _ | PSV.TokenSpan _)) -> (* in progress, found first node that include tokens - record it as first_non_zero, last and last_non_zero *) (first, Some node, Some node, Some node) | (Some _, Some _, (PSV.TokenValue _ | PSV.TokenSpan _)) -> (* in progress found some node that include tokens - record it as last_non_zero and last *) (first, first_not_zero, Some node, Some node) | _ -> (* in progress, stepped on missing node - record it as last and move on *) (first, first_not_zero, last_not_zero, Some node) in let (f, fnz, lnz, l) = fold_over_children f (None, None, None, None) syntax in match (f, fnz, lnz, l) with | (_, Some first_not_zero, Some last_not_zero, _) -> value_from_outer_children first_not_zero last_not_zero | (Some first, None, None, Some last) -> value_from_outer_children first last | _ -> failwith "how did we get a node with no children in value_from_syntax?" end include PositionedWithValue.WithValueBuilder (PositionedValueBuilder) let source_text node = PositionedSyntaxValue.source_text (value node) let leading_width node = PositionedSyntaxValue.leading_width (value node) let width node = PositionedSyntaxValue.width (value node) let trailing_width node = PositionedSyntaxValue.trailing_width (value node) let full_width node = leading_width node + width node + trailing_width node let leading_start_offset node = PositionedSyntaxValue.start_offset (value node) let leading_end_offset node = let w = leading_width node - 1 in let w = if w < 0 then 0 else w in leading_start_offset node + w let start_offset node = leading_start_offset node + leading_width node let end_offset node = let w = width node - 1 in let w = if w < 0 then 0 else w in start_offset node + w let trailing_start_offset node = leading_start_offset node + leading_width node + width node let trailing_end_offset node = let w = full_width node - 1 in let w = if w < 0 then 0 else w in leading_start_offset node + w let leading_start_position node = SourceText.offset_to_position (source_text node) (leading_start_offset node) let leading_end_position node = SourceText.offset_to_position (source_text node) (leading_end_offset node) let start_position node = SourceText.offset_to_position (source_text node) (start_offset node) let end_position node = SourceText.offset_to_position (source_text node) (end_offset node) let trailing_start_position node = SourceText.offset_to_position (source_text node) (trailing_start_offset node) let trailing_end_position node = SourceText.offset_to_position (source_text node) (trailing_end_offset node) let leading_span node = (leading_start_position node, leading_end_position node) let span node = (start_position node, end_position node) let trailing_span node = (trailing_start_position node, trailing_end_position node) let full_span node = (leading_start_position node, trailing_end_position node) let full_text node = SourceText.sub (source_text node) (leading_start_offset node) (full_width node) let leading_text node = SourceText.sub (source_text node) (leading_start_offset node) (leading_width node) let trailing_text node = SourceText.sub (source_text node) (end_offset node + 1) (trailing_width node) let text node = SourceText.sub (source_text node) (start_offset node) (width node) let trailing_token node = match value node with | PositionedSyntaxValue.TokenValue token -> Some token | PositionedSyntaxValue.TokenSpan { right; _ } -> Some right | PositionedSyntaxValue.Missing _ -> None let extract_text node = Some (text node) (* Takes a node and an offset; produces the descent through the parse tree to that position. *) let parentage node position = let rec aux nodes position acc = match nodes with | [] -> acc | h :: t -> let width = full_width h in if position < width then aux (children h) position (h :: acc) else aux t (position - width) acc in aux [node] position [] let is_in_body node position = let rec aux parents = match parents with | [] -> false | h1 :: h2 :: _ when is_compound_statement h1 && (is_methodish_declaration h2 || is_function_declaration h2) -> true | _ :: rest -> aux rest in let parents = parentage node position in aux parents let position file node = let source_text = source_text node in let start_offset = start_offset node in let end_offset = end_offset node in Some (SourceText.relative_pos file source_text start_offset end_offset) let offset node = Some (start_offset node) let position_exclusive file node = let source_text = source_text node in let start_offset = start_offset node in let end_offset = end_offset node + 1 in Some (SourceText.relative_pos file source_text start_offset end_offset) let is_synthetic _node = false let leading_trivia node = let token = leading_token node in match token with | None -> [] | Some t -> Token.leading t let trailing_trivia node = let token = trailing_token node in match token with | None -> [] | Some t -> Token.trailing t type 'a rust_parse_type = Full_fidelity_source_text.t -> Full_fidelity_parser_env.t -> 'a * t * Full_fidelity_syntax_error.t list * Rust_pointer.t option let rust_parse_ref : unit rust_parse_type ref = ref (fun _ _ -> failwith "This should be lazily set in Rust_parser_ffi") let rust_parse text env = !rust_parse_ref text env external rust_parser_errors : Full_fidelity_source_text.t -> Rust_pointer.t -> ParserOptions.ffi_t -> Full_fidelity_syntax_error.t list = "rust_parser_errors_positioned"
OCaml
hhvm/hphp/hack/src/parser/full_fidelity_positioned_token.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. * *) (** * Positioned token * * A positioned token stores the original source text, * the offset of the leading trivia, the width of the leading trivia, * node proper, and trailing trivia. From all this information we can * rapidly compute the absolute position of any portion of the node, * or the text. * *) open Hh_prelude module Trivia = Full_fidelity_positioned_trivia module SourceText = Full_fidelity_source_text module TokenKind = Full_fidelity_token_kind module TriviaKind = Full_fidelity_trivia_kind module LazyTrivia : sig type t [@@deriving show, sexp_of] val equal : t -> t -> bool val has_trivia_kind : t -> TriviaKind.t -> bool val from : Trivia.t list * Trivia.t list -> t val update_trailing : t -> (unit -> Trivia.t list) -> Trivia.t list -> t val update_leading : t -> Trivia.t list -> (unit -> Trivia.t list) -> t val leading : t -> (int -> int -> Rust_lazy_trivia_ffi.RustPositionedTrivium.t list) -> Trivia.SourceText.t -> int -> int -> Trivia.t list val trailing : t -> (int -> int -> Rust_lazy_trivia_ffi.RustPositionedTrivium.t list) -> Trivia.SourceText.t -> int -> int -> Trivia.t list end = struct (** This looks horrifying, but allow me to explain. For most trivia, we really don't care what it is, and even if we do, we can find out what it is by running the lexer over the trivia range again. To optimize for this case, we only need to store what types of trivia we're surrounded by, and since trivia kinds are stored using an enum we can just pack that into an int. Unfortunately, there are some types of trivia that are not only incredibly important to handle properly, they also can't be regenerated just by running the lexer. If any of our trivia is within that set, we need to store the trivia itself at all times. The standard, reasonable way to represent this would be to use a variant of two cases, something like [type SurroundingTrivia = Lexable of int | Unlexable of (Trivia.t list * Trivia.t list)]. Unfortunately, the first case is at least nine orders of magnitude more common than the second case, since the second case is only needed for [ExtraTokenError], which only show up in incorrect files that wouldn't pass typecheck anyway. Therefore, in order to optimize for the general case, we use the [Obj] library to store the trivia kinds packed into an int as an immediate value, unless we detect that it's not an int, in which case we can pull it out as a tuple of leading and trailing trivia. In this way we can go from 24 bytes in the base case (8 for pointer to variant, 8 for block header, 8 for int value) to just 8 bytes for the base case. Base case: [trivia] is a packed int where the top [n] bits are used to store whether a trivia of the [n]th [TriviaKind] is present. Special case: [trivia] is [(Trivia.t list * Trivia.t list)], corresponding to the leading and trailing trivia. *) type t = Obj.t let sexp_of_t _ = Sexp.Atom "Obj.t" let equal : t -> t -> bool = (fun x y -> Poly.equal x y) (** Internal representation used for printing and pattern matching. *) type internal_t = | Packed of int | Expanded of (Trivia.t list * Trivia.t list) [@@deriving show] let to_internal trivia = if Obj.is_int trivia then Packed (Obj.obj trivia) else Expanded (Obj.obj trivia) let from_internal = function | Packed trivia -> Obj.repr trivia | Expanded trivia -> Obj.repr trivia let pp formatter trivia = pp_internal_t formatter (to_internal trivia) let show trivia = show_internal_t (to_internal trivia) let trivia_kind_mask kind = 1 lsl (62 - TriviaKind.to_enum kind) let fold_kind acc kind = acc lor trivia_kind_mask kind let get_trivia_kinds trivia_lists = let get_trivia_kinds trivia_list = let kinds = List.map ~f:(fun trivia -> trivia.Trivia.kind) trivia_list in List.fold_left ~f:fold_kind ~init:0 kinds in let trivia_kinds = List.map ~f:get_trivia_kinds trivia_lists in List.fold_left ~f:( lor ) ~init:0 trivia_kinds let is_special = function | TriviaKind.ExtraTokenError -> true | _ -> false let has_special trivia_lists = trivia_lists |> List.exists ~f:(List.exists ~f:(fun trivia -> is_special trivia.Trivia.kind)) let has_trivia_kind trivia kind = match to_internal trivia with | Packed trivia -> let kind_mask = trivia_kind_mask kind in trivia land kind_mask <> 0 | Expanded (leading, trailing) -> [leading; trailing] |> List.exists ~f: (List.exists ~f:(fun trivia -> TriviaKind.equal trivia.Trivia.kind kind)) let from (leading, trailing) = let internal = if has_special [leading; trailing] then Expanded (leading, trailing) else Packed (get_trivia_kinds [leading; trailing]) in internal |> from_internal (** Updates a [LazyTrivia.t] with new values. @param trivia the trivia to update @param load_func function to load the trivia that we're not updating, if the trivia we're passed in is lazy @param new_trivia the new trivia which we're using to update @param get_func function to get the trivia that we're not updating, if the trivia we're passed in is not lazy @param update_func function to take the gotten trivia and pack it into a new tuple, if the trivia we're passed in is not lazy *) let update (trivia : t) (load_func : unit -> Trivia.t list) (new_trivia : Trivia.t list) (get_func : Trivia.t list * Trivia.t list -> Trivia.t list) (update_func : Trivia.t list -> Trivia.t list * Trivia.t list) : t = match (to_internal trivia, has_special [new_trivia]) with | (Packed _, true) -> let loaded = load_func () in from_internal (Expanded (update_func loaded)) | (Packed trivia, false) -> from_internal (Packed (trivia lor get_trivia_kinds [new_trivia])) | (Expanded trivia, _) -> let loaded = get_func trivia in from_internal (Expanded (update_func loaded)) let update_leading trivia new_leading load_trailing = update trivia load_trailing new_leading snd (fun loaded -> (new_leading, loaded)) let update_trailing trivia load_leading new_trailing = update trivia load_leading new_trailing fst (fun loaded -> (loaded, new_trailing)) let load_trivia scanner source_text offset width = if width = 0 then [] else let trivia = scanner offset width in Trivia.from_rust_trivia source_text trivia let leading trivia scanner source_text offset width = match to_internal trivia with | Packed _ -> load_trivia scanner source_text offset width | Expanded (leading, _) -> leading let trailing (trivia : t) (scanner : int -> int -> Rust_lazy_trivia_ffi.RustPositionedTrivium.t list) (source_text : Trivia.SourceText.t) (offset : int) (width : int) = match to_internal trivia with | Packed _ -> load_trivia scanner source_text offset width | Expanded (_, trailing) -> trailing end type t = { kind: TokenKind.t; source_text: SourceText.t; offset: int; (* Beginning of first trivia *) leading_width: int; width: int; (* Width of actual token, not counting trivia *) trailing_width: int; trivia: LazyTrivia.t; } [@@deriving show, eq, sexp_of] let fold_width sum trivia = sum + Trivia.width trivia let make kind source_text offset width leading trailing = let leading_width = List.fold_left ~f:fold_width ~init:0 leading in let trailing_width = List.fold_left ~f:fold_width ~init:0 trailing in let trivia = LazyTrivia.from (leading, trailing) in { kind; source_text; offset; leading_width; width; trailing_width; trivia } let kind token = token.kind let with_kind token kind = { token with kind } let has_trivia_kind token = LazyTrivia.has_trivia_kind token.trivia let source_text token = token.source_text let leading_width token = token.leading_width let width token = token.width let trailing_width token = token.trailing_width let full_width token = leading_width token + width token + trailing_width token let is_in_xhp token = match token.kind with | TokenKind.XHPBody -> true | _ -> false let make_rust_scanner token fn (offset : int) (width : int) = fn token.source_text offset width let leading token = let scanner = match is_in_xhp token with | true -> make_rust_scanner token Rust_lazy_trivia_ffi.scan_leading_xhp_trivia | false -> make_rust_scanner token Rust_lazy_trivia_ffi.scan_leading_php_trivia in LazyTrivia.leading token.trivia scanner token.source_text token.offset token.leading_width let trailing token = let scanner = match is_in_xhp token with | true -> make_rust_scanner token Rust_lazy_trivia_ffi.scan_trailing_xhp_trivia | false -> make_rust_scanner token Rust_lazy_trivia_ffi.scan_trailing_php_trivia in let offset = token.offset + token.leading_width + token.width in LazyTrivia.trailing token.trivia scanner token.source_text offset token.trailing_width let with_leading new_leading token = { token with trivia = LazyTrivia.update_leading token.trivia new_leading (fun () -> trailing token); } let with_trailing new_trailing token = { token with trivia = LazyTrivia.update_trailing token.trivia (fun () -> leading token) new_trailing; } let filter_leading_trivia_by_kind token kind = List.filter ~f:(fun t -> TriviaKind.equal (Trivia.kind t) kind) (leading token) let leading_start_offset token = token.offset let leading_end_offset token = let w = leading_width token - 1 in let w = if w < 0 then 0 else w in leading_start_offset token + w let start_offset token = leading_start_offset token + leading_width token let end_offset token = let w = width token - 1 in let w = if w < 0 then 0 else w in start_offset token + w let trailing_start_offset token = leading_start_offset token + leading_width token + width token let trailing_end_offset token = let w = full_width token - 1 in let w = if w < 0 then 0 else w in leading_start_offset token + w let leading_start_position token = SourceText.offset_to_position (source_text token) (leading_start_offset token) let leading_end_position token = SourceText.offset_to_position (source_text token) (leading_end_offset token) let start_position token = SourceText.offset_to_position (source_text token) (start_offset token) let end_position token = SourceText.offset_to_position (source_text token) (end_offset token) let trailing_start_position token = SourceText.offset_to_position (source_text token) (trailing_start_offset token) let trailing_end_position token = SourceText.offset_to_position (source_text token) (trailing_end_offset token) let leading_span token = (leading_start_position token, leading_end_position token) let span token = (start_position token, end_position token) let trailing_span token = (trailing_start_position token, trailing_end_position token) let full_span token = (leading_start_position token, trailing_end_position token) let full_text token = SourceText.sub (source_text token) (leading_start_offset token) (full_width token) let leading_text token = SourceText.sub (source_text token) (leading_start_offset token) (leading_width token) let trailing_text token = SourceText.sub (source_text token) (end_offset token + 1) (trailing_width token) let text token = SourceText.sub (source_text token) (start_offset token) (width token) let concatenate b e = { b with width = end_offset e + 1 - start_offset b; trailing_width = e.trailing_width; trivia = LazyTrivia.update_trailing b.trivia (fun () -> leading b) (trailing e); } let trim_left ~n t = { t with leading_width = t.leading_width + n; width = t.width - n } let trim_right ~n t = { t with trailing_width = t.trailing_width + n; width = t.width - n } let to_json token = Hh_json.( let (line_number, _) = start_position token in JSON_Object [ ("kind", JSON_String (TokenKind.to_string token.kind)); ("text", JSON_String (text token)); ("offset", int_ token.offset); ("leading_width", int_ token.leading_width); ("width", int_ token.width); ("trailing_width", int_ token.trailing_width); ("leading", JSON_Array (List.map ~f:Trivia.to_json (leading token))); ("trailing", JSON_Array (List.map ~f:Trivia.to_json (trailing token))); ("line_number", int_ line_number); ])
OCaml
hhvm/hphp/hack/src/parser/full_fidelity_positioned_trivia.ml
(* * Copyright (c) 2016, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Sexplib.Std (** * Positioned trivia * * A positioned trivia stores the original source text, the offset of the * start of the trivia, and its width. From all this information we can * rapidly compute the absolute position of the trivia, or obtain its text. * *) module TriviaKind = Full_fidelity_trivia_kind module SourceText = Full_fidelity_source_text type t = { kind: TriviaKind.t; source_text: SourceText.t; offset: int; width: int; } [@@deriving show, eq, sexp_of] let make_ignore_error source_text offset width = { kind = TriviaKind.IgnoreError; source_text; offset; width } let make_extra_token_error source_text offset width = { kind = TriviaKind.ExtraTokenError; source_text; offset; width } let make_fallthrough source_text offset width = { kind = TriviaKind.FallThrough; source_text; offset; width } let make_fix_me source_text offset width = { kind = TriviaKind.FixMe; source_text; offset; width } let make_whitespace source_text offset width = { kind = TriviaKind.WhiteSpace; source_text; offset; width } let make_eol source_text offset width = { kind = TriviaKind.EndOfLine; source_text; offset; width } let make_single_line_comment source_text offset width = { kind = TriviaKind.SingleLineComment; source_text; offset; width } let make_delimited_comment source_text offset width = { kind = TriviaKind.DelimitedComment; source_text; offset; width } let width trivia = trivia.width let kind trivia = trivia.kind let start_offset trivia = trivia.offset let end_offset trivia = trivia.offset + trivia.width - 1 let source_text trivia = trivia.source_text let text trivia = SourceText.sub (source_text trivia) (start_offset trivia) (width trivia) let from_rust_trivium source_text rust_trivium = let kind = rust_trivium.Rust_lazy_trivia_ffi.RustPositionedTrivium.kind in let width = rust_trivium.Rust_lazy_trivia_ffi.RustPositionedTrivium.width in let offset = rust_trivium.Rust_lazy_trivia_ffi.RustPositionedTrivium.offset in { kind; source_text; offset; width } let from_rust_trivia source_text = List.map (from_rust_trivium source_text) let to_json trivia = Hh_json.( JSON_Object [ ("kind", JSON_String (TriviaKind.to_string trivia.kind)); ("text", JSON_String (text trivia)); ("offset", int_ trivia.offset); ("width", int_ trivia.width); ])
OCaml
hhvm/hphp/hack/src/parser/full_fidelity_rewriter.ml
(* * Copyright (c) 2016, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open Common module SourceText = Full_fidelity_source_text module type RewritableType = sig type t val children : t -> t list val from_children : Full_fidelity_source_text.t -> int -> Full_fidelity_syntax_kind.t -> t list -> t val kind : t -> Full_fidelity_syntax_kind.t end module WithSyntax (Syntax : RewritableType) = struct module Result = struct type 'a t = | Remove | Keep | Replace of 'a end include Result (* The rewriter takes a function f that is parents : [node] -> current_node : node -> current_acc : accumulator -> (accumulator, node result) The tree is walked in post order; leaves are rewritten first. After all the children of a node are rewritten, then f is called on the rewritten node. The function itself returns (acc, node) *) let parented_aggregating_rewrite_post f node init_acc = (* aux takes parents node accumulator and returns (acc, node result) *) let rec aux parents node acc = (* Start by rewriting all the children. We begin by obtaining a node list, and then from it producing a new (accumulator, changed) value and a node opt list. We then transform the node opt list into a node list, which is the new list of children. *) let mapper (acc, changed) child = match aux (node :: parents) child acc with | (acc, Replace new_child) -> ((acc, true), Some new_child) | (acc, Keep) -> ((acc, changed), Some child) | (acc, Remove) -> ((acc, true), None) in let ((acc, child_changed), option_new_children) = List.map_env (acc, false) (Syntax.children node) ~f:mapper in let node = if child_changed then let new_children = List.filter_opt option_new_children in Syntax.from_children SourceText.empty 0 (Syntax.kind node) new_children else node in let (acc, result) = f parents node acc in let result = match (result, child_changed) with | (Keep, true) -> Replace node | _ -> result in (acc, result) in (* end of aux *) let (acc, result) = aux [] node init_acc in let result_node = match result with | Keep -> node | Replace new_node -> new_node | Remove -> failwith "rewriter removed the root node!" in (acc, result_node) (* The same as the above, except that f does not take parents. *) let aggregating_rewrite_post f node init_acc = let f _parents node acc = f node acc in parented_aggregating_rewrite_post f node init_acc (* The same as the above, except that f does not take or return an accumulator. *) let parented_rewrite_post f node = let f parents node _acc = ([], f parents node) in let (_acc, result) = parented_aggregating_rewrite_post f node [] in result (* The same as the above, except that f does not take or return an accumulator, and f does not take parents *) let rewrite_post f node = let f _parents node _acc = ([], f node) in let (_acc, result) = parented_aggregating_rewrite_post f node [] in result (* As above, but the rewrite happens to the node first and then recurses on the children. *) let parented_aggregating_rewrite_pre f node init_acc = let rec aux parents node acc = let mapper (acc, changed) child = match aux (node :: parents) child acc with | (acc, Replace new_child) -> ((acc, true), Some new_child) | (acc, Keep) -> ((acc, changed), Some child) | (acc, Remove) -> ((acc, true), None) in (* end of mapper *) let rewrite_children node_changed node acc = let children = Syntax.children node in let ((acc, child_changed), option_new_children) = List.map_env (acc, false) children ~f:mapper in let result = if child_changed then let new_children = List.filter_opt option_new_children in let node = Syntax.from_children SourceText.empty 0 (Syntax.kind node) new_children in Replace node else if node_changed then Replace node else Keep in (acc, result) in (* end of rewrite_children *) let (acc, result) = f parents node acc in match result with | Remove -> (acc, result) | Keep -> rewrite_children false node acc | Replace new_node -> rewrite_children true new_node acc in (* end of aux *) let (acc, result) = aux [] node init_acc in let result_node = match result with | Keep -> node | Replace new_node -> new_node | Remove -> failwith "rewriter removed the root node!" in (acc, result_node) (* The same as the above, except that f does not take or return an accumulator, and f does not take parents *) let rewrite_pre f node = let f _parents node _acc = ([], f node) in let (_acc, result) = parented_aggregating_rewrite_pre f node [] in result (** * The same as the above, except does not recurse on children when a node * is rewritten to avoid additional traversal. *) let rewrite_pre_and_stop_with_acc f node init_acc = let rec aux node acc = let mapping_fun (acc, changed) child = match aux child acc with | (acc, Keep) -> ((acc, changed), Some child) | (acc, Replace new_child) -> ((acc, true), Some new_child) | (acc, Remove) -> ((acc, true), None) in (* end of mapping_fun *) let rewrite_children node acc = let children = Syntax.children node in let ((acc, changed), option_new_children) = List.map_env (acc, false) children ~f:mapping_fun in if not changed then (acc, Keep) else let new_children = List.filter_opt option_new_children in let node = Syntax.from_children SourceText.empty 0 (Syntax.kind node) new_children in (acc, Replace node) in (* end of rewrite_children *) let (acc, result) = f node acc in match result with | Keep -> rewrite_children node acc | Replace _ | Remove -> (acc, result) in (* end of aux *) let (acc, result) = aux node init_acc in match result with | Keep -> (acc, node) | Replace new_node -> (acc, new_node) | Remove -> failwith "Cannot remove root node" (** * The same as the above, except does not recurse on children when a node * is rewritten to avoid duplicate work. *) let rewrite_pre_and_stop f node = let f node _acc = ([], f node) in let (_, result) = rewrite_pre_and_stop_with_acc f node [] in result end
OCaml
hhvm/hphp/hack/src/parser/full_fidelity_rust.ml
(* * From ocaml 4.12, libraries with any .ml modules will no longer * generates libfoo.a files. * Buck v1 is still expecting these, so the easiest workaround until * Buck v2 is to provide an empty module to trigger the generation * of libfoo.a *) let () = ()
OCaml
hhvm/hphp/hack/src/parser/full_fidelity_source_text.ml
(* * Copyright (c) 2016, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Sexplib.Std (** * This is an abstraction over source files used by the full-fidelity lexer. * Right now it is just a thin wrapper over a string, but in the future I'd * like to enhance this to efficiently support operations such as: * * - representing many different portions of a file without duplicating text * - lazily loading content from files * - caching file contents intelligently * - reporting when files are updated perhaps? * * We might not need all of these things, but it will be nice to have an * abstraction when we need some of them. *) [@@@warning "-32"] (* unused variables *) module OffsetMap = struct (* placeholder definitions to placate open source build. * These definitions will be mercilessly shadowed if deriving show fires * like it's supposed to *) let pp _ _ = () let show _ = "" include Line_break_map end [@@@warning "+32"] type t = { file_path: Relative_path.t; length: int; text: string; [@opaque] offset_map: OffsetMap.t; } [@@deriving show, eq, sexp_of] type pos = t * int let make file_path content = { file_path; text = content; offset_map = OffsetMap.make content; length = String.length content; } let empty = make Relative_path.default "" let from_file file = let content = Sys_utils.cat (Relative_path.to_absolute file) in make file content let file_path source_text = source_text.file_path let length source_text = source_text.length let text t = t.text let get source_text index = if index < source_text.length then String.unsafe_get source_text.text index else '\x00' let sub source_text start length = let len = source_text.length in if start >= len then "" else if start + length > len then String.sub source_text.text start (len - start) else String.sub source_text.text start length (* Fetch the contents of just one line of text *) let line_text (source_text : t) (line_number : int) : string = try let offset_start = OffsetMap.position_to_offset source_text.offset_map (line_number, 1) in let offset_end = OffsetMap.position_to_offset source_text.offset_map (line_number + 1, 1) in (* Strip off the newline if one exists. If we're getting the very last line of the file, and * the very last line doesn't end in a newline, this unsafe_get won't return a \n char. *) let offset_end = if String.unsafe_get source_text.text (offset_end - 1) = '\n' then offset_end - 1 else offset_end in sub source_text offset_start (offset_end - offset_start) (* If the line was outside the boundaries of the file, just return a blank string *) with | _ -> "" (* Take a zero-based offset, produce a one-based (line, char) pair. *) let offset_to_position source_text offset = OffsetMap.offset_to_position source_text.offset_map offset (* Take a one-based (line, char) pair, produce a zero-based offset *) let position_to_offset source_text position = OffsetMap.position_to_offset source_text.offset_map position (* Create a Pos.t from two offsets in a source_text (given a path) *) let relative_pos pos_file source_text start_offset end_offset = let offset_to_lnum_bol_offset offset = OffsetMap.offset_to_file_pos_triple source_text.offset_map offset in let pos_start = offset_to_lnum_bol_offset start_offset in let pos_end = offset_to_lnum_bol_offset end_offset in Pos.make_from_lnum_bol_offset ~pos_file ~pos_start ~pos_end let sub_of_pos ?length source_text pos = let offset = let (first_line, first_col) = Pos.line_column pos in position_to_offset source_text (first_line, first_col + 1) in let length = match length with | Some n -> n | None -> Pos.length pos in sub source_text offset length
OCaml Interface
hhvm/hphp/hack/src/parser/full_fidelity_source_text.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 t = { file_path: Relative_path.t; length: int; text: string; offset_map: Line_break_map.t; } [@@deriving show, eq, sexp_of] type pos = t * int (** create a new source_text.t with a path and contents *) val make : Relative_path.t -> string -> t (** empty source_text.t located nowhere *) val empty : t (** read a relative path into a source_text.t with the contents at that path *) val from_file : Relative_path.t -> t (** get the relative path *) val file_path : t -> Relative_path.t (** get the length of the contents *) val length : t -> int (** get the ith character *) val get : t -> int -> char (** get the contents as a string *) val text : t -> string (** get just one line as a string *) val line_text : t -> int -> string (** get a substring start at the ith char and continuing for length *) val sub : t -> int -> int -> string (** get a substring corresponding to a position. [length] defaults to the length of the position. *) val sub_of_pos : ?length:int -> t -> Pos.t -> string (** convert an absolute offset into a (line number, column) pair *) val offset_to_position : t -> int -> int * int (** convert a (line number, column) pair into an absolute offset *) val position_to_offset : t -> int * int -> int (** construct a relative position associated with the source_text.t virtual file *) val relative_pos : Relative_path.t -> t -> int -> int -> Pos.t
OCaml
hhvm/hphp/hack/src/parser/full_fidelity_syntax.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. An additional * directory. * ** * * THIS FILE IS @generated; DO NOT EDIT IT * To regenerate this file, run * * buck run //hphp/hack/src:generate_full_fidelity * ** * * With these factory methods, nodes can be built up from their child nodes. A * factory method must not just know all the children and the kind of node it is * constructing; it also must know how to construct the value that this node is * going to be tagged with. For that reason, an optional functor is provided. * This functor requires that methods be provided to construct the values * associated with a token or with any arbitrary node, given its children. If * this functor is used then the resulting module contains factory methods. * * This module also provides some useful helper functions, like an iterator, * a rewriting visitor, and so on. *) open Hh_prelude open Full_fidelity_syntax_type module SyntaxKind = Full_fidelity_syntax_kind module TokenKind = Full_fidelity_token_kind module Operator = Full_fidelity_operator [@@@warning "-27"] (* unused variable *) module WithToken (Token : TokenType) = struct module WithSyntaxValue (SyntaxValue : SyntaxValueType) = struct include MakeSyntaxType (Token) (SyntaxValue) let make syntax value = { syntax; value } let syntax node = node.syntax let value node = node.value let syntax_node_to_list node = match syntax node with | SyntaxList x -> x | Missing -> [] | _ -> [node] let to_kind syntax = match syntax with | Missing -> SyntaxKind.Missing | Token t -> SyntaxKind.Token (Token.kind t) | SyntaxList _ -> SyntaxKind.SyntaxList | EndOfFile _ -> SyntaxKind.EndOfFile | Script _ -> SyntaxKind.Script | QualifiedName _ -> SyntaxKind.QualifiedName | ModuleName _ -> SyntaxKind.ModuleName | SimpleTypeSpecifier _ -> SyntaxKind.SimpleTypeSpecifier | LiteralExpression _ -> SyntaxKind.LiteralExpression | PrefixedStringExpression _ -> SyntaxKind.PrefixedStringExpression | PrefixedCodeExpression _ -> SyntaxKind.PrefixedCodeExpression | VariableExpression _ -> SyntaxKind.VariableExpression | PipeVariableExpression _ -> SyntaxKind.PipeVariableExpression | FileAttributeSpecification _ -> SyntaxKind.FileAttributeSpecification | EnumDeclaration _ -> SyntaxKind.EnumDeclaration | EnumUse _ -> SyntaxKind.EnumUse | Enumerator _ -> SyntaxKind.Enumerator | EnumClassDeclaration _ -> SyntaxKind.EnumClassDeclaration | EnumClassEnumerator _ -> SyntaxKind.EnumClassEnumerator | AliasDeclaration _ -> SyntaxKind.AliasDeclaration | ContextAliasDeclaration _ -> SyntaxKind.ContextAliasDeclaration | CaseTypeDeclaration _ -> SyntaxKind.CaseTypeDeclaration | CaseTypeVariant _ -> SyntaxKind.CaseTypeVariant | PropertyDeclaration _ -> SyntaxKind.PropertyDeclaration | PropertyDeclarator _ -> SyntaxKind.PropertyDeclarator | NamespaceDeclaration _ -> SyntaxKind.NamespaceDeclaration | NamespaceDeclarationHeader _ -> SyntaxKind.NamespaceDeclarationHeader | NamespaceBody _ -> SyntaxKind.NamespaceBody | NamespaceEmptyBody _ -> SyntaxKind.NamespaceEmptyBody | NamespaceUseDeclaration _ -> SyntaxKind.NamespaceUseDeclaration | NamespaceGroupUseDeclaration _ -> SyntaxKind.NamespaceGroupUseDeclaration | NamespaceUseClause _ -> SyntaxKind.NamespaceUseClause | FunctionDeclaration _ -> SyntaxKind.FunctionDeclaration | FunctionDeclarationHeader _ -> SyntaxKind.FunctionDeclarationHeader | Contexts _ -> SyntaxKind.Contexts | WhereClause _ -> SyntaxKind.WhereClause | WhereConstraint _ -> SyntaxKind.WhereConstraint | MethodishDeclaration _ -> SyntaxKind.MethodishDeclaration | MethodishTraitResolution _ -> SyntaxKind.MethodishTraitResolution | ClassishDeclaration _ -> SyntaxKind.ClassishDeclaration | ClassishBody _ -> SyntaxKind.ClassishBody | TraitUse _ -> SyntaxKind.TraitUse | RequireClause _ -> SyntaxKind.RequireClause | ConstDeclaration _ -> SyntaxKind.ConstDeclaration | ConstantDeclarator _ -> SyntaxKind.ConstantDeclarator | TypeConstDeclaration _ -> SyntaxKind.TypeConstDeclaration | ContextConstDeclaration _ -> SyntaxKind.ContextConstDeclaration | DecoratedExpression _ -> SyntaxKind.DecoratedExpression | ParameterDeclaration _ -> SyntaxKind.ParameterDeclaration | VariadicParameter _ -> SyntaxKind.VariadicParameter | OldAttributeSpecification _ -> SyntaxKind.OldAttributeSpecification | AttributeSpecification _ -> SyntaxKind.AttributeSpecification | Attribute _ -> SyntaxKind.Attribute | InclusionExpression _ -> SyntaxKind.InclusionExpression | InclusionDirective _ -> SyntaxKind.InclusionDirective | CompoundStatement _ -> SyntaxKind.CompoundStatement | ExpressionStatement _ -> SyntaxKind.ExpressionStatement | MarkupSection _ -> SyntaxKind.MarkupSection | MarkupSuffix _ -> SyntaxKind.MarkupSuffix | UnsetStatement _ -> SyntaxKind.UnsetStatement | DeclareLocalStatement _ -> SyntaxKind.DeclareLocalStatement | UsingStatementBlockScoped _ -> SyntaxKind.UsingStatementBlockScoped | UsingStatementFunctionScoped _ -> SyntaxKind.UsingStatementFunctionScoped | WhileStatement _ -> SyntaxKind.WhileStatement | IfStatement _ -> SyntaxKind.IfStatement | ElseClause _ -> SyntaxKind.ElseClause | TryStatement _ -> SyntaxKind.TryStatement | CatchClause _ -> SyntaxKind.CatchClause | FinallyClause _ -> SyntaxKind.FinallyClause | DoStatement _ -> SyntaxKind.DoStatement | ForStatement _ -> SyntaxKind.ForStatement | ForeachStatement _ -> SyntaxKind.ForeachStatement | SwitchStatement _ -> SyntaxKind.SwitchStatement | SwitchSection _ -> SyntaxKind.SwitchSection | SwitchFallthrough _ -> SyntaxKind.SwitchFallthrough | CaseLabel _ -> SyntaxKind.CaseLabel | DefaultLabel _ -> SyntaxKind.DefaultLabel | MatchStatement _ -> SyntaxKind.MatchStatement | MatchStatementArm _ -> SyntaxKind.MatchStatementArm | ReturnStatement _ -> SyntaxKind.ReturnStatement | YieldBreakStatement _ -> SyntaxKind.YieldBreakStatement | ThrowStatement _ -> SyntaxKind.ThrowStatement | BreakStatement _ -> SyntaxKind.BreakStatement | ContinueStatement _ -> SyntaxKind.ContinueStatement | EchoStatement _ -> SyntaxKind.EchoStatement | ConcurrentStatement _ -> SyntaxKind.ConcurrentStatement | SimpleInitializer _ -> SyntaxKind.SimpleInitializer | AnonymousClass _ -> SyntaxKind.AnonymousClass | AnonymousFunction _ -> SyntaxKind.AnonymousFunction | AnonymousFunctionUseClause _ -> SyntaxKind.AnonymousFunctionUseClause | VariablePattern _ -> SyntaxKind.VariablePattern | ConstructorPattern _ -> SyntaxKind.ConstructorPattern | RefinementPattern _ -> SyntaxKind.RefinementPattern | LambdaExpression _ -> SyntaxKind.LambdaExpression | LambdaSignature _ -> SyntaxKind.LambdaSignature | CastExpression _ -> SyntaxKind.CastExpression | ScopeResolutionExpression _ -> SyntaxKind.ScopeResolutionExpression | MemberSelectionExpression _ -> SyntaxKind.MemberSelectionExpression | SafeMemberSelectionExpression _ -> SyntaxKind.SafeMemberSelectionExpression | EmbeddedMemberSelectionExpression _ -> SyntaxKind.EmbeddedMemberSelectionExpression | YieldExpression _ -> SyntaxKind.YieldExpression | PrefixUnaryExpression _ -> SyntaxKind.PrefixUnaryExpression | PostfixUnaryExpression _ -> SyntaxKind.PostfixUnaryExpression | BinaryExpression _ -> SyntaxKind.BinaryExpression | IsExpression _ -> SyntaxKind.IsExpression | AsExpression _ -> SyntaxKind.AsExpression | NullableAsExpression _ -> SyntaxKind.NullableAsExpression | UpcastExpression _ -> SyntaxKind.UpcastExpression | ConditionalExpression _ -> SyntaxKind.ConditionalExpression | EvalExpression _ -> SyntaxKind.EvalExpression | IssetExpression _ -> SyntaxKind.IssetExpression | FunctionCallExpression _ -> SyntaxKind.FunctionCallExpression | FunctionPointerExpression _ -> SyntaxKind.FunctionPointerExpression | ParenthesizedExpression _ -> SyntaxKind.ParenthesizedExpression | BracedExpression _ -> SyntaxKind.BracedExpression | ETSpliceExpression _ -> SyntaxKind.ETSpliceExpression | EmbeddedBracedExpression _ -> SyntaxKind.EmbeddedBracedExpression | ListExpression _ -> SyntaxKind.ListExpression | CollectionLiteralExpression _ -> SyntaxKind.CollectionLiteralExpression | ObjectCreationExpression _ -> SyntaxKind.ObjectCreationExpression | ConstructorCall _ -> SyntaxKind.ConstructorCall | DarrayIntrinsicExpression _ -> SyntaxKind.DarrayIntrinsicExpression | DictionaryIntrinsicExpression _ -> SyntaxKind.DictionaryIntrinsicExpression | KeysetIntrinsicExpression _ -> SyntaxKind.KeysetIntrinsicExpression | VarrayIntrinsicExpression _ -> SyntaxKind.VarrayIntrinsicExpression | VectorIntrinsicExpression _ -> SyntaxKind.VectorIntrinsicExpression | ElementInitializer _ -> SyntaxKind.ElementInitializer | SubscriptExpression _ -> SyntaxKind.SubscriptExpression | EmbeddedSubscriptExpression _ -> SyntaxKind.EmbeddedSubscriptExpression | AwaitableCreationExpression _ -> SyntaxKind.AwaitableCreationExpression | XHPChildrenDeclaration _ -> SyntaxKind.XHPChildrenDeclaration | XHPChildrenParenthesizedList _ -> SyntaxKind.XHPChildrenParenthesizedList | XHPCategoryDeclaration _ -> SyntaxKind.XHPCategoryDeclaration | XHPEnumType _ -> SyntaxKind.XHPEnumType | XHPLateinit _ -> SyntaxKind.XHPLateinit | XHPRequired _ -> SyntaxKind.XHPRequired | XHPClassAttributeDeclaration _ -> SyntaxKind.XHPClassAttributeDeclaration | XHPClassAttribute _ -> SyntaxKind.XHPClassAttribute | XHPSimpleClassAttribute _ -> SyntaxKind.XHPSimpleClassAttribute | XHPSimpleAttribute _ -> SyntaxKind.XHPSimpleAttribute | XHPSpreadAttribute _ -> SyntaxKind.XHPSpreadAttribute | XHPOpen _ -> SyntaxKind.XHPOpen | XHPExpression _ -> SyntaxKind.XHPExpression | XHPClose _ -> SyntaxKind.XHPClose | TypeConstant _ -> SyntaxKind.TypeConstant | VectorTypeSpecifier _ -> SyntaxKind.VectorTypeSpecifier | KeysetTypeSpecifier _ -> SyntaxKind.KeysetTypeSpecifier | TupleTypeExplicitSpecifier _ -> SyntaxKind.TupleTypeExplicitSpecifier | VarrayTypeSpecifier _ -> SyntaxKind.VarrayTypeSpecifier | FunctionCtxTypeSpecifier _ -> SyntaxKind.FunctionCtxTypeSpecifier | TypeParameter _ -> SyntaxKind.TypeParameter | TypeConstraint _ -> SyntaxKind.TypeConstraint | ContextConstraint _ -> SyntaxKind.ContextConstraint | DarrayTypeSpecifier _ -> SyntaxKind.DarrayTypeSpecifier | DictionaryTypeSpecifier _ -> SyntaxKind.DictionaryTypeSpecifier | ClosureTypeSpecifier _ -> SyntaxKind.ClosureTypeSpecifier | ClosureParameterTypeSpecifier _ -> SyntaxKind.ClosureParameterTypeSpecifier | TypeRefinement _ -> SyntaxKind.TypeRefinement | TypeInRefinement _ -> SyntaxKind.TypeInRefinement | CtxInRefinement _ -> SyntaxKind.CtxInRefinement | ClassnameTypeSpecifier _ -> SyntaxKind.ClassnameTypeSpecifier | FieldSpecifier _ -> SyntaxKind.FieldSpecifier | FieldInitializer _ -> SyntaxKind.FieldInitializer | ShapeTypeSpecifier _ -> SyntaxKind.ShapeTypeSpecifier | ShapeExpression _ -> SyntaxKind.ShapeExpression | TupleExpression _ -> SyntaxKind.TupleExpression | GenericTypeSpecifier _ -> SyntaxKind.GenericTypeSpecifier | NullableTypeSpecifier _ -> SyntaxKind.NullableTypeSpecifier | LikeTypeSpecifier _ -> SyntaxKind.LikeTypeSpecifier | SoftTypeSpecifier _ -> SyntaxKind.SoftTypeSpecifier | AttributizedSpecifier _ -> SyntaxKind.AttributizedSpecifier | ReifiedTypeArgument _ -> SyntaxKind.ReifiedTypeArgument | TypeArguments _ -> SyntaxKind.TypeArguments | TypeParameters _ -> SyntaxKind.TypeParameters | TupleTypeSpecifier _ -> SyntaxKind.TupleTypeSpecifier | UnionTypeSpecifier _ -> SyntaxKind.UnionTypeSpecifier | IntersectionTypeSpecifier _ -> SyntaxKind.IntersectionTypeSpecifier | ErrorSyntax _ -> SyntaxKind.ErrorSyntax | ListItem _ -> SyntaxKind.ListItem | EnumClassLabelExpression _ -> SyntaxKind.EnumClassLabelExpression | ModuleDeclaration _ -> SyntaxKind.ModuleDeclaration | ModuleExports _ -> SyntaxKind.ModuleExports | ModuleImports _ -> SyntaxKind.ModuleImports | ModuleMembershipDeclaration _ -> SyntaxKind.ModuleMembershipDeclaration | PackageExpression _ -> SyntaxKind.PackageExpression let kind node = to_kind (syntax node) let has_kind syntax_kind node = SyntaxKind.equal (kind node) syntax_kind let is_missing node = match kind node with | SyntaxKind.Missing -> true | _ -> false let is_list node = match kind node with | SyntaxKind.SyntaxList -> true | _ -> false let is_end_of_file = has_kind SyntaxKind.EndOfFile let is_script = has_kind SyntaxKind.Script let is_qualified_name = has_kind SyntaxKind.QualifiedName let is_module_name = has_kind SyntaxKind.ModuleName let is_simple_type_specifier = has_kind SyntaxKind.SimpleTypeSpecifier let is_literal_expression = has_kind SyntaxKind.LiteralExpression let is_prefixed_string_expression = has_kind SyntaxKind.PrefixedStringExpression let is_prefixed_code_expression = has_kind SyntaxKind.PrefixedCodeExpression let is_variable_expression = has_kind SyntaxKind.VariableExpression let is_pipe_variable_expression = has_kind SyntaxKind.PipeVariableExpression let is_file_attribute_specification = has_kind SyntaxKind.FileAttributeSpecification let is_enum_declaration = has_kind SyntaxKind.EnumDeclaration let is_enum_use = has_kind SyntaxKind.EnumUse let is_enumerator = has_kind SyntaxKind.Enumerator let is_enum_class_declaration = has_kind SyntaxKind.EnumClassDeclaration let is_enum_class_enumerator = has_kind SyntaxKind.EnumClassEnumerator let is_alias_declaration = has_kind SyntaxKind.AliasDeclaration let is_context_alias_declaration = has_kind SyntaxKind.ContextAliasDeclaration let is_case_type_declaration = has_kind SyntaxKind.CaseTypeDeclaration let is_case_type_variant = has_kind SyntaxKind.CaseTypeVariant let is_property_declaration = has_kind SyntaxKind.PropertyDeclaration let is_property_declarator = has_kind SyntaxKind.PropertyDeclarator let is_namespace_declaration = has_kind SyntaxKind.NamespaceDeclaration let is_namespace_declaration_header = has_kind SyntaxKind.NamespaceDeclarationHeader let is_namespace_body = has_kind SyntaxKind.NamespaceBody let is_namespace_empty_body = has_kind SyntaxKind.NamespaceEmptyBody let is_namespace_use_declaration = has_kind SyntaxKind.NamespaceUseDeclaration let is_namespace_group_use_declaration = has_kind SyntaxKind.NamespaceGroupUseDeclaration let is_namespace_use_clause = has_kind SyntaxKind.NamespaceUseClause let is_function_declaration = has_kind SyntaxKind.FunctionDeclaration let is_function_declaration_header = has_kind SyntaxKind.FunctionDeclarationHeader let is_contexts = has_kind SyntaxKind.Contexts let is_where_clause = has_kind SyntaxKind.WhereClause let is_where_constraint = has_kind SyntaxKind.WhereConstraint let is_methodish_declaration = has_kind SyntaxKind.MethodishDeclaration let is_methodish_trait_resolution = has_kind SyntaxKind.MethodishTraitResolution let is_classish_declaration = has_kind SyntaxKind.ClassishDeclaration let is_classish_body = has_kind SyntaxKind.ClassishBody let is_trait_use = has_kind SyntaxKind.TraitUse let is_require_clause = has_kind SyntaxKind.RequireClause let is_const_declaration = has_kind SyntaxKind.ConstDeclaration let is_constant_declarator = has_kind SyntaxKind.ConstantDeclarator let is_type_const_declaration = has_kind SyntaxKind.TypeConstDeclaration let is_context_const_declaration = has_kind SyntaxKind.ContextConstDeclaration let is_decorated_expression = has_kind SyntaxKind.DecoratedExpression let is_parameter_declaration = has_kind SyntaxKind.ParameterDeclaration let is_variadic_parameter = has_kind SyntaxKind.VariadicParameter let is_old_attribute_specification = has_kind SyntaxKind.OldAttributeSpecification let is_attribute_specification = has_kind SyntaxKind.AttributeSpecification let is_attribute = has_kind SyntaxKind.Attribute let is_inclusion_expression = has_kind SyntaxKind.InclusionExpression let is_inclusion_directive = has_kind SyntaxKind.InclusionDirective let is_compound_statement = has_kind SyntaxKind.CompoundStatement let is_expression_statement = has_kind SyntaxKind.ExpressionStatement let is_markup_section = has_kind SyntaxKind.MarkupSection let is_markup_suffix = has_kind SyntaxKind.MarkupSuffix let is_unset_statement = has_kind SyntaxKind.UnsetStatement let is_declare_local_statement = has_kind SyntaxKind.DeclareLocalStatement let is_using_statement_block_scoped = has_kind SyntaxKind.UsingStatementBlockScoped let is_using_statement_function_scoped = has_kind SyntaxKind.UsingStatementFunctionScoped let is_while_statement = has_kind SyntaxKind.WhileStatement let is_if_statement = has_kind SyntaxKind.IfStatement let is_else_clause = has_kind SyntaxKind.ElseClause let is_try_statement = has_kind SyntaxKind.TryStatement let is_catch_clause = has_kind SyntaxKind.CatchClause let is_finally_clause = has_kind SyntaxKind.FinallyClause let is_do_statement = has_kind SyntaxKind.DoStatement let is_for_statement = has_kind SyntaxKind.ForStatement let is_foreach_statement = has_kind SyntaxKind.ForeachStatement let is_switch_statement = has_kind SyntaxKind.SwitchStatement let is_switch_section = has_kind SyntaxKind.SwitchSection let is_switch_fallthrough = has_kind SyntaxKind.SwitchFallthrough let is_case_label = has_kind SyntaxKind.CaseLabel let is_default_label = has_kind SyntaxKind.DefaultLabel let is_match_statement = has_kind SyntaxKind.MatchStatement let is_match_statement_arm = has_kind SyntaxKind.MatchStatementArm let is_return_statement = has_kind SyntaxKind.ReturnStatement let is_yield_break_statement = has_kind SyntaxKind.YieldBreakStatement let is_throw_statement = has_kind SyntaxKind.ThrowStatement let is_break_statement = has_kind SyntaxKind.BreakStatement let is_continue_statement = has_kind SyntaxKind.ContinueStatement let is_echo_statement = has_kind SyntaxKind.EchoStatement let is_concurrent_statement = has_kind SyntaxKind.ConcurrentStatement let is_simple_initializer = has_kind SyntaxKind.SimpleInitializer let is_anonymous_class = has_kind SyntaxKind.AnonymousClass let is_anonymous_function = has_kind SyntaxKind.AnonymousFunction let is_anonymous_function_use_clause = has_kind SyntaxKind.AnonymousFunctionUseClause let is_variable_pattern = has_kind SyntaxKind.VariablePattern let is_constructor_pattern = has_kind SyntaxKind.ConstructorPattern let is_refinement_pattern = has_kind SyntaxKind.RefinementPattern let is_lambda_expression = has_kind SyntaxKind.LambdaExpression let is_lambda_signature = has_kind SyntaxKind.LambdaSignature let is_cast_expression = has_kind SyntaxKind.CastExpression let is_scope_resolution_expression = has_kind SyntaxKind.ScopeResolutionExpression let is_member_selection_expression = has_kind SyntaxKind.MemberSelectionExpression let is_safe_member_selection_expression = has_kind SyntaxKind.SafeMemberSelectionExpression let is_embedded_member_selection_expression = has_kind SyntaxKind.EmbeddedMemberSelectionExpression let is_yield_expression = has_kind SyntaxKind.YieldExpression let is_prefix_unary_expression = has_kind SyntaxKind.PrefixUnaryExpression let is_postfix_unary_expression = has_kind SyntaxKind.PostfixUnaryExpression let is_binary_expression = has_kind SyntaxKind.BinaryExpression let is_is_expression = has_kind SyntaxKind.IsExpression let is_as_expression = has_kind SyntaxKind.AsExpression let is_nullable_as_expression = has_kind SyntaxKind.NullableAsExpression let is_upcast_expression = has_kind SyntaxKind.UpcastExpression let is_conditional_expression = has_kind SyntaxKind.ConditionalExpression let is_eval_expression = has_kind SyntaxKind.EvalExpression let is_isset_expression = has_kind SyntaxKind.IssetExpression let is_function_call_expression = has_kind SyntaxKind.FunctionCallExpression let is_function_pointer_expression = has_kind SyntaxKind.FunctionPointerExpression let is_parenthesized_expression = has_kind SyntaxKind.ParenthesizedExpression let is_braced_expression = has_kind SyntaxKind.BracedExpression let is_et_splice_expression = has_kind SyntaxKind.ETSpliceExpression let is_embedded_braced_expression = has_kind SyntaxKind.EmbeddedBracedExpression let is_list_expression = has_kind SyntaxKind.ListExpression let is_collection_literal_expression = has_kind SyntaxKind.CollectionLiteralExpression let is_object_creation_expression = has_kind SyntaxKind.ObjectCreationExpression let is_constructor_call = has_kind SyntaxKind.ConstructorCall let is_darray_intrinsic_expression = has_kind SyntaxKind.DarrayIntrinsicExpression let is_dictionary_intrinsic_expression = has_kind SyntaxKind.DictionaryIntrinsicExpression let is_keyset_intrinsic_expression = has_kind SyntaxKind.KeysetIntrinsicExpression let is_varray_intrinsic_expression = has_kind SyntaxKind.VarrayIntrinsicExpression let is_vector_intrinsic_expression = has_kind SyntaxKind.VectorIntrinsicExpression let is_element_initializer = has_kind SyntaxKind.ElementInitializer let is_subscript_expression = has_kind SyntaxKind.SubscriptExpression let is_embedded_subscript_expression = has_kind SyntaxKind.EmbeddedSubscriptExpression let is_awaitable_creation_expression = has_kind SyntaxKind.AwaitableCreationExpression let is_xhp_children_declaration = has_kind SyntaxKind.XHPChildrenDeclaration let is_xhp_children_parenthesized_list = has_kind SyntaxKind.XHPChildrenParenthesizedList let is_xhp_category_declaration = has_kind SyntaxKind.XHPCategoryDeclaration let is_xhp_enum_type = has_kind SyntaxKind.XHPEnumType let is_xhp_lateinit = has_kind SyntaxKind.XHPLateinit let is_xhp_required = has_kind SyntaxKind.XHPRequired let is_xhp_class_attribute_declaration = has_kind SyntaxKind.XHPClassAttributeDeclaration let is_xhp_class_attribute = has_kind SyntaxKind.XHPClassAttribute let is_xhp_simple_class_attribute = has_kind SyntaxKind.XHPSimpleClassAttribute let is_xhp_simple_attribute = has_kind SyntaxKind.XHPSimpleAttribute let is_xhp_spread_attribute = has_kind SyntaxKind.XHPSpreadAttribute let is_xhp_open = has_kind SyntaxKind.XHPOpen let is_xhp_expression = has_kind SyntaxKind.XHPExpression let is_xhp_close = has_kind SyntaxKind.XHPClose let is_type_constant = has_kind SyntaxKind.TypeConstant let is_vector_type_specifier = has_kind SyntaxKind.VectorTypeSpecifier let is_keyset_type_specifier = has_kind SyntaxKind.KeysetTypeSpecifier let is_tuple_type_explicit_specifier = has_kind SyntaxKind.TupleTypeExplicitSpecifier let is_varray_type_specifier = has_kind SyntaxKind.VarrayTypeSpecifier let is_function_ctx_type_specifier = has_kind SyntaxKind.FunctionCtxTypeSpecifier let is_type_parameter = has_kind SyntaxKind.TypeParameter let is_type_constraint = has_kind SyntaxKind.TypeConstraint let is_context_constraint = has_kind SyntaxKind.ContextConstraint let is_darray_type_specifier = has_kind SyntaxKind.DarrayTypeSpecifier let is_dictionary_type_specifier = has_kind SyntaxKind.DictionaryTypeSpecifier let is_closure_type_specifier = has_kind SyntaxKind.ClosureTypeSpecifier let is_closure_parameter_type_specifier = has_kind SyntaxKind.ClosureParameterTypeSpecifier let is_type_refinement = has_kind SyntaxKind.TypeRefinement let is_type_in_refinement = has_kind SyntaxKind.TypeInRefinement let is_ctx_in_refinement = has_kind SyntaxKind.CtxInRefinement let is_classname_type_specifier = has_kind SyntaxKind.ClassnameTypeSpecifier let is_field_specifier = has_kind SyntaxKind.FieldSpecifier let is_field_initializer = has_kind SyntaxKind.FieldInitializer let is_shape_type_specifier = has_kind SyntaxKind.ShapeTypeSpecifier let is_shape_expression = has_kind SyntaxKind.ShapeExpression let is_tuple_expression = has_kind SyntaxKind.TupleExpression let is_generic_type_specifier = has_kind SyntaxKind.GenericTypeSpecifier let is_nullable_type_specifier = has_kind SyntaxKind.NullableTypeSpecifier let is_like_type_specifier = has_kind SyntaxKind.LikeTypeSpecifier let is_soft_type_specifier = has_kind SyntaxKind.SoftTypeSpecifier let is_attributized_specifier = has_kind SyntaxKind.AttributizedSpecifier let is_reified_type_argument = has_kind SyntaxKind.ReifiedTypeArgument let is_type_arguments = has_kind SyntaxKind.TypeArguments let is_type_parameters = has_kind SyntaxKind.TypeParameters let is_tuple_type_specifier = has_kind SyntaxKind.TupleTypeSpecifier let is_union_type_specifier = has_kind SyntaxKind.UnionTypeSpecifier let is_intersection_type_specifier = has_kind SyntaxKind.IntersectionTypeSpecifier let is_error = has_kind SyntaxKind.ErrorSyntax let is_list_item = has_kind SyntaxKind.ListItem let is_enum_class_label_expression = has_kind SyntaxKind.EnumClassLabelExpression let is_module_declaration = has_kind SyntaxKind.ModuleDeclaration let is_module_exports = has_kind SyntaxKind.ModuleExports let is_module_imports = has_kind SyntaxKind.ModuleImports let is_module_membership_declaration = has_kind SyntaxKind.ModuleMembershipDeclaration let is_package_expression = has_kind SyntaxKind.PackageExpression let is_loop_statement node = is_for_statement node || is_foreach_statement node || is_while_statement node || is_do_statement node let is_separable_prefix node = match syntax node with | Token t -> begin TokenKind.( match Token.kind t with | PlusPlus | MinusMinus -> false | _ -> true) end | _ -> true let is_specific_token kind node = match syntax node with | Token t -> TokenKind.equal (Token.kind t) kind | _ -> false let is_namespace_prefix node = match syntax node with | QualifiedName e -> begin match List.last (syntax_node_to_list e.qualified_name_parts) with | None -> false | Some p -> begin match syntax p with | ListItem p -> not (is_missing p.list_separator) | _ -> false end end | _ -> false let has_leading_trivia kind token = List.exists (Token.leading token) ~f:(fun trivia -> Full_fidelity_trivia_kind.equal (Token.Trivia.kind trivia) kind) let is_external e = is_specific_token TokenKind.Semicolon e || is_missing e let is_name = is_specific_token TokenKind.Name let is_construct = is_specific_token TokenKind.Construct let is_static = is_specific_token TokenKind.Static let is_private = is_specific_token TokenKind.Private let is_public = is_specific_token TokenKind.Public let is_protected = is_specific_token TokenKind.Protected let is_abstract = is_specific_token TokenKind.Abstract let is_final = is_specific_token TokenKind.Final let is_async = is_specific_token TokenKind.Async let is_void = is_specific_token TokenKind.Void let is_left_brace = is_specific_token TokenKind.LeftBrace let is_ellipsis = is_specific_token TokenKind.DotDotDot let is_comma = is_specific_token TokenKind.Comma let is_ampersand = is_specific_token TokenKind.Ampersand let is_inout = is_specific_token TokenKind.Inout let syntax_list_fold ~init ~f node = match syntax node with | SyntaxList sl -> List.fold_left ~init ~f:(fun init li -> match syntax li with | ListItem { list_item; _ } -> f init list_item | Missing -> init | _ -> f init li) sl | Missing -> init | _ -> f init node let fold_over_children f acc syntax = match syntax with | Missing -> acc | Token _ -> acc | SyntaxList items -> List.fold_left ~f ~init:acc items | EndOfFile { end_of_file_token } -> let acc = f acc end_of_file_token in acc | Script { script_declarations } -> let acc = f acc script_declarations in acc | QualifiedName { qualified_name_parts } -> let acc = f acc qualified_name_parts in acc | ModuleName { module_name_parts } -> let acc = f acc module_name_parts in acc | SimpleTypeSpecifier { simple_type_specifier } -> let acc = f acc simple_type_specifier in acc | LiteralExpression { literal_expression } -> let acc = f acc literal_expression in acc | PrefixedStringExpression { prefixed_string_name; prefixed_string_str } -> let acc = f acc prefixed_string_name in let acc = f acc prefixed_string_str in acc | PrefixedCodeExpression { prefixed_code_prefix; prefixed_code_left_backtick; prefixed_code_body; prefixed_code_right_backtick; } -> let acc = f acc prefixed_code_prefix in let acc = f acc prefixed_code_left_backtick in let acc = f acc prefixed_code_body in let acc = f acc prefixed_code_right_backtick in acc | VariableExpression { variable_expression } -> let acc = f acc variable_expression in acc | PipeVariableExpression { pipe_variable_expression } -> let acc = f acc pipe_variable_expression in acc | FileAttributeSpecification { file_attribute_specification_left_double_angle; file_attribute_specification_keyword; file_attribute_specification_colon; file_attribute_specification_attributes; file_attribute_specification_right_double_angle; } -> let acc = f acc file_attribute_specification_left_double_angle in let acc = f acc file_attribute_specification_keyword in let acc = f acc file_attribute_specification_colon in let acc = f acc file_attribute_specification_attributes in let acc = f acc file_attribute_specification_right_double_angle in acc | EnumDeclaration { enum_attribute_spec; enum_modifiers; enum_keyword; enum_name; enum_colon; enum_base; enum_type; enum_left_brace; enum_use_clauses; enum_enumerators; enum_right_brace; } -> let acc = f acc enum_attribute_spec in let acc = f acc enum_modifiers in let acc = f acc enum_keyword in let acc = f acc enum_name in let acc = f acc enum_colon in let acc = f acc enum_base in let acc = f acc enum_type in let acc = f acc enum_left_brace in let acc = f acc enum_use_clauses in let acc = f acc enum_enumerators in let acc = f acc enum_right_brace in acc | EnumUse { enum_use_keyword; enum_use_names; enum_use_semicolon } -> let acc = f acc enum_use_keyword in let acc = f acc enum_use_names in let acc = f acc enum_use_semicolon in acc | Enumerator { enumerator_name; enumerator_equal; enumerator_value; enumerator_semicolon; } -> let acc = f acc enumerator_name in let acc = f acc enumerator_equal in let acc = f acc enumerator_value in let acc = f acc enumerator_semicolon in acc | EnumClassDeclaration { enum_class_attribute_spec; enum_class_modifiers; enum_class_enum_keyword; enum_class_class_keyword; enum_class_name; enum_class_colon; enum_class_base; enum_class_extends; enum_class_extends_list; enum_class_left_brace; enum_class_elements; enum_class_right_brace; } -> let acc = f acc enum_class_attribute_spec in let acc = f acc enum_class_modifiers in let acc = f acc enum_class_enum_keyword in let acc = f acc enum_class_class_keyword in let acc = f acc enum_class_name in let acc = f acc enum_class_colon in let acc = f acc enum_class_base in let acc = f acc enum_class_extends in let acc = f acc enum_class_extends_list in let acc = f acc enum_class_left_brace in let acc = f acc enum_class_elements in let acc = f acc enum_class_right_brace in acc | EnumClassEnumerator { enum_class_enumerator_modifiers; enum_class_enumerator_type; enum_class_enumerator_name; enum_class_enumerator_initializer; enum_class_enumerator_semicolon; } -> let acc = f acc enum_class_enumerator_modifiers in let acc = f acc enum_class_enumerator_type in let acc = f acc enum_class_enumerator_name in let acc = f acc enum_class_enumerator_initializer in let acc = f acc enum_class_enumerator_semicolon in acc | AliasDeclaration { alias_attribute_spec; alias_modifiers; alias_module_kw_opt; alias_keyword; alias_name; alias_generic_parameter; alias_constraint; alias_equal; alias_type; alias_semicolon; } -> let acc = f acc alias_attribute_spec in let acc = f acc alias_modifiers in let acc = f acc alias_module_kw_opt in let acc = f acc alias_keyword in let acc = f acc alias_name in let acc = f acc alias_generic_parameter in let acc = f acc alias_constraint in let acc = f acc alias_equal in let acc = f acc alias_type in let acc = f acc alias_semicolon in acc | ContextAliasDeclaration { ctx_alias_attribute_spec; ctx_alias_keyword; ctx_alias_name; ctx_alias_generic_parameter; ctx_alias_as_constraint; ctx_alias_equal; ctx_alias_context; ctx_alias_semicolon; } -> let acc = f acc ctx_alias_attribute_spec in let acc = f acc ctx_alias_keyword in let acc = f acc ctx_alias_name in let acc = f acc ctx_alias_generic_parameter in let acc = f acc ctx_alias_as_constraint in let acc = f acc ctx_alias_equal in let acc = f acc ctx_alias_context in let acc = f acc ctx_alias_semicolon in acc | CaseTypeDeclaration { case_type_attribute_spec; case_type_modifiers; case_type_case_keyword; case_type_type_keyword; case_type_name; case_type_generic_parameter; case_type_as; case_type_bounds; case_type_equal; case_type_variants; case_type_semicolon; } -> let acc = f acc case_type_attribute_spec in let acc = f acc case_type_modifiers in let acc = f acc case_type_case_keyword in let acc = f acc case_type_type_keyword in let acc = f acc case_type_name in let acc = f acc case_type_generic_parameter in let acc = f acc case_type_as in let acc = f acc case_type_bounds in let acc = f acc case_type_equal in let acc = f acc case_type_variants in let acc = f acc case_type_semicolon in acc | CaseTypeVariant { case_type_variant_bar; case_type_variant_type } -> let acc = f acc case_type_variant_bar in let acc = f acc case_type_variant_type in acc | PropertyDeclaration { property_attribute_spec; property_modifiers; property_type; property_declarators; property_semicolon; } -> let acc = f acc property_attribute_spec in let acc = f acc property_modifiers in let acc = f acc property_type in let acc = f acc property_declarators in let acc = f acc property_semicolon in acc | PropertyDeclarator { property_name; property_initializer } -> let acc = f acc property_name in let acc = f acc property_initializer in acc | NamespaceDeclaration { namespace_header; namespace_body } -> let acc = f acc namespace_header in let acc = f acc namespace_body in acc | NamespaceDeclarationHeader { namespace_keyword; namespace_name } -> let acc = f acc namespace_keyword in let acc = f acc namespace_name in acc | NamespaceBody { namespace_left_brace; namespace_declarations; namespace_right_brace; } -> let acc = f acc namespace_left_brace in let acc = f acc namespace_declarations in let acc = f acc namespace_right_brace in acc | NamespaceEmptyBody { namespace_semicolon } -> let acc = f acc namespace_semicolon in acc | NamespaceUseDeclaration { namespace_use_keyword; namespace_use_kind; namespace_use_clauses; namespace_use_semicolon; } -> let acc = f acc namespace_use_keyword in let acc = f acc namespace_use_kind in let acc = f acc namespace_use_clauses in let acc = f acc namespace_use_semicolon in acc | NamespaceGroupUseDeclaration { namespace_group_use_keyword; namespace_group_use_kind; namespace_group_use_prefix; namespace_group_use_left_brace; namespace_group_use_clauses; namespace_group_use_right_brace; namespace_group_use_semicolon; } -> let acc = f acc namespace_group_use_keyword in let acc = f acc namespace_group_use_kind in let acc = f acc namespace_group_use_prefix in let acc = f acc namespace_group_use_left_brace in let acc = f acc namespace_group_use_clauses in let acc = f acc namespace_group_use_right_brace in let acc = f acc namespace_group_use_semicolon in acc | NamespaceUseClause { namespace_use_clause_kind; namespace_use_name; namespace_use_as; namespace_use_alias; } -> let acc = f acc namespace_use_clause_kind in let acc = f acc namespace_use_name in let acc = f acc namespace_use_as in let acc = f acc namespace_use_alias in acc | FunctionDeclaration { function_attribute_spec; function_declaration_header; function_body; } -> let acc = f acc function_attribute_spec in let acc = f acc function_declaration_header in let acc = f acc function_body in acc | FunctionDeclarationHeader { function_modifiers; function_keyword; function_name; function_type_parameter_list; function_left_paren; function_parameter_list; function_right_paren; function_contexts; function_colon; function_readonly_return; function_type; function_where_clause; } -> let acc = f acc function_modifiers in let acc = f acc function_keyword in let acc = f acc function_name in let acc = f acc function_type_parameter_list in let acc = f acc function_left_paren in let acc = f acc function_parameter_list in let acc = f acc function_right_paren in let acc = f acc function_contexts in let acc = f acc function_colon in let acc = f acc function_readonly_return in let acc = f acc function_type in let acc = f acc function_where_clause in acc | Contexts { contexts_left_bracket; contexts_types; contexts_right_bracket } -> let acc = f acc contexts_left_bracket in let acc = f acc contexts_types in let acc = f acc contexts_right_bracket in acc | WhereClause { where_clause_keyword; where_clause_constraints } -> let acc = f acc where_clause_keyword in let acc = f acc where_clause_constraints in acc | WhereConstraint { where_constraint_left_type; where_constraint_operator; where_constraint_right_type; } -> let acc = f acc where_constraint_left_type in let acc = f acc where_constraint_operator in let acc = f acc where_constraint_right_type in acc | MethodishDeclaration { methodish_attribute; methodish_function_decl_header; methodish_function_body; methodish_semicolon; } -> let acc = f acc methodish_attribute in let acc = f acc methodish_function_decl_header in let acc = f acc methodish_function_body in let acc = f acc methodish_semicolon in acc | MethodishTraitResolution { methodish_trait_attribute; methodish_trait_function_decl_header; methodish_trait_equal; methodish_trait_name; methodish_trait_semicolon; } -> let acc = f acc methodish_trait_attribute in let acc = f acc methodish_trait_function_decl_header in let acc = f acc methodish_trait_equal in let acc = f acc methodish_trait_name in let acc = f acc methodish_trait_semicolon in acc | ClassishDeclaration { classish_attribute; classish_modifiers; classish_xhp; classish_keyword; classish_name; classish_type_parameters; classish_extends_keyword; classish_extends_list; classish_implements_keyword; classish_implements_list; classish_where_clause; classish_body; } -> let acc = f acc classish_attribute in let acc = f acc classish_modifiers in let acc = f acc classish_xhp in let acc = f acc classish_keyword in let acc = f acc classish_name in let acc = f acc classish_type_parameters in let acc = f acc classish_extends_keyword in let acc = f acc classish_extends_list in let acc = f acc classish_implements_keyword in let acc = f acc classish_implements_list in let acc = f acc classish_where_clause in let acc = f acc classish_body in acc | ClassishBody { classish_body_left_brace; classish_body_elements; classish_body_right_brace; } -> let acc = f acc classish_body_left_brace in let acc = f acc classish_body_elements in let acc = f acc classish_body_right_brace in acc | TraitUse { trait_use_keyword; trait_use_names; trait_use_semicolon } -> let acc = f acc trait_use_keyword in let acc = f acc trait_use_names in let acc = f acc trait_use_semicolon in acc | RequireClause { require_keyword; require_kind; require_name; require_semicolon } -> let acc = f acc require_keyword in let acc = f acc require_kind in let acc = f acc require_name in let acc = f acc require_semicolon in acc | ConstDeclaration { const_attribute_spec; const_modifiers; const_keyword; const_type_specifier; const_declarators; const_semicolon; } -> let acc = f acc const_attribute_spec in let acc = f acc const_modifiers in let acc = f acc const_keyword in let acc = f acc const_type_specifier in let acc = f acc const_declarators in let acc = f acc const_semicolon in acc | ConstantDeclarator { constant_declarator_name; constant_declarator_initializer } -> let acc = f acc constant_declarator_name in let acc = f acc constant_declarator_initializer in acc | TypeConstDeclaration { type_const_attribute_spec; type_const_modifiers; type_const_keyword; type_const_type_keyword; type_const_name; type_const_type_parameters; type_const_type_constraints; type_const_equal; type_const_type_specifier; type_const_semicolon; } -> let acc = f acc type_const_attribute_spec in let acc = f acc type_const_modifiers in let acc = f acc type_const_keyword in let acc = f acc type_const_type_keyword in let acc = f acc type_const_name in let acc = f acc type_const_type_parameters in let acc = f acc type_const_type_constraints in let acc = f acc type_const_equal in let acc = f acc type_const_type_specifier in let acc = f acc type_const_semicolon in acc | ContextConstDeclaration { context_const_modifiers; context_const_const_keyword; context_const_ctx_keyword; context_const_name; context_const_type_parameters; context_const_constraint; context_const_equal; context_const_ctx_list; context_const_semicolon; } -> let acc = f acc context_const_modifiers in let acc = f acc context_const_const_keyword in let acc = f acc context_const_ctx_keyword in let acc = f acc context_const_name in let acc = f acc context_const_type_parameters in let acc = f acc context_const_constraint in let acc = f acc context_const_equal in let acc = f acc context_const_ctx_list in let acc = f acc context_const_semicolon in acc | DecoratedExpression { decorated_expression_decorator; decorated_expression_expression } -> let acc = f acc decorated_expression_decorator in let acc = f acc decorated_expression_expression in acc | ParameterDeclaration { parameter_attribute; parameter_visibility; parameter_call_convention; parameter_readonly; parameter_type; parameter_name; parameter_default_value; } -> let acc = f acc parameter_attribute in let acc = f acc parameter_visibility in let acc = f acc parameter_call_convention in let acc = f acc parameter_readonly in let acc = f acc parameter_type in let acc = f acc parameter_name in let acc = f acc parameter_default_value in acc | VariadicParameter { variadic_parameter_call_convention; variadic_parameter_type; variadic_parameter_ellipsis; } -> let acc = f acc variadic_parameter_call_convention in let acc = f acc variadic_parameter_type in let acc = f acc variadic_parameter_ellipsis in acc | OldAttributeSpecification { old_attribute_specification_left_double_angle; old_attribute_specification_attributes; old_attribute_specification_right_double_angle; } -> let acc = f acc old_attribute_specification_left_double_angle in let acc = f acc old_attribute_specification_attributes in let acc = f acc old_attribute_specification_right_double_angle in acc | AttributeSpecification { attribute_specification_attributes } -> let acc = f acc attribute_specification_attributes in acc | Attribute { attribute_at; attribute_attribute_name } -> let acc = f acc attribute_at in let acc = f acc attribute_attribute_name in acc | InclusionExpression { inclusion_require; inclusion_filename } -> let acc = f acc inclusion_require in let acc = f acc inclusion_filename in acc | InclusionDirective { inclusion_expression; inclusion_semicolon } -> let acc = f acc inclusion_expression in let acc = f acc inclusion_semicolon in acc | CompoundStatement { compound_left_brace; compound_statements; compound_right_brace } -> let acc = f acc compound_left_brace in let acc = f acc compound_statements in let acc = f acc compound_right_brace in acc | ExpressionStatement { expression_statement_expression; expression_statement_semicolon } -> let acc = f acc expression_statement_expression in let acc = f acc expression_statement_semicolon in acc | MarkupSection { markup_hashbang; markup_suffix } -> let acc = f acc markup_hashbang in let acc = f acc markup_suffix in acc | MarkupSuffix { markup_suffix_less_than_question; markup_suffix_name } -> let acc = f acc markup_suffix_less_than_question in let acc = f acc markup_suffix_name in acc | UnsetStatement { unset_keyword; unset_left_paren; unset_variables; unset_right_paren; unset_semicolon; } -> let acc = f acc unset_keyword in let acc = f acc unset_left_paren in let acc = f acc unset_variables in let acc = f acc unset_right_paren in let acc = f acc unset_semicolon in acc | DeclareLocalStatement { declare_local_keyword; declare_local_variable; declare_local_colon; declare_local_type; declare_local_initializer; declare_local_semicolon; } -> let acc = f acc declare_local_keyword in let acc = f acc declare_local_variable in let acc = f acc declare_local_colon in let acc = f acc declare_local_type in let acc = f acc declare_local_initializer in let acc = f acc declare_local_semicolon in acc | UsingStatementBlockScoped { using_block_await_keyword; using_block_using_keyword; using_block_left_paren; using_block_expressions; using_block_right_paren; using_block_body; } -> let acc = f acc using_block_await_keyword in let acc = f acc using_block_using_keyword in let acc = f acc using_block_left_paren in let acc = f acc using_block_expressions in let acc = f acc using_block_right_paren in let acc = f acc using_block_body in acc | UsingStatementFunctionScoped { using_function_await_keyword; using_function_using_keyword; using_function_expression; using_function_semicolon; } -> let acc = f acc using_function_await_keyword in let acc = f acc using_function_using_keyword in let acc = f acc using_function_expression in let acc = f acc using_function_semicolon in acc | WhileStatement { while_keyword; while_left_paren; while_condition; while_right_paren; while_body; } -> let acc = f acc while_keyword in let acc = f acc while_left_paren in let acc = f acc while_condition in let acc = f acc while_right_paren in let acc = f acc while_body in acc | IfStatement { if_keyword; if_left_paren; if_condition; if_right_paren; if_statement; if_else_clause; } -> let acc = f acc if_keyword in let acc = f acc if_left_paren in let acc = f acc if_condition in let acc = f acc if_right_paren in let acc = f acc if_statement in let acc = f acc if_else_clause in acc | ElseClause { else_keyword; else_statement } -> let acc = f acc else_keyword in let acc = f acc else_statement in acc | TryStatement { try_keyword; try_compound_statement; try_catch_clauses; try_finally_clause; } -> let acc = f acc try_keyword in let acc = f acc try_compound_statement in let acc = f acc try_catch_clauses in let acc = f acc try_finally_clause in acc | CatchClause { catch_keyword; catch_left_paren; catch_type; catch_variable; catch_right_paren; catch_body; } -> let acc = f acc catch_keyword in let acc = f acc catch_left_paren in let acc = f acc catch_type in let acc = f acc catch_variable in let acc = f acc catch_right_paren in let acc = f acc catch_body in acc | FinallyClause { finally_keyword; finally_body } -> let acc = f acc finally_keyword in let acc = f acc finally_body in acc | DoStatement { do_keyword; do_body; do_while_keyword; do_left_paren; do_condition; do_right_paren; do_semicolon; } -> let acc = f acc do_keyword in let acc = f acc do_body in let acc = f acc do_while_keyword in let acc = f acc do_left_paren in let acc = f acc do_condition in let acc = f acc do_right_paren in let acc = f acc do_semicolon in acc | ForStatement { for_keyword; for_left_paren; for_initializer; for_first_semicolon; for_control; for_second_semicolon; for_end_of_loop; for_right_paren; for_body; } -> let acc = f acc for_keyword in let acc = f acc for_left_paren in let acc = f acc for_initializer in let acc = f acc for_first_semicolon in let acc = f acc for_control in let acc = f acc for_second_semicolon in let acc = f acc for_end_of_loop in let acc = f acc for_right_paren in let acc = f acc for_body in acc | ForeachStatement { foreach_keyword; foreach_left_paren; foreach_collection; foreach_await_keyword; foreach_as; foreach_key; foreach_arrow; foreach_value; foreach_right_paren; foreach_body; } -> let acc = f acc foreach_keyword in let acc = f acc foreach_left_paren in let acc = f acc foreach_collection in let acc = f acc foreach_await_keyword in let acc = f acc foreach_as in let acc = f acc foreach_key in let acc = f acc foreach_arrow in let acc = f acc foreach_value in let acc = f acc foreach_right_paren in let acc = f acc foreach_body in acc | SwitchStatement { switch_keyword; switch_left_paren; switch_expression; switch_right_paren; switch_left_brace; switch_sections; switch_right_brace; } -> let acc = f acc switch_keyword in let acc = f acc switch_left_paren in let acc = f acc switch_expression in let acc = f acc switch_right_paren in let acc = f acc switch_left_brace in let acc = f acc switch_sections in let acc = f acc switch_right_brace in acc | SwitchSection { switch_section_labels; switch_section_statements; switch_section_fallthrough; } -> let acc = f acc switch_section_labels in let acc = f acc switch_section_statements in let acc = f acc switch_section_fallthrough in acc | SwitchFallthrough { fallthrough_keyword; fallthrough_semicolon } -> let acc = f acc fallthrough_keyword in let acc = f acc fallthrough_semicolon in acc | CaseLabel { case_keyword; case_expression; case_colon } -> let acc = f acc case_keyword in let acc = f acc case_expression in let acc = f acc case_colon in acc | DefaultLabel { default_keyword; default_colon } -> let acc = f acc default_keyword in let acc = f acc default_colon in acc | MatchStatement { match_statement_keyword; match_statement_left_paren; match_statement_expression; match_statement_right_paren; match_statement_left_brace; match_statement_arms; match_statement_right_brace; } -> let acc = f acc match_statement_keyword in let acc = f acc match_statement_left_paren in let acc = f acc match_statement_expression in let acc = f acc match_statement_right_paren in let acc = f acc match_statement_left_brace in let acc = f acc match_statement_arms in let acc = f acc match_statement_right_brace in acc | MatchStatementArm { match_statement_arm_pattern; match_statement_arm_arrow; match_statement_arm_body; } -> let acc = f acc match_statement_arm_pattern in let acc = f acc match_statement_arm_arrow in let acc = f acc match_statement_arm_body in acc | ReturnStatement { return_keyword; return_expression; return_semicolon } -> let acc = f acc return_keyword in let acc = f acc return_expression in let acc = f acc return_semicolon in acc | YieldBreakStatement { yield_break_keyword; yield_break_break; yield_break_semicolon } -> let acc = f acc yield_break_keyword in let acc = f acc yield_break_break in let acc = f acc yield_break_semicolon in acc | ThrowStatement { throw_keyword; throw_expression; throw_semicolon } -> let acc = f acc throw_keyword in let acc = f acc throw_expression in let acc = f acc throw_semicolon in acc | BreakStatement { break_keyword; break_semicolon } -> let acc = f acc break_keyword in let acc = f acc break_semicolon in acc | ContinueStatement { continue_keyword; continue_semicolon } -> let acc = f acc continue_keyword in let acc = f acc continue_semicolon in acc | EchoStatement { echo_keyword; echo_expressions; echo_semicolon } -> let acc = f acc echo_keyword in let acc = f acc echo_expressions in let acc = f acc echo_semicolon in acc | ConcurrentStatement { concurrent_keyword; concurrent_statement } -> let acc = f acc concurrent_keyword in let acc = f acc concurrent_statement in acc | SimpleInitializer { simple_initializer_equal; simple_initializer_value } -> let acc = f acc simple_initializer_equal in let acc = f acc simple_initializer_value in acc | AnonymousClass { anonymous_class_class_keyword; anonymous_class_left_paren; anonymous_class_argument_list; anonymous_class_right_paren; anonymous_class_extends_keyword; anonymous_class_extends_list; anonymous_class_implements_keyword; anonymous_class_implements_list; anonymous_class_body; } -> let acc = f acc anonymous_class_class_keyword in let acc = f acc anonymous_class_left_paren in let acc = f acc anonymous_class_argument_list in let acc = f acc anonymous_class_right_paren in let acc = f acc anonymous_class_extends_keyword in let acc = f acc anonymous_class_extends_list in let acc = f acc anonymous_class_implements_keyword in let acc = f acc anonymous_class_implements_list in let acc = f acc anonymous_class_body in acc | AnonymousFunction { anonymous_attribute_spec; anonymous_async_keyword; anonymous_function_keyword; anonymous_left_paren; anonymous_parameters; anonymous_right_paren; anonymous_ctx_list; anonymous_colon; anonymous_readonly_return; anonymous_type; anonymous_use; anonymous_body; } -> let acc = f acc anonymous_attribute_spec in let acc = f acc anonymous_async_keyword in let acc = f acc anonymous_function_keyword in let acc = f acc anonymous_left_paren in let acc = f acc anonymous_parameters in let acc = f acc anonymous_right_paren in let acc = f acc anonymous_ctx_list in let acc = f acc anonymous_colon in let acc = f acc anonymous_readonly_return in let acc = f acc anonymous_type in let acc = f acc anonymous_use in let acc = f acc anonymous_body in acc | AnonymousFunctionUseClause { anonymous_use_keyword; anonymous_use_left_paren; anonymous_use_variables; anonymous_use_right_paren; } -> let acc = f acc anonymous_use_keyword in let acc = f acc anonymous_use_left_paren in let acc = f acc anonymous_use_variables in let acc = f acc anonymous_use_right_paren in acc | VariablePattern { variable_pattern_variable } -> let acc = f acc variable_pattern_variable in acc | ConstructorPattern { constructor_pattern_constructor; constructor_pattern_left_paren; constructor_pattern_members; constructor_pattern_right_paren; } -> let acc = f acc constructor_pattern_constructor in let acc = f acc constructor_pattern_left_paren in let acc = f acc constructor_pattern_members in let acc = f acc constructor_pattern_right_paren in acc | RefinementPattern { refinement_pattern_variable; refinement_pattern_colon; refinement_pattern_specifier; } -> let acc = f acc refinement_pattern_variable in let acc = f acc refinement_pattern_colon in let acc = f acc refinement_pattern_specifier in acc | LambdaExpression { lambda_attribute_spec; lambda_async; lambda_signature; lambda_arrow; lambda_body; } -> let acc = f acc lambda_attribute_spec in let acc = f acc lambda_async in let acc = f acc lambda_signature in let acc = f acc lambda_arrow in let acc = f acc lambda_body in acc | LambdaSignature { lambda_left_paren; lambda_parameters; lambda_right_paren; lambda_contexts; lambda_colon; lambda_readonly_return; lambda_type; } -> let acc = f acc lambda_left_paren in let acc = f acc lambda_parameters in let acc = f acc lambda_right_paren in let acc = f acc lambda_contexts in let acc = f acc lambda_colon in let acc = f acc lambda_readonly_return in let acc = f acc lambda_type in acc | CastExpression { cast_left_paren; cast_type; cast_right_paren; cast_operand } -> let acc = f acc cast_left_paren in let acc = f acc cast_type in let acc = f acc cast_right_paren in let acc = f acc cast_operand in acc | ScopeResolutionExpression { scope_resolution_qualifier; scope_resolution_operator; scope_resolution_name; } -> let acc = f acc scope_resolution_qualifier in let acc = f acc scope_resolution_operator in let acc = f acc scope_resolution_name in acc | MemberSelectionExpression { member_object; member_operator; member_name } -> let acc = f acc member_object in let acc = f acc member_operator in let acc = f acc member_name in acc | SafeMemberSelectionExpression { safe_member_object; safe_member_operator; safe_member_name } -> let acc = f acc safe_member_object in let acc = f acc safe_member_operator in let acc = f acc safe_member_name in acc | EmbeddedMemberSelectionExpression { embedded_member_object; embedded_member_operator; embedded_member_name; } -> let acc = f acc embedded_member_object in let acc = f acc embedded_member_operator in let acc = f acc embedded_member_name in acc | YieldExpression { yield_keyword; yield_operand } -> let acc = f acc yield_keyword in let acc = f acc yield_operand in acc | PrefixUnaryExpression { prefix_unary_operator; prefix_unary_operand } -> let acc = f acc prefix_unary_operator in let acc = f acc prefix_unary_operand in acc | PostfixUnaryExpression { postfix_unary_operand; postfix_unary_operator } -> let acc = f acc postfix_unary_operand in let acc = f acc postfix_unary_operator in acc | BinaryExpression { binary_left_operand; binary_operator; binary_right_operand } -> let acc = f acc binary_left_operand in let acc = f acc binary_operator in let acc = f acc binary_right_operand in acc | IsExpression { is_left_operand; is_operator; is_right_operand } -> let acc = f acc is_left_operand in let acc = f acc is_operator in let acc = f acc is_right_operand in acc | AsExpression { as_left_operand; as_operator; as_right_operand } -> let acc = f acc as_left_operand in let acc = f acc as_operator in let acc = f acc as_right_operand in acc | NullableAsExpression { nullable_as_left_operand; nullable_as_operator; nullable_as_right_operand; } -> let acc = f acc nullable_as_left_operand in let acc = f acc nullable_as_operator in let acc = f acc nullable_as_right_operand in acc | UpcastExpression { upcast_left_operand; upcast_operator; upcast_right_operand } -> let acc = f acc upcast_left_operand in let acc = f acc upcast_operator in let acc = f acc upcast_right_operand in acc | ConditionalExpression { conditional_test; conditional_question; conditional_consequence; conditional_colon; conditional_alternative; } -> let acc = f acc conditional_test in let acc = f acc conditional_question in let acc = f acc conditional_consequence in let acc = f acc conditional_colon in let acc = f acc conditional_alternative in acc | EvalExpression { eval_keyword; eval_left_paren; eval_argument; eval_right_paren } -> let acc = f acc eval_keyword in let acc = f acc eval_left_paren in let acc = f acc eval_argument in let acc = f acc eval_right_paren in acc | IssetExpression { isset_keyword; isset_left_paren; isset_argument_list; isset_right_paren; } -> let acc = f acc isset_keyword in let acc = f acc isset_left_paren in let acc = f acc isset_argument_list in let acc = f acc isset_right_paren in acc | FunctionCallExpression { function_call_receiver; function_call_type_args; function_call_left_paren; function_call_argument_list; function_call_right_paren; } -> let acc = f acc function_call_receiver in let acc = f acc function_call_type_args in let acc = f acc function_call_left_paren in let acc = f acc function_call_argument_list in let acc = f acc function_call_right_paren in acc | FunctionPointerExpression { function_pointer_receiver; function_pointer_type_args } -> let acc = f acc function_pointer_receiver in let acc = f acc function_pointer_type_args in acc | ParenthesizedExpression { parenthesized_expression_left_paren; parenthesized_expression_expression; parenthesized_expression_right_paren; } -> let acc = f acc parenthesized_expression_left_paren in let acc = f acc parenthesized_expression_expression in let acc = f acc parenthesized_expression_right_paren in acc | BracedExpression { braced_expression_left_brace; braced_expression_expression; braced_expression_right_brace; } -> let acc = f acc braced_expression_left_brace in let acc = f acc braced_expression_expression in let acc = f acc braced_expression_right_brace in acc | ETSpliceExpression { et_splice_expression_dollar; et_splice_expression_left_brace; et_splice_expression_expression; et_splice_expression_right_brace; } -> let acc = f acc et_splice_expression_dollar in let acc = f acc et_splice_expression_left_brace in let acc = f acc et_splice_expression_expression in let acc = f acc et_splice_expression_right_brace in acc | EmbeddedBracedExpression { embedded_braced_expression_left_brace; embedded_braced_expression_expression; embedded_braced_expression_right_brace; } -> let acc = f acc embedded_braced_expression_left_brace in let acc = f acc embedded_braced_expression_expression in let acc = f acc embedded_braced_expression_right_brace in acc | ListExpression { list_keyword; list_left_paren; list_members; list_right_paren } -> let acc = f acc list_keyword in let acc = f acc list_left_paren in let acc = f acc list_members in let acc = f acc list_right_paren in acc | CollectionLiteralExpression { collection_literal_name; collection_literal_left_brace; collection_literal_initializers; collection_literal_right_brace; } -> let acc = f acc collection_literal_name in let acc = f acc collection_literal_left_brace in let acc = f acc collection_literal_initializers in let acc = f acc collection_literal_right_brace in acc | ObjectCreationExpression { object_creation_new_keyword; object_creation_object } -> let acc = f acc object_creation_new_keyword in let acc = f acc object_creation_object in acc | ConstructorCall { constructor_call_type; constructor_call_left_paren; constructor_call_argument_list; constructor_call_right_paren; } -> let acc = f acc constructor_call_type in let acc = f acc constructor_call_left_paren in let acc = f acc constructor_call_argument_list in let acc = f acc constructor_call_right_paren in acc | DarrayIntrinsicExpression { darray_intrinsic_keyword; darray_intrinsic_explicit_type; darray_intrinsic_left_bracket; darray_intrinsic_members; darray_intrinsic_right_bracket; } -> let acc = f acc darray_intrinsic_keyword in let acc = f acc darray_intrinsic_explicit_type in let acc = f acc darray_intrinsic_left_bracket in let acc = f acc darray_intrinsic_members in let acc = f acc darray_intrinsic_right_bracket in acc | DictionaryIntrinsicExpression { dictionary_intrinsic_keyword; dictionary_intrinsic_explicit_type; dictionary_intrinsic_left_bracket; dictionary_intrinsic_members; dictionary_intrinsic_right_bracket; } -> let acc = f acc dictionary_intrinsic_keyword in let acc = f acc dictionary_intrinsic_explicit_type in let acc = f acc dictionary_intrinsic_left_bracket in let acc = f acc dictionary_intrinsic_members in let acc = f acc dictionary_intrinsic_right_bracket in acc | KeysetIntrinsicExpression { keyset_intrinsic_keyword; keyset_intrinsic_explicit_type; keyset_intrinsic_left_bracket; keyset_intrinsic_members; keyset_intrinsic_right_bracket; } -> let acc = f acc keyset_intrinsic_keyword in let acc = f acc keyset_intrinsic_explicit_type in let acc = f acc keyset_intrinsic_left_bracket in let acc = f acc keyset_intrinsic_members in let acc = f acc keyset_intrinsic_right_bracket in acc | VarrayIntrinsicExpression { varray_intrinsic_keyword; varray_intrinsic_explicit_type; varray_intrinsic_left_bracket; varray_intrinsic_members; varray_intrinsic_right_bracket; } -> let acc = f acc varray_intrinsic_keyword in let acc = f acc varray_intrinsic_explicit_type in let acc = f acc varray_intrinsic_left_bracket in let acc = f acc varray_intrinsic_members in let acc = f acc varray_intrinsic_right_bracket in acc | VectorIntrinsicExpression { vector_intrinsic_keyword; vector_intrinsic_explicit_type; vector_intrinsic_left_bracket; vector_intrinsic_members; vector_intrinsic_right_bracket; } -> let acc = f acc vector_intrinsic_keyword in let acc = f acc vector_intrinsic_explicit_type in let acc = f acc vector_intrinsic_left_bracket in let acc = f acc vector_intrinsic_members in let acc = f acc vector_intrinsic_right_bracket in acc | ElementInitializer { element_key; element_arrow; element_value } -> let acc = f acc element_key in let acc = f acc element_arrow in let acc = f acc element_value in acc | SubscriptExpression { subscript_receiver; subscript_left_bracket; subscript_index; subscript_right_bracket; } -> let acc = f acc subscript_receiver in let acc = f acc subscript_left_bracket in let acc = f acc subscript_index in let acc = f acc subscript_right_bracket in acc | EmbeddedSubscriptExpression { embedded_subscript_receiver; embedded_subscript_left_bracket; embedded_subscript_index; embedded_subscript_right_bracket; } -> let acc = f acc embedded_subscript_receiver in let acc = f acc embedded_subscript_left_bracket in let acc = f acc embedded_subscript_index in let acc = f acc embedded_subscript_right_bracket in acc | AwaitableCreationExpression { awaitable_attribute_spec; awaitable_async; awaitable_compound_statement; } -> let acc = f acc awaitable_attribute_spec in let acc = f acc awaitable_async in let acc = f acc awaitable_compound_statement in acc | XHPChildrenDeclaration { xhp_children_keyword; xhp_children_expression; xhp_children_semicolon; } -> let acc = f acc xhp_children_keyword in let acc = f acc xhp_children_expression in let acc = f acc xhp_children_semicolon in acc | XHPChildrenParenthesizedList { xhp_children_list_left_paren; xhp_children_list_xhp_children; xhp_children_list_right_paren; } -> let acc = f acc xhp_children_list_left_paren in let acc = f acc xhp_children_list_xhp_children in let acc = f acc xhp_children_list_right_paren in acc | XHPCategoryDeclaration { xhp_category_keyword; xhp_category_categories; xhp_category_semicolon; } -> let acc = f acc xhp_category_keyword in let acc = f acc xhp_category_categories in let acc = f acc xhp_category_semicolon in acc | XHPEnumType { xhp_enum_like; xhp_enum_keyword; xhp_enum_left_brace; xhp_enum_values; xhp_enum_right_brace; } -> let acc = f acc xhp_enum_like in let acc = f acc xhp_enum_keyword in let acc = f acc xhp_enum_left_brace in let acc = f acc xhp_enum_values in let acc = f acc xhp_enum_right_brace in acc | XHPLateinit { xhp_lateinit_at; xhp_lateinit_keyword } -> let acc = f acc xhp_lateinit_at in let acc = f acc xhp_lateinit_keyword in acc | XHPRequired { xhp_required_at; xhp_required_keyword } -> let acc = f acc xhp_required_at in let acc = f acc xhp_required_keyword in acc | XHPClassAttributeDeclaration { xhp_attribute_keyword; xhp_attribute_attributes; xhp_attribute_semicolon; } -> let acc = f acc xhp_attribute_keyword in let acc = f acc xhp_attribute_attributes in let acc = f acc xhp_attribute_semicolon in acc | XHPClassAttribute { xhp_attribute_decl_type; xhp_attribute_decl_name; xhp_attribute_decl_initializer; xhp_attribute_decl_required; } -> let acc = f acc xhp_attribute_decl_type in let acc = f acc xhp_attribute_decl_name in let acc = f acc xhp_attribute_decl_initializer in let acc = f acc xhp_attribute_decl_required in acc | XHPSimpleClassAttribute { xhp_simple_class_attribute_type } -> let acc = f acc xhp_simple_class_attribute_type in acc | XHPSimpleAttribute { xhp_simple_attribute_name; xhp_simple_attribute_equal; xhp_simple_attribute_expression; } -> let acc = f acc xhp_simple_attribute_name in let acc = f acc xhp_simple_attribute_equal in let acc = f acc xhp_simple_attribute_expression in acc | XHPSpreadAttribute { xhp_spread_attribute_left_brace; xhp_spread_attribute_spread_operator; xhp_spread_attribute_expression; xhp_spread_attribute_right_brace; } -> let acc = f acc xhp_spread_attribute_left_brace in let acc = f acc xhp_spread_attribute_spread_operator in let acc = f acc xhp_spread_attribute_expression in let acc = f acc xhp_spread_attribute_right_brace in acc | XHPOpen { xhp_open_left_angle; xhp_open_name; xhp_open_attributes; xhp_open_right_angle; } -> let acc = f acc xhp_open_left_angle in let acc = f acc xhp_open_name in let acc = f acc xhp_open_attributes in let acc = f acc xhp_open_right_angle in acc | XHPExpression { xhp_open; xhp_body; xhp_close } -> let acc = f acc xhp_open in let acc = f acc xhp_body in let acc = f acc xhp_close in acc | XHPClose { xhp_close_left_angle; xhp_close_name; xhp_close_right_angle } -> let acc = f acc xhp_close_left_angle in let acc = f acc xhp_close_name in let acc = f acc xhp_close_right_angle in acc | TypeConstant { type_constant_left_type; type_constant_separator; type_constant_right_type; } -> let acc = f acc type_constant_left_type in let acc = f acc type_constant_separator in let acc = f acc type_constant_right_type in acc | VectorTypeSpecifier { vector_type_keyword; vector_type_left_angle; vector_type_type; vector_type_trailing_comma; vector_type_right_angle; } -> let acc = f acc vector_type_keyword in let acc = f acc vector_type_left_angle in let acc = f acc vector_type_type in let acc = f acc vector_type_trailing_comma in let acc = f acc vector_type_right_angle in acc | KeysetTypeSpecifier { keyset_type_keyword; keyset_type_left_angle; keyset_type_type; keyset_type_trailing_comma; keyset_type_right_angle; } -> let acc = f acc keyset_type_keyword in let acc = f acc keyset_type_left_angle in let acc = f acc keyset_type_type in let acc = f acc keyset_type_trailing_comma in let acc = f acc keyset_type_right_angle in acc | TupleTypeExplicitSpecifier { tuple_type_keyword; tuple_type_left_angle; tuple_type_types; tuple_type_right_angle; } -> let acc = f acc tuple_type_keyword in let acc = f acc tuple_type_left_angle in let acc = f acc tuple_type_types in let acc = f acc tuple_type_right_angle in acc | VarrayTypeSpecifier { varray_keyword; varray_left_angle; varray_type; varray_trailing_comma; varray_right_angle; } -> let acc = f acc varray_keyword in let acc = f acc varray_left_angle in let acc = f acc varray_type in let acc = f acc varray_trailing_comma in let acc = f acc varray_right_angle in acc | FunctionCtxTypeSpecifier { function_ctx_type_keyword; function_ctx_type_variable } -> let acc = f acc function_ctx_type_keyword in let acc = f acc function_ctx_type_variable in acc | TypeParameter { type_attribute_spec; type_reified; type_variance; type_name; type_param_params; type_constraints; } -> let acc = f acc type_attribute_spec in let acc = f acc type_reified in let acc = f acc type_variance in let acc = f acc type_name in let acc = f acc type_param_params in let acc = f acc type_constraints in acc | TypeConstraint { constraint_keyword; constraint_type } -> let acc = f acc constraint_keyword in let acc = f acc constraint_type in acc | ContextConstraint { ctx_constraint_keyword; ctx_constraint_ctx_list } -> let acc = f acc ctx_constraint_keyword in let acc = f acc ctx_constraint_ctx_list in acc | DarrayTypeSpecifier { darray_keyword; darray_left_angle; darray_key; darray_comma; darray_value; darray_trailing_comma; darray_right_angle; } -> let acc = f acc darray_keyword in let acc = f acc darray_left_angle in let acc = f acc darray_key in let acc = f acc darray_comma in let acc = f acc darray_value in let acc = f acc darray_trailing_comma in let acc = f acc darray_right_angle in acc | DictionaryTypeSpecifier { dictionary_type_keyword; dictionary_type_left_angle; dictionary_type_members; dictionary_type_right_angle; } -> let acc = f acc dictionary_type_keyword in let acc = f acc dictionary_type_left_angle in let acc = f acc dictionary_type_members in let acc = f acc dictionary_type_right_angle in acc | ClosureTypeSpecifier { closure_outer_left_paren; closure_readonly_keyword; closure_function_keyword; closure_inner_left_paren; closure_parameter_list; closure_inner_right_paren; closure_contexts; closure_colon; closure_readonly_return; closure_return_type; closure_outer_right_paren; } -> let acc = f acc closure_outer_left_paren in let acc = f acc closure_readonly_keyword in let acc = f acc closure_function_keyword in let acc = f acc closure_inner_left_paren in let acc = f acc closure_parameter_list in let acc = f acc closure_inner_right_paren in let acc = f acc closure_contexts in let acc = f acc closure_colon in let acc = f acc closure_readonly_return in let acc = f acc closure_return_type in let acc = f acc closure_outer_right_paren in acc | ClosureParameterTypeSpecifier { closure_parameter_call_convention; closure_parameter_readonly; closure_parameter_type; } -> let acc = f acc closure_parameter_call_convention in let acc = f acc closure_parameter_readonly in let acc = f acc closure_parameter_type in acc | TypeRefinement { type_refinement_type; type_refinement_keyword; type_refinement_left_brace; type_refinement_members; type_refinement_right_brace; } -> let acc = f acc type_refinement_type in let acc = f acc type_refinement_keyword in let acc = f acc type_refinement_left_brace in let acc = f acc type_refinement_members in let acc = f acc type_refinement_right_brace in acc | TypeInRefinement { type_in_refinement_keyword; type_in_refinement_name; type_in_refinement_type_parameters; type_in_refinement_constraints; type_in_refinement_equal; type_in_refinement_type; } -> let acc = f acc type_in_refinement_keyword in let acc = f acc type_in_refinement_name in let acc = f acc type_in_refinement_type_parameters in let acc = f acc type_in_refinement_constraints in let acc = f acc type_in_refinement_equal in let acc = f acc type_in_refinement_type in acc | CtxInRefinement { ctx_in_refinement_keyword; ctx_in_refinement_name; ctx_in_refinement_type_parameters; ctx_in_refinement_constraints; ctx_in_refinement_equal; ctx_in_refinement_ctx_list; } -> let acc = f acc ctx_in_refinement_keyword in let acc = f acc ctx_in_refinement_name in let acc = f acc ctx_in_refinement_type_parameters in let acc = f acc ctx_in_refinement_constraints in let acc = f acc ctx_in_refinement_equal in let acc = f acc ctx_in_refinement_ctx_list in acc | ClassnameTypeSpecifier { classname_keyword; classname_left_angle; classname_type; classname_trailing_comma; classname_right_angle; } -> let acc = f acc classname_keyword in let acc = f acc classname_left_angle in let acc = f acc classname_type in let acc = f acc classname_trailing_comma in let acc = f acc classname_right_angle in acc | FieldSpecifier { field_question; field_name; field_arrow; field_type } -> let acc = f acc field_question in let acc = f acc field_name in let acc = f acc field_arrow in let acc = f acc field_type in acc | FieldInitializer { field_initializer_name; field_initializer_arrow; field_initializer_value; } -> let acc = f acc field_initializer_name in let acc = f acc field_initializer_arrow in let acc = f acc field_initializer_value in acc | ShapeTypeSpecifier { shape_type_keyword; shape_type_left_paren; shape_type_fields; shape_type_ellipsis; shape_type_right_paren; } -> let acc = f acc shape_type_keyword in let acc = f acc shape_type_left_paren in let acc = f acc shape_type_fields in let acc = f acc shape_type_ellipsis in let acc = f acc shape_type_right_paren in acc | ShapeExpression { shape_expression_keyword; shape_expression_left_paren; shape_expression_fields; shape_expression_right_paren; } -> let acc = f acc shape_expression_keyword in let acc = f acc shape_expression_left_paren in let acc = f acc shape_expression_fields in let acc = f acc shape_expression_right_paren in acc | TupleExpression { tuple_expression_keyword; tuple_expression_left_paren; tuple_expression_items; tuple_expression_right_paren; } -> let acc = f acc tuple_expression_keyword in let acc = f acc tuple_expression_left_paren in let acc = f acc tuple_expression_items in let acc = f acc tuple_expression_right_paren in acc | GenericTypeSpecifier { generic_class_type; generic_argument_list } -> let acc = f acc generic_class_type in let acc = f acc generic_argument_list in acc | NullableTypeSpecifier { nullable_question; nullable_type } -> let acc = f acc nullable_question in let acc = f acc nullable_type in acc | LikeTypeSpecifier { like_tilde; like_type } -> let acc = f acc like_tilde in let acc = f acc like_type in acc | SoftTypeSpecifier { soft_at; soft_type } -> let acc = f acc soft_at in let acc = f acc soft_type in acc | AttributizedSpecifier { attributized_specifier_attribute_spec; attributized_specifier_type } -> let acc = f acc attributized_specifier_attribute_spec in let acc = f acc attributized_specifier_type in acc | ReifiedTypeArgument { reified_type_argument_reified; reified_type_argument_type } -> let acc = f acc reified_type_argument_reified in let acc = f acc reified_type_argument_type in acc | TypeArguments { type_arguments_left_angle; type_arguments_types; type_arguments_right_angle; } -> let acc = f acc type_arguments_left_angle in let acc = f acc type_arguments_types in let acc = f acc type_arguments_right_angle in acc | TypeParameters { type_parameters_left_angle; type_parameters_parameters; type_parameters_right_angle; } -> let acc = f acc type_parameters_left_angle in let acc = f acc type_parameters_parameters in let acc = f acc type_parameters_right_angle in acc | TupleTypeSpecifier { tuple_left_paren; tuple_types; tuple_right_paren } -> let acc = f acc tuple_left_paren in let acc = f acc tuple_types in let acc = f acc tuple_right_paren in acc | UnionTypeSpecifier { union_left_paren; union_types; union_right_paren } -> let acc = f acc union_left_paren in let acc = f acc union_types in let acc = f acc union_right_paren in acc | IntersectionTypeSpecifier { intersection_left_paren; intersection_types; intersection_right_paren; } -> let acc = f acc intersection_left_paren in let acc = f acc intersection_types in let acc = f acc intersection_right_paren in acc | ErrorSyntax { error_error } -> let acc = f acc error_error in acc | ListItem { list_item; list_separator } -> let acc = f acc list_item in let acc = f acc list_separator in acc | EnumClassLabelExpression { enum_class_label_qualifier; enum_class_label_hash; enum_class_label_expression; } -> let acc = f acc enum_class_label_qualifier in let acc = f acc enum_class_label_hash in let acc = f acc enum_class_label_expression in acc | ModuleDeclaration { module_declaration_attribute_spec; module_declaration_new_keyword; module_declaration_module_keyword; module_declaration_name; module_declaration_left_brace; module_declaration_exports; module_declaration_imports; module_declaration_right_brace; } -> let acc = f acc module_declaration_attribute_spec in let acc = f acc module_declaration_new_keyword in let acc = f acc module_declaration_module_keyword in let acc = f acc module_declaration_name in let acc = f acc module_declaration_left_brace in let acc = f acc module_declaration_exports in let acc = f acc module_declaration_imports in let acc = f acc module_declaration_right_brace in acc | ModuleExports { module_exports_exports_keyword; module_exports_left_brace; module_exports_exports; module_exports_right_brace; } -> let acc = f acc module_exports_exports_keyword in let acc = f acc module_exports_left_brace in let acc = f acc module_exports_exports in let acc = f acc module_exports_right_brace in acc | ModuleImports { module_imports_imports_keyword; module_imports_left_brace; module_imports_imports; module_imports_right_brace; } -> let acc = f acc module_imports_imports_keyword in let acc = f acc module_imports_left_brace in let acc = f acc module_imports_imports in let acc = f acc module_imports_right_brace in acc | ModuleMembershipDeclaration { module_membership_declaration_module_keyword; module_membership_declaration_name; module_membership_declaration_semicolon; } -> let acc = f acc module_membership_declaration_module_keyword in let acc = f acc module_membership_declaration_name in let acc = f acc module_membership_declaration_semicolon in acc | PackageExpression { package_expression_keyword; package_expression_name } -> let acc = f acc package_expression_keyword in let acc = f acc package_expression_name in acc (* The order that the children are returned in should match the order that they appear in the source text *) let children_from_syntax s = match s with | Missing -> [] | Token _ -> [] | SyntaxList x -> x | EndOfFile { end_of_file_token } -> [end_of_file_token] | Script { script_declarations } -> [script_declarations] | QualifiedName { qualified_name_parts } -> [qualified_name_parts] | ModuleName { module_name_parts } -> [module_name_parts] | SimpleTypeSpecifier { simple_type_specifier } -> [simple_type_specifier] | LiteralExpression { literal_expression } -> [literal_expression] | PrefixedStringExpression { prefixed_string_name; prefixed_string_str } -> [prefixed_string_name; prefixed_string_str] | PrefixedCodeExpression { prefixed_code_prefix; prefixed_code_left_backtick; prefixed_code_body; prefixed_code_right_backtick; } -> [ prefixed_code_prefix; prefixed_code_left_backtick; prefixed_code_body; prefixed_code_right_backtick; ] | VariableExpression { variable_expression } -> [variable_expression] | PipeVariableExpression { pipe_variable_expression } -> [pipe_variable_expression] | FileAttributeSpecification { file_attribute_specification_left_double_angle; file_attribute_specification_keyword; file_attribute_specification_colon; file_attribute_specification_attributes; file_attribute_specification_right_double_angle; } -> [ file_attribute_specification_left_double_angle; file_attribute_specification_keyword; file_attribute_specification_colon; file_attribute_specification_attributes; file_attribute_specification_right_double_angle; ] | EnumDeclaration { enum_attribute_spec; enum_modifiers; enum_keyword; enum_name; enum_colon; enum_base; enum_type; enum_left_brace; enum_use_clauses; enum_enumerators; enum_right_brace; } -> [ enum_attribute_spec; enum_modifiers; enum_keyword; enum_name; enum_colon; enum_base; enum_type; enum_left_brace; enum_use_clauses; enum_enumerators; enum_right_brace; ] | EnumUse { enum_use_keyword; enum_use_names; enum_use_semicolon } -> [enum_use_keyword; enum_use_names; enum_use_semicolon] | Enumerator { enumerator_name; enumerator_equal; enumerator_value; enumerator_semicolon; } -> [ enumerator_name; enumerator_equal; enumerator_value; enumerator_semicolon; ] | EnumClassDeclaration { enum_class_attribute_spec; enum_class_modifiers; enum_class_enum_keyword; enum_class_class_keyword; enum_class_name; enum_class_colon; enum_class_base; enum_class_extends; enum_class_extends_list; enum_class_left_brace; enum_class_elements; enum_class_right_brace; } -> [ enum_class_attribute_spec; enum_class_modifiers; enum_class_enum_keyword; enum_class_class_keyword; enum_class_name; enum_class_colon; enum_class_base; enum_class_extends; enum_class_extends_list; enum_class_left_brace; enum_class_elements; enum_class_right_brace; ] | EnumClassEnumerator { enum_class_enumerator_modifiers; enum_class_enumerator_type; enum_class_enumerator_name; enum_class_enumerator_initializer; enum_class_enumerator_semicolon; } -> [ enum_class_enumerator_modifiers; enum_class_enumerator_type; enum_class_enumerator_name; enum_class_enumerator_initializer; enum_class_enumerator_semicolon; ] | AliasDeclaration { alias_attribute_spec; alias_modifiers; alias_module_kw_opt; alias_keyword; alias_name; alias_generic_parameter; alias_constraint; alias_equal; alias_type; alias_semicolon; } -> [ alias_attribute_spec; alias_modifiers; alias_module_kw_opt; alias_keyword; alias_name; alias_generic_parameter; alias_constraint; alias_equal; alias_type; alias_semicolon; ] | ContextAliasDeclaration { ctx_alias_attribute_spec; ctx_alias_keyword; ctx_alias_name; ctx_alias_generic_parameter; ctx_alias_as_constraint; ctx_alias_equal; ctx_alias_context; ctx_alias_semicolon; } -> [ ctx_alias_attribute_spec; ctx_alias_keyword; ctx_alias_name; ctx_alias_generic_parameter; ctx_alias_as_constraint; ctx_alias_equal; ctx_alias_context; ctx_alias_semicolon; ] | CaseTypeDeclaration { case_type_attribute_spec; case_type_modifiers; case_type_case_keyword; case_type_type_keyword; case_type_name; case_type_generic_parameter; case_type_as; case_type_bounds; case_type_equal; case_type_variants; case_type_semicolon; } -> [ case_type_attribute_spec; case_type_modifiers; case_type_case_keyword; case_type_type_keyword; case_type_name; case_type_generic_parameter; case_type_as; case_type_bounds; case_type_equal; case_type_variants; case_type_semicolon; ] | CaseTypeVariant { case_type_variant_bar; case_type_variant_type } -> [case_type_variant_bar; case_type_variant_type] | PropertyDeclaration { property_attribute_spec; property_modifiers; property_type; property_declarators; property_semicolon; } -> [ property_attribute_spec; property_modifiers; property_type; property_declarators; property_semicolon; ] | PropertyDeclarator { property_name; property_initializer } -> [property_name; property_initializer] | NamespaceDeclaration { namespace_header; namespace_body } -> [namespace_header; namespace_body] | NamespaceDeclarationHeader { namespace_keyword; namespace_name } -> [namespace_keyword; namespace_name] | NamespaceBody { namespace_left_brace; namespace_declarations; namespace_right_brace; } -> [namespace_left_brace; namespace_declarations; namespace_right_brace] | NamespaceEmptyBody { namespace_semicolon } -> [namespace_semicolon] | NamespaceUseDeclaration { namespace_use_keyword; namespace_use_kind; namespace_use_clauses; namespace_use_semicolon; } -> [ namespace_use_keyword; namespace_use_kind; namespace_use_clauses; namespace_use_semicolon; ] | NamespaceGroupUseDeclaration { namespace_group_use_keyword; namespace_group_use_kind; namespace_group_use_prefix; namespace_group_use_left_brace; namespace_group_use_clauses; namespace_group_use_right_brace; namespace_group_use_semicolon; } -> [ namespace_group_use_keyword; namespace_group_use_kind; namespace_group_use_prefix; namespace_group_use_left_brace; namespace_group_use_clauses; namespace_group_use_right_brace; namespace_group_use_semicolon; ] | NamespaceUseClause { namespace_use_clause_kind; namespace_use_name; namespace_use_as; namespace_use_alias; } -> [ namespace_use_clause_kind; namespace_use_name; namespace_use_as; namespace_use_alias; ] | FunctionDeclaration { function_attribute_spec; function_declaration_header; function_body; } -> [function_attribute_spec; function_declaration_header; function_body] | FunctionDeclarationHeader { function_modifiers; function_keyword; function_name; function_type_parameter_list; function_left_paren; function_parameter_list; function_right_paren; function_contexts; function_colon; function_readonly_return; function_type; function_where_clause; } -> [ function_modifiers; function_keyword; function_name; function_type_parameter_list; function_left_paren; function_parameter_list; function_right_paren; function_contexts; function_colon; function_readonly_return; function_type; function_where_clause; ] | Contexts { contexts_left_bracket; contexts_types; contexts_right_bracket } -> [contexts_left_bracket; contexts_types; contexts_right_bracket] | WhereClause { where_clause_keyword; where_clause_constraints } -> [where_clause_keyword; where_clause_constraints] | WhereConstraint { where_constraint_left_type; where_constraint_operator; where_constraint_right_type; } -> [ where_constraint_left_type; where_constraint_operator; where_constraint_right_type; ] | MethodishDeclaration { methodish_attribute; methodish_function_decl_header; methodish_function_body; methodish_semicolon; } -> [ methodish_attribute; methodish_function_decl_header; methodish_function_body; methodish_semicolon; ] | MethodishTraitResolution { methodish_trait_attribute; methodish_trait_function_decl_header; methodish_trait_equal; methodish_trait_name; methodish_trait_semicolon; } -> [ methodish_trait_attribute; methodish_trait_function_decl_header; methodish_trait_equal; methodish_trait_name; methodish_trait_semicolon; ] | ClassishDeclaration { classish_attribute; classish_modifiers; classish_xhp; classish_keyword; classish_name; classish_type_parameters; classish_extends_keyword; classish_extends_list; classish_implements_keyword; classish_implements_list; classish_where_clause; classish_body; } -> [ classish_attribute; classish_modifiers; classish_xhp; classish_keyword; classish_name; classish_type_parameters; classish_extends_keyword; classish_extends_list; classish_implements_keyword; classish_implements_list; classish_where_clause; classish_body; ] | ClassishBody { classish_body_left_brace; classish_body_elements; classish_body_right_brace; } -> [ classish_body_left_brace; classish_body_elements; classish_body_right_brace; ] | TraitUse { trait_use_keyword; trait_use_names; trait_use_semicolon } -> [trait_use_keyword; trait_use_names; trait_use_semicolon] | RequireClause { require_keyword; require_kind; require_name; require_semicolon } -> [require_keyword; require_kind; require_name; require_semicolon] | ConstDeclaration { const_attribute_spec; const_modifiers; const_keyword; const_type_specifier; const_declarators; const_semicolon; } -> [ const_attribute_spec; const_modifiers; const_keyword; const_type_specifier; const_declarators; const_semicolon; ] | ConstantDeclarator { constant_declarator_name; constant_declarator_initializer } -> [constant_declarator_name; constant_declarator_initializer] | TypeConstDeclaration { type_const_attribute_spec; type_const_modifiers; type_const_keyword; type_const_type_keyword; type_const_name; type_const_type_parameters; type_const_type_constraints; type_const_equal; type_const_type_specifier; type_const_semicolon; } -> [ type_const_attribute_spec; type_const_modifiers; type_const_keyword; type_const_type_keyword; type_const_name; type_const_type_parameters; type_const_type_constraints; type_const_equal; type_const_type_specifier; type_const_semicolon; ] | ContextConstDeclaration { context_const_modifiers; context_const_const_keyword; context_const_ctx_keyword; context_const_name; context_const_type_parameters; context_const_constraint; context_const_equal; context_const_ctx_list; context_const_semicolon; } -> [ context_const_modifiers; context_const_const_keyword; context_const_ctx_keyword; context_const_name; context_const_type_parameters; context_const_constraint; context_const_equal; context_const_ctx_list; context_const_semicolon; ] | DecoratedExpression { decorated_expression_decorator; decorated_expression_expression } -> [decorated_expression_decorator; decorated_expression_expression] | ParameterDeclaration { parameter_attribute; parameter_visibility; parameter_call_convention; parameter_readonly; parameter_type; parameter_name; parameter_default_value; } -> [ parameter_attribute; parameter_visibility; parameter_call_convention; parameter_readonly; parameter_type; parameter_name; parameter_default_value; ] | VariadicParameter { variadic_parameter_call_convention; variadic_parameter_type; variadic_parameter_ellipsis; } -> [ variadic_parameter_call_convention; variadic_parameter_type; variadic_parameter_ellipsis; ] | OldAttributeSpecification { old_attribute_specification_left_double_angle; old_attribute_specification_attributes; old_attribute_specification_right_double_angle; } -> [ old_attribute_specification_left_double_angle; old_attribute_specification_attributes; old_attribute_specification_right_double_angle; ] | AttributeSpecification { attribute_specification_attributes } -> [attribute_specification_attributes] | Attribute { attribute_at; attribute_attribute_name } -> [attribute_at; attribute_attribute_name] | InclusionExpression { inclusion_require; inclusion_filename } -> [inclusion_require; inclusion_filename] | InclusionDirective { inclusion_expression; inclusion_semicolon } -> [inclusion_expression; inclusion_semicolon] | CompoundStatement { compound_left_brace; compound_statements; compound_right_brace } -> [compound_left_brace; compound_statements; compound_right_brace] | ExpressionStatement { expression_statement_expression; expression_statement_semicolon } -> [expression_statement_expression; expression_statement_semicolon] | MarkupSection { markup_hashbang; markup_suffix } -> [markup_hashbang; markup_suffix] | MarkupSuffix { markup_suffix_less_than_question; markup_suffix_name } -> [markup_suffix_less_than_question; markup_suffix_name] | UnsetStatement { unset_keyword; unset_left_paren; unset_variables; unset_right_paren; unset_semicolon; } -> [ unset_keyword; unset_left_paren; unset_variables; unset_right_paren; unset_semicolon; ] | DeclareLocalStatement { declare_local_keyword; declare_local_variable; declare_local_colon; declare_local_type; declare_local_initializer; declare_local_semicolon; } -> [ declare_local_keyword; declare_local_variable; declare_local_colon; declare_local_type; declare_local_initializer; declare_local_semicolon; ] | UsingStatementBlockScoped { using_block_await_keyword; using_block_using_keyword; using_block_left_paren; using_block_expressions; using_block_right_paren; using_block_body; } -> [ using_block_await_keyword; using_block_using_keyword; using_block_left_paren; using_block_expressions; using_block_right_paren; using_block_body; ] | UsingStatementFunctionScoped { using_function_await_keyword; using_function_using_keyword; using_function_expression; using_function_semicolon; } -> [ using_function_await_keyword; using_function_using_keyword; using_function_expression; using_function_semicolon; ] | WhileStatement { while_keyword; while_left_paren; while_condition; while_right_paren; while_body; } -> [ while_keyword; while_left_paren; while_condition; while_right_paren; while_body; ] | IfStatement { if_keyword; if_left_paren; if_condition; if_right_paren; if_statement; if_else_clause; } -> [ if_keyword; if_left_paren; if_condition; if_right_paren; if_statement; if_else_clause; ] | ElseClause { else_keyword; else_statement } -> [else_keyword; else_statement] | TryStatement { try_keyword; try_compound_statement; try_catch_clauses; try_finally_clause; } -> [ try_keyword; try_compound_statement; try_catch_clauses; try_finally_clause; ] | CatchClause { catch_keyword; catch_left_paren; catch_type; catch_variable; catch_right_paren; catch_body; } -> [ catch_keyword; catch_left_paren; catch_type; catch_variable; catch_right_paren; catch_body; ] | FinallyClause { finally_keyword; finally_body } -> [finally_keyword; finally_body] | DoStatement { do_keyword; do_body; do_while_keyword; do_left_paren; do_condition; do_right_paren; do_semicolon; } -> [ do_keyword; do_body; do_while_keyword; do_left_paren; do_condition; do_right_paren; do_semicolon; ] | ForStatement { for_keyword; for_left_paren; for_initializer; for_first_semicolon; for_control; for_second_semicolon; for_end_of_loop; for_right_paren; for_body; } -> [ for_keyword; for_left_paren; for_initializer; for_first_semicolon; for_control; for_second_semicolon; for_end_of_loop; for_right_paren; for_body; ] | ForeachStatement { foreach_keyword; foreach_left_paren; foreach_collection; foreach_await_keyword; foreach_as; foreach_key; foreach_arrow; foreach_value; foreach_right_paren; foreach_body; } -> [ foreach_keyword; foreach_left_paren; foreach_collection; foreach_await_keyword; foreach_as; foreach_key; foreach_arrow; foreach_value; foreach_right_paren; foreach_body; ] | SwitchStatement { switch_keyword; switch_left_paren; switch_expression; switch_right_paren; switch_left_brace; switch_sections; switch_right_brace; } -> [ switch_keyword; switch_left_paren; switch_expression; switch_right_paren; switch_left_brace; switch_sections; switch_right_brace; ] | SwitchSection { switch_section_labels; switch_section_statements; switch_section_fallthrough; } -> [ switch_section_labels; switch_section_statements; switch_section_fallthrough; ] | SwitchFallthrough { fallthrough_keyword; fallthrough_semicolon } -> [fallthrough_keyword; fallthrough_semicolon] | CaseLabel { case_keyword; case_expression; case_colon } -> [case_keyword; case_expression; case_colon] | DefaultLabel { default_keyword; default_colon } -> [default_keyword; default_colon] | MatchStatement { match_statement_keyword; match_statement_left_paren; match_statement_expression; match_statement_right_paren; match_statement_left_brace; match_statement_arms; match_statement_right_brace; } -> [ match_statement_keyword; match_statement_left_paren; match_statement_expression; match_statement_right_paren; match_statement_left_brace; match_statement_arms; match_statement_right_brace; ] | MatchStatementArm { match_statement_arm_pattern; match_statement_arm_arrow; match_statement_arm_body; } -> [ match_statement_arm_pattern; match_statement_arm_arrow; match_statement_arm_body; ] | ReturnStatement { return_keyword; return_expression; return_semicolon } -> [return_keyword; return_expression; return_semicolon] | YieldBreakStatement { yield_break_keyword; yield_break_break; yield_break_semicolon } -> [yield_break_keyword; yield_break_break; yield_break_semicolon] | ThrowStatement { throw_keyword; throw_expression; throw_semicolon } -> [throw_keyword; throw_expression; throw_semicolon] | BreakStatement { break_keyword; break_semicolon } -> [break_keyword; break_semicolon] | ContinueStatement { continue_keyword; continue_semicolon } -> [continue_keyword; continue_semicolon] | EchoStatement { echo_keyword; echo_expressions; echo_semicolon } -> [echo_keyword; echo_expressions; echo_semicolon] | ConcurrentStatement { concurrent_keyword; concurrent_statement } -> [concurrent_keyword; concurrent_statement] | SimpleInitializer { simple_initializer_equal; simple_initializer_value } -> [simple_initializer_equal; simple_initializer_value] | AnonymousClass { anonymous_class_class_keyword; anonymous_class_left_paren; anonymous_class_argument_list; anonymous_class_right_paren; anonymous_class_extends_keyword; anonymous_class_extends_list; anonymous_class_implements_keyword; anonymous_class_implements_list; anonymous_class_body; } -> [ anonymous_class_class_keyword; anonymous_class_left_paren; anonymous_class_argument_list; anonymous_class_right_paren; anonymous_class_extends_keyword; anonymous_class_extends_list; anonymous_class_implements_keyword; anonymous_class_implements_list; anonymous_class_body; ] | AnonymousFunction { anonymous_attribute_spec; anonymous_async_keyword; anonymous_function_keyword; anonymous_left_paren; anonymous_parameters; anonymous_right_paren; anonymous_ctx_list; anonymous_colon; anonymous_readonly_return; anonymous_type; anonymous_use; anonymous_body; } -> [ anonymous_attribute_spec; anonymous_async_keyword; anonymous_function_keyword; anonymous_left_paren; anonymous_parameters; anonymous_right_paren; anonymous_ctx_list; anonymous_colon; anonymous_readonly_return; anonymous_type; anonymous_use; anonymous_body; ] | AnonymousFunctionUseClause { anonymous_use_keyword; anonymous_use_left_paren; anonymous_use_variables; anonymous_use_right_paren; } -> [ anonymous_use_keyword; anonymous_use_left_paren; anonymous_use_variables; anonymous_use_right_paren; ] | VariablePattern { variable_pattern_variable } -> [variable_pattern_variable] | ConstructorPattern { constructor_pattern_constructor; constructor_pattern_left_paren; constructor_pattern_members; constructor_pattern_right_paren; } -> [ constructor_pattern_constructor; constructor_pattern_left_paren; constructor_pattern_members; constructor_pattern_right_paren; ] | RefinementPattern { refinement_pattern_variable; refinement_pattern_colon; refinement_pattern_specifier; } -> [ refinement_pattern_variable; refinement_pattern_colon; refinement_pattern_specifier; ] | LambdaExpression { lambda_attribute_spec; lambda_async; lambda_signature; lambda_arrow; lambda_body; } -> [ lambda_attribute_spec; lambda_async; lambda_signature; lambda_arrow; lambda_body; ] | LambdaSignature { lambda_left_paren; lambda_parameters; lambda_right_paren; lambda_contexts; lambda_colon; lambda_readonly_return; lambda_type; } -> [ lambda_left_paren; lambda_parameters; lambda_right_paren; lambda_contexts; lambda_colon; lambda_readonly_return; lambda_type; ] | CastExpression { cast_left_paren; cast_type; cast_right_paren; cast_operand } -> [cast_left_paren; cast_type; cast_right_paren; cast_operand] | ScopeResolutionExpression { scope_resolution_qualifier; scope_resolution_operator; scope_resolution_name; } -> [ scope_resolution_qualifier; scope_resolution_operator; scope_resolution_name; ] | MemberSelectionExpression { member_object; member_operator; member_name } -> [member_object; member_operator; member_name] | SafeMemberSelectionExpression { safe_member_object; safe_member_operator; safe_member_name } -> [safe_member_object; safe_member_operator; safe_member_name] | EmbeddedMemberSelectionExpression { embedded_member_object; embedded_member_operator; embedded_member_name; } -> [embedded_member_object; embedded_member_operator; embedded_member_name] | YieldExpression { yield_keyword; yield_operand } -> [yield_keyword; yield_operand] | PrefixUnaryExpression { prefix_unary_operator; prefix_unary_operand } -> [prefix_unary_operator; prefix_unary_operand] | PostfixUnaryExpression { postfix_unary_operand; postfix_unary_operator } -> [postfix_unary_operand; postfix_unary_operator] | BinaryExpression { binary_left_operand; binary_operator; binary_right_operand } -> [binary_left_operand; binary_operator; binary_right_operand] | IsExpression { is_left_operand; is_operator; is_right_operand } -> [is_left_operand; is_operator; is_right_operand] | AsExpression { as_left_operand; as_operator; as_right_operand } -> [as_left_operand; as_operator; as_right_operand] | NullableAsExpression { nullable_as_left_operand; nullable_as_operator; nullable_as_right_operand; } -> [ nullable_as_left_operand; nullable_as_operator; nullable_as_right_operand; ] | UpcastExpression { upcast_left_operand; upcast_operator; upcast_right_operand } -> [upcast_left_operand; upcast_operator; upcast_right_operand] | ConditionalExpression { conditional_test; conditional_question; conditional_consequence; conditional_colon; conditional_alternative; } -> [ conditional_test; conditional_question; conditional_consequence; conditional_colon; conditional_alternative; ] | EvalExpression { eval_keyword; eval_left_paren; eval_argument; eval_right_paren } -> [eval_keyword; eval_left_paren; eval_argument; eval_right_paren] | IssetExpression { isset_keyword; isset_left_paren; isset_argument_list; isset_right_paren; } -> [ isset_keyword; isset_left_paren; isset_argument_list; isset_right_paren; ] | FunctionCallExpression { function_call_receiver; function_call_type_args; function_call_left_paren; function_call_argument_list; function_call_right_paren; } -> [ function_call_receiver; function_call_type_args; function_call_left_paren; function_call_argument_list; function_call_right_paren; ] | FunctionPointerExpression { function_pointer_receiver; function_pointer_type_args } -> [function_pointer_receiver; function_pointer_type_args] | ParenthesizedExpression { parenthesized_expression_left_paren; parenthesized_expression_expression; parenthesized_expression_right_paren; } -> [ parenthesized_expression_left_paren; parenthesized_expression_expression; parenthesized_expression_right_paren; ] | BracedExpression { braced_expression_left_brace; braced_expression_expression; braced_expression_right_brace; } -> [ braced_expression_left_brace; braced_expression_expression; braced_expression_right_brace; ] | ETSpliceExpression { et_splice_expression_dollar; et_splice_expression_left_brace; et_splice_expression_expression; et_splice_expression_right_brace; } -> [ et_splice_expression_dollar; et_splice_expression_left_brace; et_splice_expression_expression; et_splice_expression_right_brace; ] | EmbeddedBracedExpression { embedded_braced_expression_left_brace; embedded_braced_expression_expression; embedded_braced_expression_right_brace; } -> [ embedded_braced_expression_left_brace; embedded_braced_expression_expression; embedded_braced_expression_right_brace; ] | ListExpression { list_keyword; list_left_paren; list_members; list_right_paren } -> [list_keyword; list_left_paren; list_members; list_right_paren] | CollectionLiteralExpression { collection_literal_name; collection_literal_left_brace; collection_literal_initializers; collection_literal_right_brace; } -> [ collection_literal_name; collection_literal_left_brace; collection_literal_initializers; collection_literal_right_brace; ] | ObjectCreationExpression { object_creation_new_keyword; object_creation_object } -> [object_creation_new_keyword; object_creation_object] | ConstructorCall { constructor_call_type; constructor_call_left_paren; constructor_call_argument_list; constructor_call_right_paren; } -> [ constructor_call_type; constructor_call_left_paren; constructor_call_argument_list; constructor_call_right_paren; ] | DarrayIntrinsicExpression { darray_intrinsic_keyword; darray_intrinsic_explicit_type; darray_intrinsic_left_bracket; darray_intrinsic_members; darray_intrinsic_right_bracket; } -> [ darray_intrinsic_keyword; darray_intrinsic_explicit_type; darray_intrinsic_left_bracket; darray_intrinsic_members; darray_intrinsic_right_bracket; ] | DictionaryIntrinsicExpression { dictionary_intrinsic_keyword; dictionary_intrinsic_explicit_type; dictionary_intrinsic_left_bracket; dictionary_intrinsic_members; dictionary_intrinsic_right_bracket; } -> [ dictionary_intrinsic_keyword; dictionary_intrinsic_explicit_type; dictionary_intrinsic_left_bracket; dictionary_intrinsic_members; dictionary_intrinsic_right_bracket; ] | KeysetIntrinsicExpression { keyset_intrinsic_keyword; keyset_intrinsic_explicit_type; keyset_intrinsic_left_bracket; keyset_intrinsic_members; keyset_intrinsic_right_bracket; } -> [ keyset_intrinsic_keyword; keyset_intrinsic_explicit_type; keyset_intrinsic_left_bracket; keyset_intrinsic_members; keyset_intrinsic_right_bracket; ] | VarrayIntrinsicExpression { varray_intrinsic_keyword; varray_intrinsic_explicit_type; varray_intrinsic_left_bracket; varray_intrinsic_members; varray_intrinsic_right_bracket; } -> [ varray_intrinsic_keyword; varray_intrinsic_explicit_type; varray_intrinsic_left_bracket; varray_intrinsic_members; varray_intrinsic_right_bracket; ] | VectorIntrinsicExpression { vector_intrinsic_keyword; vector_intrinsic_explicit_type; vector_intrinsic_left_bracket; vector_intrinsic_members; vector_intrinsic_right_bracket; } -> [ vector_intrinsic_keyword; vector_intrinsic_explicit_type; vector_intrinsic_left_bracket; vector_intrinsic_members; vector_intrinsic_right_bracket; ] | ElementInitializer { element_key; element_arrow; element_value } -> [element_key; element_arrow; element_value] | SubscriptExpression { subscript_receiver; subscript_left_bracket; subscript_index; subscript_right_bracket; } -> [ subscript_receiver; subscript_left_bracket; subscript_index; subscript_right_bracket; ] | EmbeddedSubscriptExpression { embedded_subscript_receiver; embedded_subscript_left_bracket; embedded_subscript_index; embedded_subscript_right_bracket; } -> [ embedded_subscript_receiver; embedded_subscript_left_bracket; embedded_subscript_index; embedded_subscript_right_bracket; ] | AwaitableCreationExpression { awaitable_attribute_spec; awaitable_async; awaitable_compound_statement; } -> [ awaitable_attribute_spec; awaitable_async; awaitable_compound_statement; ] | XHPChildrenDeclaration { xhp_children_keyword; xhp_children_expression; xhp_children_semicolon; } -> [xhp_children_keyword; xhp_children_expression; xhp_children_semicolon] | XHPChildrenParenthesizedList { xhp_children_list_left_paren; xhp_children_list_xhp_children; xhp_children_list_right_paren; } -> [ xhp_children_list_left_paren; xhp_children_list_xhp_children; xhp_children_list_right_paren; ] | XHPCategoryDeclaration { xhp_category_keyword; xhp_category_categories; xhp_category_semicolon; } -> [xhp_category_keyword; xhp_category_categories; xhp_category_semicolon] | XHPEnumType { xhp_enum_like; xhp_enum_keyword; xhp_enum_left_brace; xhp_enum_values; xhp_enum_right_brace; } -> [ xhp_enum_like; xhp_enum_keyword; xhp_enum_left_brace; xhp_enum_values; xhp_enum_right_brace; ] | XHPLateinit { xhp_lateinit_at; xhp_lateinit_keyword } -> [xhp_lateinit_at; xhp_lateinit_keyword] | XHPRequired { xhp_required_at; xhp_required_keyword } -> [xhp_required_at; xhp_required_keyword] | XHPClassAttributeDeclaration { xhp_attribute_keyword; xhp_attribute_attributes; xhp_attribute_semicolon; } -> [ xhp_attribute_keyword; xhp_attribute_attributes; xhp_attribute_semicolon; ] | XHPClassAttribute { xhp_attribute_decl_type; xhp_attribute_decl_name; xhp_attribute_decl_initializer; xhp_attribute_decl_required; } -> [ xhp_attribute_decl_type; xhp_attribute_decl_name; xhp_attribute_decl_initializer; xhp_attribute_decl_required; ] | XHPSimpleClassAttribute { xhp_simple_class_attribute_type } -> [xhp_simple_class_attribute_type] | XHPSimpleAttribute { xhp_simple_attribute_name; xhp_simple_attribute_equal; xhp_simple_attribute_expression; } -> [ xhp_simple_attribute_name; xhp_simple_attribute_equal; xhp_simple_attribute_expression; ] | XHPSpreadAttribute { xhp_spread_attribute_left_brace; xhp_spread_attribute_spread_operator; xhp_spread_attribute_expression; xhp_spread_attribute_right_brace; } -> [ xhp_spread_attribute_left_brace; xhp_spread_attribute_spread_operator; xhp_spread_attribute_expression; xhp_spread_attribute_right_brace; ] | XHPOpen { xhp_open_left_angle; xhp_open_name; xhp_open_attributes; xhp_open_right_angle; } -> [ xhp_open_left_angle; xhp_open_name; xhp_open_attributes; xhp_open_right_angle; ] | XHPExpression { xhp_open; xhp_body; xhp_close } -> [xhp_open; xhp_body; xhp_close] | XHPClose { xhp_close_left_angle; xhp_close_name; xhp_close_right_angle } -> [xhp_close_left_angle; xhp_close_name; xhp_close_right_angle] | TypeConstant { type_constant_left_type; type_constant_separator; type_constant_right_type; } -> [ type_constant_left_type; type_constant_separator; type_constant_right_type; ] | VectorTypeSpecifier { vector_type_keyword; vector_type_left_angle; vector_type_type; vector_type_trailing_comma; vector_type_right_angle; } -> [ vector_type_keyword; vector_type_left_angle; vector_type_type; vector_type_trailing_comma; vector_type_right_angle; ] | KeysetTypeSpecifier { keyset_type_keyword; keyset_type_left_angle; keyset_type_type; keyset_type_trailing_comma; keyset_type_right_angle; } -> [ keyset_type_keyword; keyset_type_left_angle; keyset_type_type; keyset_type_trailing_comma; keyset_type_right_angle; ] | TupleTypeExplicitSpecifier { tuple_type_keyword; tuple_type_left_angle; tuple_type_types; tuple_type_right_angle; } -> [ tuple_type_keyword; tuple_type_left_angle; tuple_type_types; tuple_type_right_angle; ] | VarrayTypeSpecifier { varray_keyword; varray_left_angle; varray_type; varray_trailing_comma; varray_right_angle; } -> [ varray_keyword; varray_left_angle; varray_type; varray_trailing_comma; varray_right_angle; ] | FunctionCtxTypeSpecifier { function_ctx_type_keyword; function_ctx_type_variable } -> [function_ctx_type_keyword; function_ctx_type_variable] | TypeParameter { type_attribute_spec; type_reified; type_variance; type_name; type_param_params; type_constraints; } -> [ type_attribute_spec; type_reified; type_variance; type_name; type_param_params; type_constraints; ] | TypeConstraint { constraint_keyword; constraint_type } -> [constraint_keyword; constraint_type] | ContextConstraint { ctx_constraint_keyword; ctx_constraint_ctx_list } -> [ctx_constraint_keyword; ctx_constraint_ctx_list] | DarrayTypeSpecifier { darray_keyword; darray_left_angle; darray_key; darray_comma; darray_value; darray_trailing_comma; darray_right_angle; } -> [ darray_keyword; darray_left_angle; darray_key; darray_comma; darray_value; darray_trailing_comma; darray_right_angle; ] | DictionaryTypeSpecifier { dictionary_type_keyword; dictionary_type_left_angle; dictionary_type_members; dictionary_type_right_angle; } -> [ dictionary_type_keyword; dictionary_type_left_angle; dictionary_type_members; dictionary_type_right_angle; ] | ClosureTypeSpecifier { closure_outer_left_paren; closure_readonly_keyword; closure_function_keyword; closure_inner_left_paren; closure_parameter_list; closure_inner_right_paren; closure_contexts; closure_colon; closure_readonly_return; closure_return_type; closure_outer_right_paren; } -> [ closure_outer_left_paren; closure_readonly_keyword; closure_function_keyword; closure_inner_left_paren; closure_parameter_list; closure_inner_right_paren; closure_contexts; closure_colon; closure_readonly_return; closure_return_type; closure_outer_right_paren; ] | ClosureParameterTypeSpecifier { closure_parameter_call_convention; closure_parameter_readonly; closure_parameter_type; } -> [ closure_parameter_call_convention; closure_parameter_readonly; closure_parameter_type; ] | TypeRefinement { type_refinement_type; type_refinement_keyword; type_refinement_left_brace; type_refinement_members; type_refinement_right_brace; } -> [ type_refinement_type; type_refinement_keyword; type_refinement_left_brace; type_refinement_members; type_refinement_right_brace; ] | TypeInRefinement { type_in_refinement_keyword; type_in_refinement_name; type_in_refinement_type_parameters; type_in_refinement_constraints; type_in_refinement_equal; type_in_refinement_type; } -> [ type_in_refinement_keyword; type_in_refinement_name; type_in_refinement_type_parameters; type_in_refinement_constraints; type_in_refinement_equal; type_in_refinement_type; ] | CtxInRefinement { ctx_in_refinement_keyword; ctx_in_refinement_name; ctx_in_refinement_type_parameters; ctx_in_refinement_constraints; ctx_in_refinement_equal; ctx_in_refinement_ctx_list; } -> [ ctx_in_refinement_keyword; ctx_in_refinement_name; ctx_in_refinement_type_parameters; ctx_in_refinement_constraints; ctx_in_refinement_equal; ctx_in_refinement_ctx_list; ] | ClassnameTypeSpecifier { classname_keyword; classname_left_angle; classname_type; classname_trailing_comma; classname_right_angle; } -> [ classname_keyword; classname_left_angle; classname_type; classname_trailing_comma; classname_right_angle; ] | FieldSpecifier { field_question; field_name; field_arrow; field_type } -> [field_question; field_name; field_arrow; field_type] | FieldInitializer { field_initializer_name; field_initializer_arrow; field_initializer_value; } -> [ field_initializer_name; field_initializer_arrow; field_initializer_value; ] | ShapeTypeSpecifier { shape_type_keyword; shape_type_left_paren; shape_type_fields; shape_type_ellipsis; shape_type_right_paren; } -> [ shape_type_keyword; shape_type_left_paren; shape_type_fields; shape_type_ellipsis; shape_type_right_paren; ] | ShapeExpression { shape_expression_keyword; shape_expression_left_paren; shape_expression_fields; shape_expression_right_paren; } -> [ shape_expression_keyword; shape_expression_left_paren; shape_expression_fields; shape_expression_right_paren; ] | TupleExpression { tuple_expression_keyword; tuple_expression_left_paren; tuple_expression_items; tuple_expression_right_paren; } -> [ tuple_expression_keyword; tuple_expression_left_paren; tuple_expression_items; tuple_expression_right_paren; ] | GenericTypeSpecifier { generic_class_type; generic_argument_list } -> [generic_class_type; generic_argument_list] | NullableTypeSpecifier { nullable_question; nullable_type } -> [nullable_question; nullable_type] | LikeTypeSpecifier { like_tilde; like_type } -> [like_tilde; like_type] | SoftTypeSpecifier { soft_at; soft_type } -> [soft_at; soft_type] | AttributizedSpecifier { attributized_specifier_attribute_spec; attributized_specifier_type } -> [attributized_specifier_attribute_spec; attributized_specifier_type] | ReifiedTypeArgument { reified_type_argument_reified; reified_type_argument_type } -> [reified_type_argument_reified; reified_type_argument_type] | TypeArguments { type_arguments_left_angle; type_arguments_types; type_arguments_right_angle; } -> [ type_arguments_left_angle; type_arguments_types; type_arguments_right_angle; ] | TypeParameters { type_parameters_left_angle; type_parameters_parameters; type_parameters_right_angle; } -> [ type_parameters_left_angle; type_parameters_parameters; type_parameters_right_angle; ] | TupleTypeSpecifier { tuple_left_paren; tuple_types; tuple_right_paren } -> [tuple_left_paren; tuple_types; tuple_right_paren] | UnionTypeSpecifier { union_left_paren; union_types; union_right_paren } -> [union_left_paren; union_types; union_right_paren] | IntersectionTypeSpecifier { intersection_left_paren; intersection_types; intersection_right_paren; } -> [intersection_left_paren; intersection_types; intersection_right_paren] | ErrorSyntax { error_error } -> [error_error] | ListItem { list_item; list_separator } -> [list_item; list_separator] | EnumClassLabelExpression { enum_class_label_qualifier; enum_class_label_hash; enum_class_label_expression; } -> [ enum_class_label_qualifier; enum_class_label_hash; enum_class_label_expression; ] | ModuleDeclaration { module_declaration_attribute_spec; module_declaration_new_keyword; module_declaration_module_keyword; module_declaration_name; module_declaration_left_brace; module_declaration_exports; module_declaration_imports; module_declaration_right_brace; } -> [ module_declaration_attribute_spec; module_declaration_new_keyword; module_declaration_module_keyword; module_declaration_name; module_declaration_left_brace; module_declaration_exports; module_declaration_imports; module_declaration_right_brace; ] | ModuleExports { module_exports_exports_keyword; module_exports_left_brace; module_exports_exports; module_exports_right_brace; } -> [ module_exports_exports_keyword; module_exports_left_brace; module_exports_exports; module_exports_right_brace; ] | ModuleImports { module_imports_imports_keyword; module_imports_left_brace; module_imports_imports; module_imports_right_brace; } -> [ module_imports_imports_keyword; module_imports_left_brace; module_imports_imports; module_imports_right_brace; ] | ModuleMembershipDeclaration { module_membership_declaration_module_keyword; module_membership_declaration_name; module_membership_declaration_semicolon; } -> [ module_membership_declaration_module_keyword; module_membership_declaration_name; module_membership_declaration_semicolon; ] | PackageExpression { package_expression_keyword; package_expression_name } -> [package_expression_keyword; package_expression_name] let children node = children_from_syntax node.syntax let children_names node = match node.syntax with | Missing -> [] | Token _ -> [] | SyntaxList _ -> [] | EndOfFile { end_of_file_token } -> ["end_of_file_token"] | Script { script_declarations } -> ["script_declarations"] | QualifiedName { qualified_name_parts } -> ["qualified_name_parts"] | ModuleName { module_name_parts } -> ["module_name_parts"] | SimpleTypeSpecifier { simple_type_specifier } -> ["simple_type_specifier"] | LiteralExpression { literal_expression } -> ["literal_expression"] | PrefixedStringExpression { prefixed_string_name; prefixed_string_str } -> ["prefixed_string_name"; "prefixed_string_str"] | PrefixedCodeExpression { prefixed_code_prefix; prefixed_code_left_backtick; prefixed_code_body; prefixed_code_right_backtick; } -> [ "prefixed_code_prefix"; "prefixed_code_left_backtick"; "prefixed_code_body"; "prefixed_code_right_backtick"; ] | VariableExpression { variable_expression } -> ["variable_expression"] | PipeVariableExpression { pipe_variable_expression } -> ["pipe_variable_expression"] | FileAttributeSpecification { file_attribute_specification_left_double_angle; file_attribute_specification_keyword; file_attribute_specification_colon; file_attribute_specification_attributes; file_attribute_specification_right_double_angle; } -> [ "file_attribute_specification_left_double_angle"; "file_attribute_specification_keyword"; "file_attribute_specification_colon"; "file_attribute_specification_attributes"; "file_attribute_specification_right_double_angle"; ] | EnumDeclaration { enum_attribute_spec; enum_modifiers; enum_keyword; enum_name; enum_colon; enum_base; enum_type; enum_left_brace; enum_use_clauses; enum_enumerators; enum_right_brace; } -> [ "enum_attribute_spec"; "enum_modifiers"; "enum_keyword"; "enum_name"; "enum_colon"; "enum_base"; "enum_type"; "enum_left_brace"; "enum_use_clauses"; "enum_enumerators"; "enum_right_brace"; ] | EnumUse { enum_use_keyword; enum_use_names; enum_use_semicolon } -> ["enum_use_keyword"; "enum_use_names"; "enum_use_semicolon"] | Enumerator { enumerator_name; enumerator_equal; enumerator_value; enumerator_semicolon; } -> [ "enumerator_name"; "enumerator_equal"; "enumerator_value"; "enumerator_semicolon"; ] | EnumClassDeclaration { enum_class_attribute_spec; enum_class_modifiers; enum_class_enum_keyword; enum_class_class_keyword; enum_class_name; enum_class_colon; enum_class_base; enum_class_extends; enum_class_extends_list; enum_class_left_brace; enum_class_elements; enum_class_right_brace; } -> [ "enum_class_attribute_spec"; "enum_class_modifiers"; "enum_class_enum_keyword"; "enum_class_class_keyword"; "enum_class_name"; "enum_class_colon"; "enum_class_base"; "enum_class_extends"; "enum_class_extends_list"; "enum_class_left_brace"; "enum_class_elements"; "enum_class_right_brace"; ] | EnumClassEnumerator { enum_class_enumerator_modifiers; enum_class_enumerator_type; enum_class_enumerator_name; enum_class_enumerator_initializer; enum_class_enumerator_semicolon; } -> [ "enum_class_enumerator_modifiers"; "enum_class_enumerator_type"; "enum_class_enumerator_name"; "enum_class_enumerator_initializer"; "enum_class_enumerator_semicolon"; ] | AliasDeclaration { alias_attribute_spec; alias_modifiers; alias_module_kw_opt; alias_keyword; alias_name; alias_generic_parameter; alias_constraint; alias_equal; alias_type; alias_semicolon; } -> [ "alias_attribute_spec"; "alias_modifiers"; "alias_module_kw_opt"; "alias_keyword"; "alias_name"; "alias_generic_parameter"; "alias_constraint"; "alias_equal"; "alias_type"; "alias_semicolon"; ] | ContextAliasDeclaration { ctx_alias_attribute_spec; ctx_alias_keyword; ctx_alias_name; ctx_alias_generic_parameter; ctx_alias_as_constraint; ctx_alias_equal; ctx_alias_context; ctx_alias_semicolon; } -> [ "ctx_alias_attribute_spec"; "ctx_alias_keyword"; "ctx_alias_name"; "ctx_alias_generic_parameter"; "ctx_alias_as_constraint"; "ctx_alias_equal"; "ctx_alias_context"; "ctx_alias_semicolon"; ] | CaseTypeDeclaration { case_type_attribute_spec; case_type_modifiers; case_type_case_keyword; case_type_type_keyword; case_type_name; case_type_generic_parameter; case_type_as; case_type_bounds; case_type_equal; case_type_variants; case_type_semicolon; } -> [ "case_type_attribute_spec"; "case_type_modifiers"; "case_type_case_keyword"; "case_type_type_keyword"; "case_type_name"; "case_type_generic_parameter"; "case_type_as"; "case_type_bounds"; "case_type_equal"; "case_type_variants"; "case_type_semicolon"; ] | CaseTypeVariant { case_type_variant_bar; case_type_variant_type } -> ["case_type_variant_bar"; "case_type_variant_type"] | PropertyDeclaration { property_attribute_spec; property_modifiers; property_type; property_declarators; property_semicolon; } -> [ "property_attribute_spec"; "property_modifiers"; "property_type"; "property_declarators"; "property_semicolon"; ] | PropertyDeclarator { property_name; property_initializer } -> ["property_name"; "property_initializer"] | NamespaceDeclaration { namespace_header; namespace_body } -> ["namespace_header"; "namespace_body"] | NamespaceDeclarationHeader { namespace_keyword; namespace_name } -> ["namespace_keyword"; "namespace_name"] | NamespaceBody { namespace_left_brace; namespace_declarations; namespace_right_brace; } -> [ "namespace_left_brace"; "namespace_declarations"; "namespace_right_brace"; ] | NamespaceEmptyBody { namespace_semicolon } -> ["namespace_semicolon"] | NamespaceUseDeclaration { namespace_use_keyword; namespace_use_kind; namespace_use_clauses; namespace_use_semicolon; } -> [ "namespace_use_keyword"; "namespace_use_kind"; "namespace_use_clauses"; "namespace_use_semicolon"; ] | NamespaceGroupUseDeclaration { namespace_group_use_keyword; namespace_group_use_kind; namespace_group_use_prefix; namespace_group_use_left_brace; namespace_group_use_clauses; namespace_group_use_right_brace; namespace_group_use_semicolon; } -> [ "namespace_group_use_keyword"; "namespace_group_use_kind"; "namespace_group_use_prefix"; "namespace_group_use_left_brace"; "namespace_group_use_clauses"; "namespace_group_use_right_brace"; "namespace_group_use_semicolon"; ] | NamespaceUseClause { namespace_use_clause_kind; namespace_use_name; namespace_use_as; namespace_use_alias; } -> [ "namespace_use_clause_kind"; "namespace_use_name"; "namespace_use_as"; "namespace_use_alias"; ] | FunctionDeclaration { function_attribute_spec; function_declaration_header; function_body; } -> [ "function_attribute_spec"; "function_declaration_header"; "function_body"; ] | FunctionDeclarationHeader { function_modifiers; function_keyword; function_name; function_type_parameter_list; function_left_paren; function_parameter_list; function_right_paren; function_contexts; function_colon; function_readonly_return; function_type; function_where_clause; } -> [ "function_modifiers"; "function_keyword"; "function_name"; "function_type_parameter_list"; "function_left_paren"; "function_parameter_list"; "function_right_paren"; "function_contexts"; "function_colon"; "function_readonly_return"; "function_type"; "function_where_clause"; ] | Contexts { contexts_left_bracket; contexts_types; contexts_right_bracket } -> ["contexts_left_bracket"; "contexts_types"; "contexts_right_bracket"] | WhereClause { where_clause_keyword; where_clause_constraints } -> ["where_clause_keyword"; "where_clause_constraints"] | WhereConstraint { where_constraint_left_type; where_constraint_operator; where_constraint_right_type; } -> [ "where_constraint_left_type"; "where_constraint_operator"; "where_constraint_right_type"; ] | MethodishDeclaration { methodish_attribute; methodish_function_decl_header; methodish_function_body; methodish_semicolon; } -> [ "methodish_attribute"; "methodish_function_decl_header"; "methodish_function_body"; "methodish_semicolon"; ] | MethodishTraitResolution { methodish_trait_attribute; methodish_trait_function_decl_header; methodish_trait_equal; methodish_trait_name; methodish_trait_semicolon; } -> [ "methodish_trait_attribute"; "methodish_trait_function_decl_header"; "methodish_trait_equal"; "methodish_trait_name"; "methodish_trait_semicolon"; ] | ClassishDeclaration { classish_attribute; classish_modifiers; classish_xhp; classish_keyword; classish_name; classish_type_parameters; classish_extends_keyword; classish_extends_list; classish_implements_keyword; classish_implements_list; classish_where_clause; classish_body; } -> [ "classish_attribute"; "classish_modifiers"; "classish_xhp"; "classish_keyword"; "classish_name"; "classish_type_parameters"; "classish_extends_keyword"; "classish_extends_list"; "classish_implements_keyword"; "classish_implements_list"; "classish_where_clause"; "classish_body"; ] | ClassishBody { classish_body_left_brace; classish_body_elements; classish_body_right_brace; } -> [ "classish_body_left_brace"; "classish_body_elements"; "classish_body_right_brace"; ] | TraitUse { trait_use_keyword; trait_use_names; trait_use_semicolon } -> ["trait_use_keyword"; "trait_use_names"; "trait_use_semicolon"] | RequireClause { require_keyword; require_kind; require_name; require_semicolon } -> ["require_keyword"; "require_kind"; "require_name"; "require_semicolon"] | ConstDeclaration { const_attribute_spec; const_modifiers; const_keyword; const_type_specifier; const_declarators; const_semicolon; } -> [ "const_attribute_spec"; "const_modifiers"; "const_keyword"; "const_type_specifier"; "const_declarators"; "const_semicolon"; ] | ConstantDeclarator { constant_declarator_name; constant_declarator_initializer } -> ["constant_declarator_name"; "constant_declarator_initializer"] | TypeConstDeclaration { type_const_attribute_spec; type_const_modifiers; type_const_keyword; type_const_type_keyword; type_const_name; type_const_type_parameters; type_const_type_constraints; type_const_equal; type_const_type_specifier; type_const_semicolon; } -> [ "type_const_attribute_spec"; "type_const_modifiers"; "type_const_keyword"; "type_const_type_keyword"; "type_const_name"; "type_const_type_parameters"; "type_const_type_constraints"; "type_const_equal"; "type_const_type_specifier"; "type_const_semicolon"; ] | ContextConstDeclaration { context_const_modifiers; context_const_const_keyword; context_const_ctx_keyword; context_const_name; context_const_type_parameters; context_const_constraint; context_const_equal; context_const_ctx_list; context_const_semicolon; } -> [ "context_const_modifiers"; "context_const_const_keyword"; "context_const_ctx_keyword"; "context_const_name"; "context_const_type_parameters"; "context_const_constraint"; "context_const_equal"; "context_const_ctx_list"; "context_const_semicolon"; ] | DecoratedExpression { decorated_expression_decorator; decorated_expression_expression } -> ["decorated_expression_decorator"; "decorated_expression_expression"] | ParameterDeclaration { parameter_attribute; parameter_visibility; parameter_call_convention; parameter_readonly; parameter_type; parameter_name; parameter_default_value; } -> [ "parameter_attribute"; "parameter_visibility"; "parameter_call_convention"; "parameter_readonly"; "parameter_type"; "parameter_name"; "parameter_default_value"; ] | VariadicParameter { variadic_parameter_call_convention; variadic_parameter_type; variadic_parameter_ellipsis; } -> [ "variadic_parameter_call_convention"; "variadic_parameter_type"; "variadic_parameter_ellipsis"; ] | OldAttributeSpecification { old_attribute_specification_left_double_angle; old_attribute_specification_attributes; old_attribute_specification_right_double_angle; } -> [ "old_attribute_specification_left_double_angle"; "old_attribute_specification_attributes"; "old_attribute_specification_right_double_angle"; ] | AttributeSpecification { attribute_specification_attributes } -> ["attribute_specification_attributes"] | Attribute { attribute_at; attribute_attribute_name } -> ["attribute_at"; "attribute_attribute_name"] | InclusionExpression { inclusion_require; inclusion_filename } -> ["inclusion_require"; "inclusion_filename"] | InclusionDirective { inclusion_expression; inclusion_semicolon } -> ["inclusion_expression"; "inclusion_semicolon"] | CompoundStatement { compound_left_brace; compound_statements; compound_right_brace } -> ["compound_left_brace"; "compound_statements"; "compound_right_brace"] | ExpressionStatement { expression_statement_expression; expression_statement_semicolon } -> ["expression_statement_expression"; "expression_statement_semicolon"] | MarkupSection { markup_hashbang; markup_suffix } -> ["markup_hashbang"; "markup_suffix"] | MarkupSuffix { markup_suffix_less_than_question; markup_suffix_name } -> ["markup_suffix_less_than_question"; "markup_suffix_name"] | UnsetStatement { unset_keyword; unset_left_paren; unset_variables; unset_right_paren; unset_semicolon; } -> [ "unset_keyword"; "unset_left_paren"; "unset_variables"; "unset_right_paren"; "unset_semicolon"; ] | DeclareLocalStatement { declare_local_keyword; declare_local_variable; declare_local_colon; declare_local_type; declare_local_initializer; declare_local_semicolon; } -> [ "declare_local_keyword"; "declare_local_variable"; "declare_local_colon"; "declare_local_type"; "declare_local_initializer"; "declare_local_semicolon"; ] | UsingStatementBlockScoped { using_block_await_keyword; using_block_using_keyword; using_block_left_paren; using_block_expressions; using_block_right_paren; using_block_body; } -> [ "using_block_await_keyword"; "using_block_using_keyword"; "using_block_left_paren"; "using_block_expressions"; "using_block_right_paren"; "using_block_body"; ] | UsingStatementFunctionScoped { using_function_await_keyword; using_function_using_keyword; using_function_expression; using_function_semicolon; } -> [ "using_function_await_keyword"; "using_function_using_keyword"; "using_function_expression"; "using_function_semicolon"; ] | WhileStatement { while_keyword; while_left_paren; while_condition; while_right_paren; while_body; } -> [ "while_keyword"; "while_left_paren"; "while_condition"; "while_right_paren"; "while_body"; ] | IfStatement { if_keyword; if_left_paren; if_condition; if_right_paren; if_statement; if_else_clause; } -> [ "if_keyword"; "if_left_paren"; "if_condition"; "if_right_paren"; "if_statement"; "if_else_clause"; ] | ElseClause { else_keyword; else_statement } -> ["else_keyword"; "else_statement"] | TryStatement { try_keyword; try_compound_statement; try_catch_clauses; try_finally_clause; } -> [ "try_keyword"; "try_compound_statement"; "try_catch_clauses"; "try_finally_clause"; ] | CatchClause { catch_keyword; catch_left_paren; catch_type; catch_variable; catch_right_paren; catch_body; } -> [ "catch_keyword"; "catch_left_paren"; "catch_type"; "catch_variable"; "catch_right_paren"; "catch_body"; ] | FinallyClause { finally_keyword; finally_body } -> ["finally_keyword"; "finally_body"] | DoStatement { do_keyword; do_body; do_while_keyword; do_left_paren; do_condition; do_right_paren; do_semicolon; } -> [ "do_keyword"; "do_body"; "do_while_keyword"; "do_left_paren"; "do_condition"; "do_right_paren"; "do_semicolon"; ] | ForStatement { for_keyword; for_left_paren; for_initializer; for_first_semicolon; for_control; for_second_semicolon; for_end_of_loop; for_right_paren; for_body; } -> [ "for_keyword"; "for_left_paren"; "for_initializer"; "for_first_semicolon"; "for_control"; "for_second_semicolon"; "for_end_of_loop"; "for_right_paren"; "for_body"; ] | ForeachStatement { foreach_keyword; foreach_left_paren; foreach_collection; foreach_await_keyword; foreach_as; foreach_key; foreach_arrow; foreach_value; foreach_right_paren; foreach_body; } -> [ "foreach_keyword"; "foreach_left_paren"; "foreach_collection"; "foreach_await_keyword"; "foreach_as"; "foreach_key"; "foreach_arrow"; "foreach_value"; "foreach_right_paren"; "foreach_body"; ] | SwitchStatement { switch_keyword; switch_left_paren; switch_expression; switch_right_paren; switch_left_brace; switch_sections; switch_right_brace; } -> [ "switch_keyword"; "switch_left_paren"; "switch_expression"; "switch_right_paren"; "switch_left_brace"; "switch_sections"; "switch_right_brace"; ] | SwitchSection { switch_section_labels; switch_section_statements; switch_section_fallthrough; } -> [ "switch_section_labels"; "switch_section_statements"; "switch_section_fallthrough"; ] | SwitchFallthrough { fallthrough_keyword; fallthrough_semicolon } -> ["fallthrough_keyword"; "fallthrough_semicolon"] | CaseLabel { case_keyword; case_expression; case_colon } -> ["case_keyword"; "case_expression"; "case_colon"] | DefaultLabel { default_keyword; default_colon } -> ["default_keyword"; "default_colon"] | MatchStatement { match_statement_keyword; match_statement_left_paren; match_statement_expression; match_statement_right_paren; match_statement_left_brace; match_statement_arms; match_statement_right_brace; } -> [ "match_statement_keyword"; "match_statement_left_paren"; "match_statement_expression"; "match_statement_right_paren"; "match_statement_left_brace"; "match_statement_arms"; "match_statement_right_brace"; ] | MatchStatementArm { match_statement_arm_pattern; match_statement_arm_arrow; match_statement_arm_body; } -> [ "match_statement_arm_pattern"; "match_statement_arm_arrow"; "match_statement_arm_body"; ] | ReturnStatement { return_keyword; return_expression; return_semicolon } -> ["return_keyword"; "return_expression"; "return_semicolon"] | YieldBreakStatement { yield_break_keyword; yield_break_break; yield_break_semicolon } -> ["yield_break_keyword"; "yield_break_break"; "yield_break_semicolon"] | ThrowStatement { throw_keyword; throw_expression; throw_semicolon } -> ["throw_keyword"; "throw_expression"; "throw_semicolon"] | BreakStatement { break_keyword; break_semicolon } -> ["break_keyword"; "break_semicolon"] | ContinueStatement { continue_keyword; continue_semicolon } -> ["continue_keyword"; "continue_semicolon"] | EchoStatement { echo_keyword; echo_expressions; echo_semicolon } -> ["echo_keyword"; "echo_expressions"; "echo_semicolon"] | ConcurrentStatement { concurrent_keyword; concurrent_statement } -> ["concurrent_keyword"; "concurrent_statement"] | SimpleInitializer { simple_initializer_equal; simple_initializer_value } -> ["simple_initializer_equal"; "simple_initializer_value"] | AnonymousClass { anonymous_class_class_keyword; anonymous_class_left_paren; anonymous_class_argument_list; anonymous_class_right_paren; anonymous_class_extends_keyword; anonymous_class_extends_list; anonymous_class_implements_keyword; anonymous_class_implements_list; anonymous_class_body; } -> [ "anonymous_class_class_keyword"; "anonymous_class_left_paren"; "anonymous_class_argument_list"; "anonymous_class_right_paren"; "anonymous_class_extends_keyword"; "anonymous_class_extends_list"; "anonymous_class_implements_keyword"; "anonymous_class_implements_list"; "anonymous_class_body"; ] | AnonymousFunction { anonymous_attribute_spec; anonymous_async_keyword; anonymous_function_keyword; anonymous_left_paren; anonymous_parameters; anonymous_right_paren; anonymous_ctx_list; anonymous_colon; anonymous_readonly_return; anonymous_type; anonymous_use; anonymous_body; } -> [ "anonymous_attribute_spec"; "anonymous_async_keyword"; "anonymous_function_keyword"; "anonymous_left_paren"; "anonymous_parameters"; "anonymous_right_paren"; "anonymous_ctx_list"; "anonymous_colon"; "anonymous_readonly_return"; "anonymous_type"; "anonymous_use"; "anonymous_body"; ] | AnonymousFunctionUseClause { anonymous_use_keyword; anonymous_use_left_paren; anonymous_use_variables; anonymous_use_right_paren; } -> [ "anonymous_use_keyword"; "anonymous_use_left_paren"; "anonymous_use_variables"; "anonymous_use_right_paren"; ] | VariablePattern { variable_pattern_variable } -> ["variable_pattern_variable"] | ConstructorPattern { constructor_pattern_constructor; constructor_pattern_left_paren; constructor_pattern_members; constructor_pattern_right_paren; } -> [ "constructor_pattern_constructor"; "constructor_pattern_left_paren"; "constructor_pattern_members"; "constructor_pattern_right_paren"; ] | RefinementPattern { refinement_pattern_variable; refinement_pattern_colon; refinement_pattern_specifier; } -> [ "refinement_pattern_variable"; "refinement_pattern_colon"; "refinement_pattern_specifier"; ] | LambdaExpression { lambda_attribute_spec; lambda_async; lambda_signature; lambda_arrow; lambda_body; } -> [ "lambda_attribute_spec"; "lambda_async"; "lambda_signature"; "lambda_arrow"; "lambda_body"; ] | LambdaSignature { lambda_left_paren; lambda_parameters; lambda_right_paren; lambda_contexts; lambda_colon; lambda_readonly_return; lambda_type; } -> [ "lambda_left_paren"; "lambda_parameters"; "lambda_right_paren"; "lambda_contexts"; "lambda_colon"; "lambda_readonly_return"; "lambda_type"; ] | CastExpression { cast_left_paren; cast_type; cast_right_paren; cast_operand } -> ["cast_left_paren"; "cast_type"; "cast_right_paren"; "cast_operand"] | ScopeResolutionExpression { scope_resolution_qualifier; scope_resolution_operator; scope_resolution_name; } -> [ "scope_resolution_qualifier"; "scope_resolution_operator"; "scope_resolution_name"; ] | MemberSelectionExpression { member_object; member_operator; member_name } -> ["member_object"; "member_operator"; "member_name"] | SafeMemberSelectionExpression { safe_member_object; safe_member_operator; safe_member_name } -> ["safe_member_object"; "safe_member_operator"; "safe_member_name"] | EmbeddedMemberSelectionExpression { embedded_member_object; embedded_member_operator; embedded_member_name; } -> [ "embedded_member_object"; "embedded_member_operator"; "embedded_member_name"; ] | YieldExpression { yield_keyword; yield_operand } -> ["yield_keyword"; "yield_operand"] | PrefixUnaryExpression { prefix_unary_operator; prefix_unary_operand } -> ["prefix_unary_operator"; "prefix_unary_operand"] | PostfixUnaryExpression { postfix_unary_operand; postfix_unary_operator } -> ["postfix_unary_operand"; "postfix_unary_operator"] | BinaryExpression { binary_left_operand; binary_operator; binary_right_operand } -> ["binary_left_operand"; "binary_operator"; "binary_right_operand"] | IsExpression { is_left_operand; is_operator; is_right_operand } -> ["is_left_operand"; "is_operator"; "is_right_operand"] | AsExpression { as_left_operand; as_operator; as_right_operand } -> ["as_left_operand"; "as_operator"; "as_right_operand"] | NullableAsExpression { nullable_as_left_operand; nullable_as_operator; nullable_as_right_operand; } -> [ "nullable_as_left_operand"; "nullable_as_operator"; "nullable_as_right_operand"; ] | UpcastExpression { upcast_left_operand; upcast_operator; upcast_right_operand } -> ["upcast_left_operand"; "upcast_operator"; "upcast_right_operand"] | ConditionalExpression { conditional_test; conditional_question; conditional_consequence; conditional_colon; conditional_alternative; } -> [ "conditional_test"; "conditional_question"; "conditional_consequence"; "conditional_colon"; "conditional_alternative"; ] | EvalExpression { eval_keyword; eval_left_paren; eval_argument; eval_right_paren } -> ["eval_keyword"; "eval_left_paren"; "eval_argument"; "eval_right_paren"] | IssetExpression { isset_keyword; isset_left_paren; isset_argument_list; isset_right_paren; } -> [ "isset_keyword"; "isset_left_paren"; "isset_argument_list"; "isset_right_paren"; ] | FunctionCallExpression { function_call_receiver; function_call_type_args; function_call_left_paren; function_call_argument_list; function_call_right_paren; } -> [ "function_call_receiver"; "function_call_type_args"; "function_call_left_paren"; "function_call_argument_list"; "function_call_right_paren"; ] | FunctionPointerExpression { function_pointer_receiver; function_pointer_type_args } -> ["function_pointer_receiver"; "function_pointer_type_args"] | ParenthesizedExpression { parenthesized_expression_left_paren; parenthesized_expression_expression; parenthesized_expression_right_paren; } -> [ "parenthesized_expression_left_paren"; "parenthesized_expression_expression"; "parenthesized_expression_right_paren"; ] | BracedExpression { braced_expression_left_brace; braced_expression_expression; braced_expression_right_brace; } -> [ "braced_expression_left_brace"; "braced_expression_expression"; "braced_expression_right_brace"; ] | ETSpliceExpression { et_splice_expression_dollar; et_splice_expression_left_brace; et_splice_expression_expression; et_splice_expression_right_brace; } -> [ "et_splice_expression_dollar"; "et_splice_expression_left_brace"; "et_splice_expression_expression"; "et_splice_expression_right_brace"; ] | EmbeddedBracedExpression { embedded_braced_expression_left_brace; embedded_braced_expression_expression; embedded_braced_expression_right_brace; } -> [ "embedded_braced_expression_left_brace"; "embedded_braced_expression_expression"; "embedded_braced_expression_right_brace"; ] | ListExpression { list_keyword; list_left_paren; list_members; list_right_paren } -> ["list_keyword"; "list_left_paren"; "list_members"; "list_right_paren"] | CollectionLiteralExpression { collection_literal_name; collection_literal_left_brace; collection_literal_initializers; collection_literal_right_brace; } -> [ "collection_literal_name"; "collection_literal_left_brace"; "collection_literal_initializers"; "collection_literal_right_brace"; ] | ObjectCreationExpression { object_creation_new_keyword; object_creation_object } -> ["object_creation_new_keyword"; "object_creation_object"] | ConstructorCall { constructor_call_type; constructor_call_left_paren; constructor_call_argument_list; constructor_call_right_paren; } -> [ "constructor_call_type"; "constructor_call_left_paren"; "constructor_call_argument_list"; "constructor_call_right_paren"; ] | DarrayIntrinsicExpression { darray_intrinsic_keyword; darray_intrinsic_explicit_type; darray_intrinsic_left_bracket; darray_intrinsic_members; darray_intrinsic_right_bracket; } -> [ "darray_intrinsic_keyword"; "darray_intrinsic_explicit_type"; "darray_intrinsic_left_bracket"; "darray_intrinsic_members"; "darray_intrinsic_right_bracket"; ] | DictionaryIntrinsicExpression { dictionary_intrinsic_keyword; dictionary_intrinsic_explicit_type; dictionary_intrinsic_left_bracket; dictionary_intrinsic_members; dictionary_intrinsic_right_bracket; } -> [ "dictionary_intrinsic_keyword"; "dictionary_intrinsic_explicit_type"; "dictionary_intrinsic_left_bracket"; "dictionary_intrinsic_members"; "dictionary_intrinsic_right_bracket"; ] | KeysetIntrinsicExpression { keyset_intrinsic_keyword; keyset_intrinsic_explicit_type; keyset_intrinsic_left_bracket; keyset_intrinsic_members; keyset_intrinsic_right_bracket; } -> [ "keyset_intrinsic_keyword"; "keyset_intrinsic_explicit_type"; "keyset_intrinsic_left_bracket"; "keyset_intrinsic_members"; "keyset_intrinsic_right_bracket"; ] | VarrayIntrinsicExpression { varray_intrinsic_keyword; varray_intrinsic_explicit_type; varray_intrinsic_left_bracket; varray_intrinsic_members; varray_intrinsic_right_bracket; } -> [ "varray_intrinsic_keyword"; "varray_intrinsic_explicit_type"; "varray_intrinsic_left_bracket"; "varray_intrinsic_members"; "varray_intrinsic_right_bracket"; ] | VectorIntrinsicExpression { vector_intrinsic_keyword; vector_intrinsic_explicit_type; vector_intrinsic_left_bracket; vector_intrinsic_members; vector_intrinsic_right_bracket; } -> [ "vector_intrinsic_keyword"; "vector_intrinsic_explicit_type"; "vector_intrinsic_left_bracket"; "vector_intrinsic_members"; "vector_intrinsic_right_bracket"; ] | ElementInitializer { element_key; element_arrow; element_value } -> ["element_key"; "element_arrow"; "element_value"] | SubscriptExpression { subscript_receiver; subscript_left_bracket; subscript_index; subscript_right_bracket; } -> [ "subscript_receiver"; "subscript_left_bracket"; "subscript_index"; "subscript_right_bracket"; ] | EmbeddedSubscriptExpression { embedded_subscript_receiver; embedded_subscript_left_bracket; embedded_subscript_index; embedded_subscript_right_bracket; } -> [ "embedded_subscript_receiver"; "embedded_subscript_left_bracket"; "embedded_subscript_index"; "embedded_subscript_right_bracket"; ] | AwaitableCreationExpression { awaitable_attribute_spec; awaitable_async; awaitable_compound_statement; } -> [ "awaitable_attribute_spec"; "awaitable_async"; "awaitable_compound_statement"; ] | XHPChildrenDeclaration { xhp_children_keyword; xhp_children_expression; xhp_children_semicolon; } -> [ "xhp_children_keyword"; "xhp_children_expression"; "xhp_children_semicolon"; ] | XHPChildrenParenthesizedList { xhp_children_list_left_paren; xhp_children_list_xhp_children; xhp_children_list_right_paren; } -> [ "xhp_children_list_left_paren"; "xhp_children_list_xhp_children"; "xhp_children_list_right_paren"; ] | XHPCategoryDeclaration { xhp_category_keyword; xhp_category_categories; xhp_category_semicolon; } -> [ "xhp_category_keyword"; "xhp_category_categories"; "xhp_category_semicolon"; ] | XHPEnumType { xhp_enum_like; xhp_enum_keyword; xhp_enum_left_brace; xhp_enum_values; xhp_enum_right_brace; } -> [ "xhp_enum_like"; "xhp_enum_keyword"; "xhp_enum_left_brace"; "xhp_enum_values"; "xhp_enum_right_brace"; ] | XHPLateinit { xhp_lateinit_at; xhp_lateinit_keyword } -> ["xhp_lateinit_at"; "xhp_lateinit_keyword"] | XHPRequired { xhp_required_at; xhp_required_keyword } -> ["xhp_required_at"; "xhp_required_keyword"] | XHPClassAttributeDeclaration { xhp_attribute_keyword; xhp_attribute_attributes; xhp_attribute_semicolon; } -> [ "xhp_attribute_keyword"; "xhp_attribute_attributes"; "xhp_attribute_semicolon"; ] | XHPClassAttribute { xhp_attribute_decl_type; xhp_attribute_decl_name; xhp_attribute_decl_initializer; xhp_attribute_decl_required; } -> [ "xhp_attribute_decl_type"; "xhp_attribute_decl_name"; "xhp_attribute_decl_initializer"; "xhp_attribute_decl_required"; ] | XHPSimpleClassAttribute { xhp_simple_class_attribute_type } -> ["xhp_simple_class_attribute_type"] | XHPSimpleAttribute { xhp_simple_attribute_name; xhp_simple_attribute_equal; xhp_simple_attribute_expression; } -> [ "xhp_simple_attribute_name"; "xhp_simple_attribute_equal"; "xhp_simple_attribute_expression"; ] | XHPSpreadAttribute { xhp_spread_attribute_left_brace; xhp_spread_attribute_spread_operator; xhp_spread_attribute_expression; xhp_spread_attribute_right_brace; } -> [ "xhp_spread_attribute_left_brace"; "xhp_spread_attribute_spread_operator"; "xhp_spread_attribute_expression"; "xhp_spread_attribute_right_brace"; ] | XHPOpen { xhp_open_left_angle; xhp_open_name; xhp_open_attributes; xhp_open_right_angle; } -> [ "xhp_open_left_angle"; "xhp_open_name"; "xhp_open_attributes"; "xhp_open_right_angle"; ] | XHPExpression { xhp_open; xhp_body; xhp_close } -> ["xhp_open"; "xhp_body"; "xhp_close"] | XHPClose { xhp_close_left_angle; xhp_close_name; xhp_close_right_angle } -> ["xhp_close_left_angle"; "xhp_close_name"; "xhp_close_right_angle"] | TypeConstant { type_constant_left_type; type_constant_separator; type_constant_right_type; } -> [ "type_constant_left_type"; "type_constant_separator"; "type_constant_right_type"; ] | VectorTypeSpecifier { vector_type_keyword; vector_type_left_angle; vector_type_type; vector_type_trailing_comma; vector_type_right_angle; } -> [ "vector_type_keyword"; "vector_type_left_angle"; "vector_type_type"; "vector_type_trailing_comma"; "vector_type_right_angle"; ] | KeysetTypeSpecifier { keyset_type_keyword; keyset_type_left_angle; keyset_type_type; keyset_type_trailing_comma; keyset_type_right_angle; } -> [ "keyset_type_keyword"; "keyset_type_left_angle"; "keyset_type_type"; "keyset_type_trailing_comma"; "keyset_type_right_angle"; ] | TupleTypeExplicitSpecifier { tuple_type_keyword; tuple_type_left_angle; tuple_type_types; tuple_type_right_angle; } -> [ "tuple_type_keyword"; "tuple_type_left_angle"; "tuple_type_types"; "tuple_type_right_angle"; ] | VarrayTypeSpecifier { varray_keyword; varray_left_angle; varray_type; varray_trailing_comma; varray_right_angle; } -> [ "varray_keyword"; "varray_left_angle"; "varray_type"; "varray_trailing_comma"; "varray_right_angle"; ] | FunctionCtxTypeSpecifier { function_ctx_type_keyword; function_ctx_type_variable } -> ["function_ctx_type_keyword"; "function_ctx_type_variable"] | TypeParameter { type_attribute_spec; type_reified; type_variance; type_name; type_param_params; type_constraints; } -> [ "type_attribute_spec"; "type_reified"; "type_variance"; "type_name"; "type_param_params"; "type_constraints"; ] | TypeConstraint { constraint_keyword; constraint_type } -> ["constraint_keyword"; "constraint_type"] | ContextConstraint { ctx_constraint_keyword; ctx_constraint_ctx_list } -> ["ctx_constraint_keyword"; "ctx_constraint_ctx_list"] | DarrayTypeSpecifier { darray_keyword; darray_left_angle; darray_key; darray_comma; darray_value; darray_trailing_comma; darray_right_angle; } -> [ "darray_keyword"; "darray_left_angle"; "darray_key"; "darray_comma"; "darray_value"; "darray_trailing_comma"; "darray_right_angle"; ] | DictionaryTypeSpecifier { dictionary_type_keyword; dictionary_type_left_angle; dictionary_type_members; dictionary_type_right_angle; } -> [ "dictionary_type_keyword"; "dictionary_type_left_angle"; "dictionary_type_members"; "dictionary_type_right_angle"; ] | ClosureTypeSpecifier { closure_outer_left_paren; closure_readonly_keyword; closure_function_keyword; closure_inner_left_paren; closure_parameter_list; closure_inner_right_paren; closure_contexts; closure_colon; closure_readonly_return; closure_return_type; closure_outer_right_paren; } -> [ "closure_outer_left_paren"; "closure_readonly_keyword"; "closure_function_keyword"; "closure_inner_left_paren"; "closure_parameter_list"; "closure_inner_right_paren"; "closure_contexts"; "closure_colon"; "closure_readonly_return"; "closure_return_type"; "closure_outer_right_paren"; ] | ClosureParameterTypeSpecifier { closure_parameter_call_convention; closure_parameter_readonly; closure_parameter_type; } -> [ "closure_parameter_call_convention"; "closure_parameter_readonly"; "closure_parameter_type"; ] | TypeRefinement { type_refinement_type; type_refinement_keyword; type_refinement_left_brace; type_refinement_members; type_refinement_right_brace; } -> [ "type_refinement_type"; "type_refinement_keyword"; "type_refinement_left_brace"; "type_refinement_members"; "type_refinement_right_brace"; ] | TypeInRefinement { type_in_refinement_keyword; type_in_refinement_name; type_in_refinement_type_parameters; type_in_refinement_constraints; type_in_refinement_equal; type_in_refinement_type; } -> [ "type_in_refinement_keyword"; "type_in_refinement_name"; "type_in_refinement_type_parameters"; "type_in_refinement_constraints"; "type_in_refinement_equal"; "type_in_refinement_type"; ] | CtxInRefinement { ctx_in_refinement_keyword; ctx_in_refinement_name; ctx_in_refinement_type_parameters; ctx_in_refinement_constraints; ctx_in_refinement_equal; ctx_in_refinement_ctx_list; } -> [ "ctx_in_refinement_keyword"; "ctx_in_refinement_name"; "ctx_in_refinement_type_parameters"; "ctx_in_refinement_constraints"; "ctx_in_refinement_equal"; "ctx_in_refinement_ctx_list"; ] | ClassnameTypeSpecifier { classname_keyword; classname_left_angle; classname_type; classname_trailing_comma; classname_right_angle; } -> [ "classname_keyword"; "classname_left_angle"; "classname_type"; "classname_trailing_comma"; "classname_right_angle"; ] | FieldSpecifier { field_question; field_name; field_arrow; field_type } -> ["field_question"; "field_name"; "field_arrow"; "field_type"] | FieldInitializer { field_initializer_name; field_initializer_arrow; field_initializer_value; } -> [ "field_initializer_name"; "field_initializer_arrow"; "field_initializer_value"; ] | ShapeTypeSpecifier { shape_type_keyword; shape_type_left_paren; shape_type_fields; shape_type_ellipsis; shape_type_right_paren; } -> [ "shape_type_keyword"; "shape_type_left_paren"; "shape_type_fields"; "shape_type_ellipsis"; "shape_type_right_paren"; ] | ShapeExpression { shape_expression_keyword; shape_expression_left_paren; shape_expression_fields; shape_expression_right_paren; } -> [ "shape_expression_keyword"; "shape_expression_left_paren"; "shape_expression_fields"; "shape_expression_right_paren"; ] | TupleExpression { tuple_expression_keyword; tuple_expression_left_paren; tuple_expression_items; tuple_expression_right_paren; } -> [ "tuple_expression_keyword"; "tuple_expression_left_paren"; "tuple_expression_items"; "tuple_expression_right_paren"; ] | GenericTypeSpecifier { generic_class_type; generic_argument_list } -> ["generic_class_type"; "generic_argument_list"] | NullableTypeSpecifier { nullable_question; nullable_type } -> ["nullable_question"; "nullable_type"] | LikeTypeSpecifier { like_tilde; like_type } -> ["like_tilde"; "like_type"] | SoftTypeSpecifier { soft_at; soft_type } -> ["soft_at"; "soft_type"] | AttributizedSpecifier { attributized_specifier_attribute_spec; attributized_specifier_type } -> ["attributized_specifier_attribute_spec"; "attributized_specifier_type"] | ReifiedTypeArgument { reified_type_argument_reified; reified_type_argument_type } -> ["reified_type_argument_reified"; "reified_type_argument_type"] | TypeArguments { type_arguments_left_angle; type_arguments_types; type_arguments_right_angle; } -> [ "type_arguments_left_angle"; "type_arguments_types"; "type_arguments_right_angle"; ] | TypeParameters { type_parameters_left_angle; type_parameters_parameters; type_parameters_right_angle; } -> [ "type_parameters_left_angle"; "type_parameters_parameters"; "type_parameters_right_angle"; ] | TupleTypeSpecifier { tuple_left_paren; tuple_types; tuple_right_paren } -> ["tuple_left_paren"; "tuple_types"; "tuple_right_paren"] | UnionTypeSpecifier { union_left_paren; union_types; union_right_paren } -> ["union_left_paren"; "union_types"; "union_right_paren"] | IntersectionTypeSpecifier { intersection_left_paren; intersection_types; intersection_right_paren; } -> [ "intersection_left_paren"; "intersection_types"; "intersection_right_paren"; ] | ErrorSyntax { error_error } -> ["error_error"] | ListItem { list_item; list_separator } -> ["list_item"; "list_separator"] | EnumClassLabelExpression { enum_class_label_qualifier; enum_class_label_hash; enum_class_label_expression; } -> [ "enum_class_label_qualifier"; "enum_class_label_hash"; "enum_class_label_expression"; ] | ModuleDeclaration { module_declaration_attribute_spec; module_declaration_new_keyword; module_declaration_module_keyword; module_declaration_name; module_declaration_left_brace; module_declaration_exports; module_declaration_imports; module_declaration_right_brace; } -> [ "module_declaration_attribute_spec"; "module_declaration_new_keyword"; "module_declaration_module_keyword"; "module_declaration_name"; "module_declaration_left_brace"; "module_declaration_exports"; "module_declaration_imports"; "module_declaration_right_brace"; ] | ModuleExports { module_exports_exports_keyword; module_exports_left_brace; module_exports_exports; module_exports_right_brace; } -> [ "module_exports_exports_keyword"; "module_exports_left_brace"; "module_exports_exports"; "module_exports_right_brace"; ] | ModuleImports { module_imports_imports_keyword; module_imports_left_brace; module_imports_imports; module_imports_right_brace; } -> [ "module_imports_imports_keyword"; "module_imports_left_brace"; "module_imports_imports"; "module_imports_right_brace"; ] | ModuleMembershipDeclaration { module_membership_declaration_module_keyword; module_membership_declaration_name; module_membership_declaration_semicolon; } -> [ "module_membership_declaration_module_keyword"; "module_membership_declaration_name"; "module_membership_declaration_semicolon"; ] | PackageExpression { package_expression_keyword; package_expression_name } -> ["package_expression_keyword"; "package_expression_name"] let rec to_json_ ?(with_value = false) ?(ignore_missing = false) node = let open Hh_json in let ch = match node.syntax with | Token t -> [("token", Token.to_json t)] | SyntaxList x -> [ ( "elements", JSON_Array (List.filter_map ~f:(to_json_ ~with_value ~ignore_missing) x) ); ] | _ -> let rec aux acc c n = match (c, n) with | ([], []) -> acc | (hc :: tc, hn :: tn) -> let result = (to_json_ ~with_value ~ignore_missing) hc in (match result with | Some r -> aux ((hn, r) :: acc) tc tn | None -> aux acc tc tn) | _ -> failwith "mismatch between children and names" in List.rev (aux [] (children node) (children_names node)) in let k = ("kind", JSON_String (SyntaxKind.to_string (kind node))) in let v = if with_value then ("value", SyntaxValue.to_json node.value) :: ch else ch in if ignore_missing && List.is_empty ch then None else Some (JSON_Object (k :: v)) let to_json ?(with_value = false) ?(ignore_missing = false) node = match to_json_ ~with_value ~ignore_missing node with | Some x -> x | None -> Hh_json.JSON_Object [] let binary_operator_kind b = match syntax b with | Token token -> let kind = Token.kind token in if Operator.is_trailing_operator_token kind then Some (Operator.trailing_from_token kind) else None | _ -> None let get_token node = match syntax node with | Token token -> Some token | _ -> None let leading_token node = let rec aux nodes = match nodes with | [] -> None | h :: t -> let token = get_token h in if Option.is_none token then let result = aux (children h) in if Option.is_none result then aux t else result else token in aux [node] let trailing_token node = let rec aux nodes = match nodes with | [] -> None | h :: t -> let token = get_token h in if Option.is_none token then let result = aux (List.rev (children h)) in if Option.is_none result then aux t else result else token in aux [node] let syntax_from_children kind ts = match (kind, ts) with | (SyntaxKind.EndOfFile, [end_of_file_token]) -> EndOfFile { end_of_file_token } | (SyntaxKind.Script, [script_declarations]) -> Script { script_declarations } | (SyntaxKind.QualifiedName, [qualified_name_parts]) -> QualifiedName { qualified_name_parts } | (SyntaxKind.ModuleName, [module_name_parts]) -> ModuleName { module_name_parts } | (SyntaxKind.SimpleTypeSpecifier, [simple_type_specifier]) -> SimpleTypeSpecifier { simple_type_specifier } | (SyntaxKind.LiteralExpression, [literal_expression]) -> LiteralExpression { literal_expression } | ( SyntaxKind.PrefixedStringExpression, [prefixed_string_name; prefixed_string_str] ) -> PrefixedStringExpression { prefixed_string_name; prefixed_string_str } | ( SyntaxKind.PrefixedCodeExpression, [ prefixed_code_prefix; prefixed_code_left_backtick; prefixed_code_body; prefixed_code_right_backtick; ] ) -> PrefixedCodeExpression { prefixed_code_prefix; prefixed_code_left_backtick; prefixed_code_body; prefixed_code_right_backtick; } | (SyntaxKind.VariableExpression, [variable_expression]) -> VariableExpression { variable_expression } | (SyntaxKind.PipeVariableExpression, [pipe_variable_expression]) -> PipeVariableExpression { pipe_variable_expression } | ( SyntaxKind.FileAttributeSpecification, [ file_attribute_specification_left_double_angle; file_attribute_specification_keyword; file_attribute_specification_colon; file_attribute_specification_attributes; file_attribute_specification_right_double_angle; ] ) -> FileAttributeSpecification { file_attribute_specification_left_double_angle; file_attribute_specification_keyword; file_attribute_specification_colon; file_attribute_specification_attributes; file_attribute_specification_right_double_angle; } | ( SyntaxKind.EnumDeclaration, [ enum_attribute_spec; enum_modifiers; enum_keyword; enum_name; enum_colon; enum_base; enum_type; enum_left_brace; enum_use_clauses; enum_enumerators; enum_right_brace; ] ) -> EnumDeclaration { enum_attribute_spec; enum_modifiers; enum_keyword; enum_name; enum_colon; enum_base; enum_type; enum_left_brace; enum_use_clauses; enum_enumerators; enum_right_brace; } | ( SyntaxKind.EnumUse, [enum_use_keyword; enum_use_names; enum_use_semicolon] ) -> EnumUse { enum_use_keyword; enum_use_names; enum_use_semicolon } | ( SyntaxKind.Enumerator, [ enumerator_name; enumerator_equal; enumerator_value; enumerator_semicolon; ] ) -> Enumerator { enumerator_name; enumerator_equal; enumerator_value; enumerator_semicolon; } | ( SyntaxKind.EnumClassDeclaration, [ enum_class_attribute_spec; enum_class_modifiers; enum_class_enum_keyword; enum_class_class_keyword; enum_class_name; enum_class_colon; enum_class_base; enum_class_extends; enum_class_extends_list; enum_class_left_brace; enum_class_elements; enum_class_right_brace; ] ) -> EnumClassDeclaration { enum_class_attribute_spec; enum_class_modifiers; enum_class_enum_keyword; enum_class_class_keyword; enum_class_name; enum_class_colon; enum_class_base; enum_class_extends; enum_class_extends_list; enum_class_left_brace; enum_class_elements; enum_class_right_brace; } | ( SyntaxKind.EnumClassEnumerator, [ enum_class_enumerator_modifiers; enum_class_enumerator_type; enum_class_enumerator_name; enum_class_enumerator_initializer; enum_class_enumerator_semicolon; ] ) -> EnumClassEnumerator { enum_class_enumerator_modifiers; enum_class_enumerator_type; enum_class_enumerator_name; enum_class_enumerator_initializer; enum_class_enumerator_semicolon; } | ( SyntaxKind.AliasDeclaration, [ alias_attribute_spec; alias_modifiers; alias_module_kw_opt; alias_keyword; alias_name; alias_generic_parameter; alias_constraint; alias_equal; alias_type; alias_semicolon; ] ) -> AliasDeclaration { alias_attribute_spec; alias_modifiers; alias_module_kw_opt; alias_keyword; alias_name; alias_generic_parameter; alias_constraint; alias_equal; alias_type; alias_semicolon; } | ( SyntaxKind.ContextAliasDeclaration, [ ctx_alias_attribute_spec; ctx_alias_keyword; ctx_alias_name; ctx_alias_generic_parameter; ctx_alias_as_constraint; ctx_alias_equal; ctx_alias_context; ctx_alias_semicolon; ] ) -> ContextAliasDeclaration { ctx_alias_attribute_spec; ctx_alias_keyword; ctx_alias_name; ctx_alias_generic_parameter; ctx_alias_as_constraint; ctx_alias_equal; ctx_alias_context; ctx_alias_semicolon; } | ( SyntaxKind.CaseTypeDeclaration, [ case_type_attribute_spec; case_type_modifiers; case_type_case_keyword; case_type_type_keyword; case_type_name; case_type_generic_parameter; case_type_as; case_type_bounds; case_type_equal; case_type_variants; case_type_semicolon; ] ) -> CaseTypeDeclaration { case_type_attribute_spec; case_type_modifiers; case_type_case_keyword; case_type_type_keyword; case_type_name; case_type_generic_parameter; case_type_as; case_type_bounds; case_type_equal; case_type_variants; case_type_semicolon; } | ( SyntaxKind.CaseTypeVariant, [case_type_variant_bar; case_type_variant_type] ) -> CaseTypeVariant { case_type_variant_bar; case_type_variant_type } | ( SyntaxKind.PropertyDeclaration, [ property_attribute_spec; property_modifiers; property_type; property_declarators; property_semicolon; ] ) -> PropertyDeclaration { property_attribute_spec; property_modifiers; property_type; property_declarators; property_semicolon; } | (SyntaxKind.PropertyDeclarator, [property_name; property_initializer]) -> PropertyDeclarator { property_name; property_initializer } | (SyntaxKind.NamespaceDeclaration, [namespace_header; namespace_body]) -> NamespaceDeclaration { namespace_header; namespace_body } | ( SyntaxKind.NamespaceDeclarationHeader, [namespace_keyword; namespace_name] ) -> NamespaceDeclarationHeader { namespace_keyword; namespace_name } | ( SyntaxKind.NamespaceBody, [namespace_left_brace; namespace_declarations; namespace_right_brace] ) -> NamespaceBody { namespace_left_brace; namespace_declarations; namespace_right_brace; } | (SyntaxKind.NamespaceEmptyBody, [namespace_semicolon]) -> NamespaceEmptyBody { namespace_semicolon } | ( SyntaxKind.NamespaceUseDeclaration, [ namespace_use_keyword; namespace_use_kind; namespace_use_clauses; namespace_use_semicolon; ] ) -> NamespaceUseDeclaration { namespace_use_keyword; namespace_use_kind; namespace_use_clauses; namespace_use_semicolon; } | ( SyntaxKind.NamespaceGroupUseDeclaration, [ namespace_group_use_keyword; namespace_group_use_kind; namespace_group_use_prefix; namespace_group_use_left_brace; namespace_group_use_clauses; namespace_group_use_right_brace; namespace_group_use_semicolon; ] ) -> NamespaceGroupUseDeclaration { namespace_group_use_keyword; namespace_group_use_kind; namespace_group_use_prefix; namespace_group_use_left_brace; namespace_group_use_clauses; namespace_group_use_right_brace; namespace_group_use_semicolon; } | ( SyntaxKind.NamespaceUseClause, [ namespace_use_clause_kind; namespace_use_name; namespace_use_as; namespace_use_alias; ] ) -> NamespaceUseClause { namespace_use_clause_kind; namespace_use_name; namespace_use_as; namespace_use_alias; } | ( SyntaxKind.FunctionDeclaration, [function_attribute_spec; function_declaration_header; function_body] ) -> FunctionDeclaration { function_attribute_spec; function_declaration_header; function_body; } | ( SyntaxKind.FunctionDeclarationHeader, [ function_modifiers; function_keyword; function_name; function_type_parameter_list; function_left_paren; function_parameter_list; function_right_paren; function_contexts; function_colon; function_readonly_return; function_type; function_where_clause; ] ) -> FunctionDeclarationHeader { function_modifiers; function_keyword; function_name; function_type_parameter_list; function_left_paren; function_parameter_list; function_right_paren; function_contexts; function_colon; function_readonly_return; function_type; function_where_clause; } | ( SyntaxKind.Contexts, [contexts_left_bracket; contexts_types; contexts_right_bracket] ) -> Contexts { contexts_left_bracket; contexts_types; contexts_right_bracket } | ( SyntaxKind.WhereClause, [where_clause_keyword; where_clause_constraints] ) -> WhereClause { where_clause_keyword; where_clause_constraints } | ( SyntaxKind.WhereConstraint, [ where_constraint_left_type; where_constraint_operator; where_constraint_right_type; ] ) -> WhereConstraint { where_constraint_left_type; where_constraint_operator; where_constraint_right_type; } | ( SyntaxKind.MethodishDeclaration, [ methodish_attribute; methodish_function_decl_header; methodish_function_body; methodish_semicolon; ] ) -> MethodishDeclaration { methodish_attribute; methodish_function_decl_header; methodish_function_body; methodish_semicolon; } | ( SyntaxKind.MethodishTraitResolution, [ methodish_trait_attribute; methodish_trait_function_decl_header; methodish_trait_equal; methodish_trait_name; methodish_trait_semicolon; ] ) -> MethodishTraitResolution { methodish_trait_attribute; methodish_trait_function_decl_header; methodish_trait_equal; methodish_trait_name; methodish_trait_semicolon; } | ( SyntaxKind.ClassishDeclaration, [ classish_attribute; classish_modifiers; classish_xhp; classish_keyword; classish_name; classish_type_parameters; classish_extends_keyword; classish_extends_list; classish_implements_keyword; classish_implements_list; classish_where_clause; classish_body; ] ) -> ClassishDeclaration { classish_attribute; classish_modifiers; classish_xhp; classish_keyword; classish_name; classish_type_parameters; classish_extends_keyword; classish_extends_list; classish_implements_keyword; classish_implements_list; classish_where_clause; classish_body; } | ( SyntaxKind.ClassishBody, [ classish_body_left_brace; classish_body_elements; classish_body_right_brace; ] ) -> ClassishBody { classish_body_left_brace; classish_body_elements; classish_body_right_brace; } | ( SyntaxKind.TraitUse, [trait_use_keyword; trait_use_names; trait_use_semicolon] ) -> TraitUse { trait_use_keyword; trait_use_names; trait_use_semicolon } | ( SyntaxKind.RequireClause, [require_keyword; require_kind; require_name; require_semicolon] ) -> RequireClause { require_keyword; require_kind; require_name; require_semicolon } | ( SyntaxKind.ConstDeclaration, [ const_attribute_spec; const_modifiers; const_keyword; const_type_specifier; const_declarators; const_semicolon; ] ) -> ConstDeclaration { const_attribute_spec; const_modifiers; const_keyword; const_type_specifier; const_declarators; const_semicolon; } | ( SyntaxKind.ConstantDeclarator, [constant_declarator_name; constant_declarator_initializer] ) -> ConstantDeclarator { constant_declarator_name; constant_declarator_initializer } | ( SyntaxKind.TypeConstDeclaration, [ type_const_attribute_spec; type_const_modifiers; type_const_keyword; type_const_type_keyword; type_const_name; type_const_type_parameters; type_const_type_constraints; type_const_equal; type_const_type_specifier; type_const_semicolon; ] ) -> TypeConstDeclaration { type_const_attribute_spec; type_const_modifiers; type_const_keyword; type_const_type_keyword; type_const_name; type_const_type_parameters; type_const_type_constraints; type_const_equal; type_const_type_specifier; type_const_semicolon; } | ( SyntaxKind.ContextConstDeclaration, [ context_const_modifiers; context_const_const_keyword; context_const_ctx_keyword; context_const_name; context_const_type_parameters; context_const_constraint; context_const_equal; context_const_ctx_list; context_const_semicolon; ] ) -> ContextConstDeclaration { context_const_modifiers; context_const_const_keyword; context_const_ctx_keyword; context_const_name; context_const_type_parameters; context_const_constraint; context_const_equal; context_const_ctx_list; context_const_semicolon; } | ( SyntaxKind.DecoratedExpression, [decorated_expression_decorator; decorated_expression_expression] ) -> DecoratedExpression { decorated_expression_decorator; decorated_expression_expression } | ( SyntaxKind.ParameterDeclaration, [ parameter_attribute; parameter_visibility; parameter_call_convention; parameter_readonly; parameter_type; parameter_name; parameter_default_value; ] ) -> ParameterDeclaration { parameter_attribute; parameter_visibility; parameter_call_convention; parameter_readonly; parameter_type; parameter_name; parameter_default_value; } | ( SyntaxKind.VariadicParameter, [ variadic_parameter_call_convention; variadic_parameter_type; variadic_parameter_ellipsis; ] ) -> VariadicParameter { variadic_parameter_call_convention; variadic_parameter_type; variadic_parameter_ellipsis; } | ( SyntaxKind.OldAttributeSpecification, [ old_attribute_specification_left_double_angle; old_attribute_specification_attributes; old_attribute_specification_right_double_angle; ] ) -> OldAttributeSpecification { old_attribute_specification_left_double_angle; old_attribute_specification_attributes; old_attribute_specification_right_double_angle; } | (SyntaxKind.AttributeSpecification, [attribute_specification_attributes]) -> AttributeSpecification { attribute_specification_attributes } | (SyntaxKind.Attribute, [attribute_at; attribute_attribute_name]) -> Attribute { attribute_at; attribute_attribute_name } | (SyntaxKind.InclusionExpression, [inclusion_require; inclusion_filename]) -> InclusionExpression { inclusion_require; inclusion_filename } | ( SyntaxKind.InclusionDirective, [inclusion_expression; inclusion_semicolon] ) -> InclusionDirective { inclusion_expression; inclusion_semicolon } | ( SyntaxKind.CompoundStatement, [compound_left_brace; compound_statements; compound_right_brace] ) -> CompoundStatement { compound_left_brace; compound_statements; compound_right_brace } | ( SyntaxKind.ExpressionStatement, [expression_statement_expression; expression_statement_semicolon] ) -> ExpressionStatement { expression_statement_expression; expression_statement_semicolon } | (SyntaxKind.MarkupSection, [markup_hashbang; markup_suffix]) -> MarkupSection { markup_hashbang; markup_suffix } | ( SyntaxKind.MarkupSuffix, [markup_suffix_less_than_question; markup_suffix_name] ) -> MarkupSuffix { markup_suffix_less_than_question; markup_suffix_name } | ( SyntaxKind.UnsetStatement, [ unset_keyword; unset_left_paren; unset_variables; unset_right_paren; unset_semicolon; ] ) -> UnsetStatement { unset_keyword; unset_left_paren; unset_variables; unset_right_paren; unset_semicolon; } | ( SyntaxKind.DeclareLocalStatement, [ declare_local_keyword; declare_local_variable; declare_local_colon; declare_local_type; declare_local_initializer; declare_local_semicolon; ] ) -> DeclareLocalStatement { declare_local_keyword; declare_local_variable; declare_local_colon; declare_local_type; declare_local_initializer; declare_local_semicolon; } | ( SyntaxKind.UsingStatementBlockScoped, [ using_block_await_keyword; using_block_using_keyword; using_block_left_paren; using_block_expressions; using_block_right_paren; using_block_body; ] ) -> UsingStatementBlockScoped { using_block_await_keyword; using_block_using_keyword; using_block_left_paren; using_block_expressions; using_block_right_paren; using_block_body; } | ( SyntaxKind.UsingStatementFunctionScoped, [ using_function_await_keyword; using_function_using_keyword; using_function_expression; using_function_semicolon; ] ) -> UsingStatementFunctionScoped { using_function_await_keyword; using_function_using_keyword; using_function_expression; using_function_semicolon; } | ( SyntaxKind.WhileStatement, [ while_keyword; while_left_paren; while_condition; while_right_paren; while_body; ] ) -> WhileStatement { while_keyword; while_left_paren; while_condition; while_right_paren; while_body; } | ( SyntaxKind.IfStatement, [ if_keyword; if_left_paren; if_condition; if_right_paren; if_statement; if_else_clause; ] ) -> IfStatement { if_keyword; if_left_paren; if_condition; if_right_paren; if_statement; if_else_clause; } | (SyntaxKind.ElseClause, [else_keyword; else_statement]) -> ElseClause { else_keyword; else_statement } | ( SyntaxKind.TryStatement, [ try_keyword; try_compound_statement; try_catch_clauses; try_finally_clause; ] ) -> TryStatement { try_keyword; try_compound_statement; try_catch_clauses; try_finally_clause; } | ( SyntaxKind.CatchClause, [ catch_keyword; catch_left_paren; catch_type; catch_variable; catch_right_paren; catch_body; ] ) -> CatchClause { catch_keyword; catch_left_paren; catch_type; catch_variable; catch_right_paren; catch_body; } | (SyntaxKind.FinallyClause, [finally_keyword; finally_body]) -> FinallyClause { finally_keyword; finally_body } | ( SyntaxKind.DoStatement, [ do_keyword; do_body; do_while_keyword; do_left_paren; do_condition; do_right_paren; do_semicolon; ] ) -> DoStatement { do_keyword; do_body; do_while_keyword; do_left_paren; do_condition; do_right_paren; do_semicolon; } | ( SyntaxKind.ForStatement, [ for_keyword; for_left_paren; for_initializer; for_first_semicolon; for_control; for_second_semicolon; for_end_of_loop; for_right_paren; for_body; ] ) -> ForStatement { for_keyword; for_left_paren; for_initializer; for_first_semicolon; for_control; for_second_semicolon; for_end_of_loop; for_right_paren; for_body; } | ( SyntaxKind.ForeachStatement, [ foreach_keyword; foreach_left_paren; foreach_collection; foreach_await_keyword; foreach_as; foreach_key; foreach_arrow; foreach_value; foreach_right_paren; foreach_body; ] ) -> ForeachStatement { foreach_keyword; foreach_left_paren; foreach_collection; foreach_await_keyword; foreach_as; foreach_key; foreach_arrow; foreach_value; foreach_right_paren; foreach_body; } | ( SyntaxKind.SwitchStatement, [ switch_keyword; switch_left_paren; switch_expression; switch_right_paren; switch_left_brace; switch_sections; switch_right_brace; ] ) -> SwitchStatement { switch_keyword; switch_left_paren; switch_expression; switch_right_paren; switch_left_brace; switch_sections; switch_right_brace; } | ( SyntaxKind.SwitchSection, [ switch_section_labels; switch_section_statements; switch_section_fallthrough; ] ) -> SwitchSection { switch_section_labels; switch_section_statements; switch_section_fallthrough; } | ( SyntaxKind.SwitchFallthrough, [fallthrough_keyword; fallthrough_semicolon] ) -> SwitchFallthrough { fallthrough_keyword; fallthrough_semicolon } | (SyntaxKind.CaseLabel, [case_keyword; case_expression; case_colon]) -> CaseLabel { case_keyword; case_expression; case_colon } | (SyntaxKind.DefaultLabel, [default_keyword; default_colon]) -> DefaultLabel { default_keyword; default_colon } | ( SyntaxKind.MatchStatement, [ match_statement_keyword; match_statement_left_paren; match_statement_expression; match_statement_right_paren; match_statement_left_brace; match_statement_arms; match_statement_right_brace; ] ) -> MatchStatement { match_statement_keyword; match_statement_left_paren; match_statement_expression; match_statement_right_paren; match_statement_left_brace; match_statement_arms; match_statement_right_brace; } | ( SyntaxKind.MatchStatementArm, [ match_statement_arm_pattern; match_statement_arm_arrow; match_statement_arm_body; ] ) -> MatchStatementArm { match_statement_arm_pattern; match_statement_arm_arrow; match_statement_arm_body; } | ( SyntaxKind.ReturnStatement, [return_keyword; return_expression; return_semicolon] ) -> ReturnStatement { return_keyword; return_expression; return_semicolon } | ( SyntaxKind.YieldBreakStatement, [yield_break_keyword; yield_break_break; yield_break_semicolon] ) -> YieldBreakStatement { yield_break_keyword; yield_break_break; yield_break_semicolon } | ( SyntaxKind.ThrowStatement, [throw_keyword; throw_expression; throw_semicolon] ) -> ThrowStatement { throw_keyword; throw_expression; throw_semicolon } | (SyntaxKind.BreakStatement, [break_keyword; break_semicolon]) -> BreakStatement { break_keyword; break_semicolon } | (SyntaxKind.ContinueStatement, [continue_keyword; continue_semicolon]) -> ContinueStatement { continue_keyword; continue_semicolon } | ( SyntaxKind.EchoStatement, [echo_keyword; echo_expressions; echo_semicolon] ) -> EchoStatement { echo_keyword; echo_expressions; echo_semicolon } | ( SyntaxKind.ConcurrentStatement, [concurrent_keyword; concurrent_statement] ) -> ConcurrentStatement { concurrent_keyword; concurrent_statement } | ( SyntaxKind.SimpleInitializer, [simple_initializer_equal; simple_initializer_value] ) -> SimpleInitializer { simple_initializer_equal; simple_initializer_value } | ( SyntaxKind.AnonymousClass, [ anonymous_class_class_keyword; anonymous_class_left_paren; anonymous_class_argument_list; anonymous_class_right_paren; anonymous_class_extends_keyword; anonymous_class_extends_list; anonymous_class_implements_keyword; anonymous_class_implements_list; anonymous_class_body; ] ) -> AnonymousClass { anonymous_class_class_keyword; anonymous_class_left_paren; anonymous_class_argument_list; anonymous_class_right_paren; anonymous_class_extends_keyword; anonymous_class_extends_list; anonymous_class_implements_keyword; anonymous_class_implements_list; anonymous_class_body; } | ( SyntaxKind.AnonymousFunction, [ anonymous_attribute_spec; anonymous_async_keyword; anonymous_function_keyword; anonymous_left_paren; anonymous_parameters; anonymous_right_paren; anonymous_ctx_list; anonymous_colon; anonymous_readonly_return; anonymous_type; anonymous_use; anonymous_body; ] ) -> AnonymousFunction { anonymous_attribute_spec; anonymous_async_keyword; anonymous_function_keyword; anonymous_left_paren; anonymous_parameters; anonymous_right_paren; anonymous_ctx_list; anonymous_colon; anonymous_readonly_return; anonymous_type; anonymous_use; anonymous_body; } | ( SyntaxKind.AnonymousFunctionUseClause, [ anonymous_use_keyword; anonymous_use_left_paren; anonymous_use_variables; anonymous_use_right_paren; ] ) -> AnonymousFunctionUseClause { anonymous_use_keyword; anonymous_use_left_paren; anonymous_use_variables; anonymous_use_right_paren; } | (SyntaxKind.VariablePattern, [variable_pattern_variable]) -> VariablePattern { variable_pattern_variable } | ( SyntaxKind.ConstructorPattern, [ constructor_pattern_constructor; constructor_pattern_left_paren; constructor_pattern_members; constructor_pattern_right_paren; ] ) -> ConstructorPattern { constructor_pattern_constructor; constructor_pattern_left_paren; constructor_pattern_members; constructor_pattern_right_paren; } | ( SyntaxKind.RefinementPattern, [ refinement_pattern_variable; refinement_pattern_colon; refinement_pattern_specifier; ] ) -> RefinementPattern { refinement_pattern_variable; refinement_pattern_colon; refinement_pattern_specifier; } | ( SyntaxKind.LambdaExpression, [ lambda_attribute_spec; lambda_async; lambda_signature; lambda_arrow; lambda_body; ] ) -> LambdaExpression { lambda_attribute_spec; lambda_async; lambda_signature; lambda_arrow; lambda_body; } | ( SyntaxKind.LambdaSignature, [ lambda_left_paren; lambda_parameters; lambda_right_paren; lambda_contexts; lambda_colon; lambda_readonly_return; lambda_type; ] ) -> LambdaSignature { lambda_left_paren; lambda_parameters; lambda_right_paren; lambda_contexts; lambda_colon; lambda_readonly_return; lambda_type; } | ( SyntaxKind.CastExpression, [cast_left_paren; cast_type; cast_right_paren; cast_operand] ) -> CastExpression { cast_left_paren; cast_type; cast_right_paren; cast_operand } | ( SyntaxKind.ScopeResolutionExpression, [ scope_resolution_qualifier; scope_resolution_operator; scope_resolution_name; ] ) -> ScopeResolutionExpression { scope_resolution_qualifier; scope_resolution_operator; scope_resolution_name; } | ( SyntaxKind.MemberSelectionExpression, [member_object; member_operator; member_name] ) -> MemberSelectionExpression { member_object; member_operator; member_name } | ( SyntaxKind.SafeMemberSelectionExpression, [safe_member_object; safe_member_operator; safe_member_name] ) -> SafeMemberSelectionExpression { safe_member_object; safe_member_operator; safe_member_name } | ( SyntaxKind.EmbeddedMemberSelectionExpression, [ embedded_member_object; embedded_member_operator; embedded_member_name; ] ) -> EmbeddedMemberSelectionExpression { embedded_member_object; embedded_member_operator; embedded_member_name; } | (SyntaxKind.YieldExpression, [yield_keyword; yield_operand]) -> YieldExpression { yield_keyword; yield_operand } | ( SyntaxKind.PrefixUnaryExpression, [prefix_unary_operator; prefix_unary_operand] ) -> PrefixUnaryExpression { prefix_unary_operator; prefix_unary_operand } | ( SyntaxKind.PostfixUnaryExpression, [postfix_unary_operand; postfix_unary_operator] ) -> PostfixUnaryExpression { postfix_unary_operand; postfix_unary_operator } | ( SyntaxKind.BinaryExpression, [binary_left_operand; binary_operator; binary_right_operand] ) -> BinaryExpression { binary_left_operand; binary_operator; binary_right_operand } | ( SyntaxKind.IsExpression, [is_left_operand; is_operator; is_right_operand] ) -> IsExpression { is_left_operand; is_operator; is_right_operand } | ( SyntaxKind.AsExpression, [as_left_operand; as_operator; as_right_operand] ) -> AsExpression { as_left_operand; as_operator; as_right_operand } | ( SyntaxKind.NullableAsExpression, [ nullable_as_left_operand; nullable_as_operator; nullable_as_right_operand; ] ) -> NullableAsExpression { nullable_as_left_operand; nullable_as_operator; nullable_as_right_operand; } | ( SyntaxKind.UpcastExpression, [upcast_left_operand; upcast_operator; upcast_right_operand] ) -> UpcastExpression { upcast_left_operand; upcast_operator; upcast_right_operand } | ( SyntaxKind.ConditionalExpression, [ conditional_test; conditional_question; conditional_consequence; conditional_colon; conditional_alternative; ] ) -> ConditionalExpression { conditional_test; conditional_question; conditional_consequence; conditional_colon; conditional_alternative; } | ( SyntaxKind.EvalExpression, [eval_keyword; eval_left_paren; eval_argument; eval_right_paren] ) -> EvalExpression { eval_keyword; eval_left_paren; eval_argument; eval_right_paren } | ( SyntaxKind.IssetExpression, [ isset_keyword; isset_left_paren; isset_argument_list; isset_right_paren; ] ) -> IssetExpression { isset_keyword; isset_left_paren; isset_argument_list; isset_right_paren; } | ( SyntaxKind.FunctionCallExpression, [ function_call_receiver; function_call_type_args; function_call_left_paren; function_call_argument_list; function_call_right_paren; ] ) -> FunctionCallExpression { function_call_receiver; function_call_type_args; function_call_left_paren; function_call_argument_list; function_call_right_paren; } | ( SyntaxKind.FunctionPointerExpression, [function_pointer_receiver; function_pointer_type_args] ) -> FunctionPointerExpression { function_pointer_receiver; function_pointer_type_args } | ( SyntaxKind.ParenthesizedExpression, [ parenthesized_expression_left_paren; parenthesized_expression_expression; parenthesized_expression_right_paren; ] ) -> ParenthesizedExpression { parenthesized_expression_left_paren; parenthesized_expression_expression; parenthesized_expression_right_paren; } | ( SyntaxKind.BracedExpression, [ braced_expression_left_brace; braced_expression_expression; braced_expression_right_brace; ] ) -> BracedExpression { braced_expression_left_brace; braced_expression_expression; braced_expression_right_brace; } | ( SyntaxKind.ETSpliceExpression, [ et_splice_expression_dollar; et_splice_expression_left_brace; et_splice_expression_expression; et_splice_expression_right_brace; ] ) -> ETSpliceExpression { et_splice_expression_dollar; et_splice_expression_left_brace; et_splice_expression_expression; et_splice_expression_right_brace; } | ( SyntaxKind.EmbeddedBracedExpression, [ embedded_braced_expression_left_brace; embedded_braced_expression_expression; embedded_braced_expression_right_brace; ] ) -> EmbeddedBracedExpression { embedded_braced_expression_left_brace; embedded_braced_expression_expression; embedded_braced_expression_right_brace; } | ( SyntaxKind.ListExpression, [list_keyword; list_left_paren; list_members; list_right_paren] ) -> ListExpression { list_keyword; list_left_paren; list_members; list_right_paren } | ( SyntaxKind.CollectionLiteralExpression, [ collection_literal_name; collection_literal_left_brace; collection_literal_initializers; collection_literal_right_brace; ] ) -> CollectionLiteralExpression { collection_literal_name; collection_literal_left_brace; collection_literal_initializers; collection_literal_right_brace; } | ( SyntaxKind.ObjectCreationExpression, [object_creation_new_keyword; object_creation_object] ) -> ObjectCreationExpression { object_creation_new_keyword; object_creation_object } | ( SyntaxKind.ConstructorCall, [ constructor_call_type; constructor_call_left_paren; constructor_call_argument_list; constructor_call_right_paren; ] ) -> ConstructorCall { constructor_call_type; constructor_call_left_paren; constructor_call_argument_list; constructor_call_right_paren; } | ( SyntaxKind.DarrayIntrinsicExpression, [ darray_intrinsic_keyword; darray_intrinsic_explicit_type; darray_intrinsic_left_bracket; darray_intrinsic_members; darray_intrinsic_right_bracket; ] ) -> DarrayIntrinsicExpression { darray_intrinsic_keyword; darray_intrinsic_explicit_type; darray_intrinsic_left_bracket; darray_intrinsic_members; darray_intrinsic_right_bracket; } | ( SyntaxKind.DictionaryIntrinsicExpression, [ dictionary_intrinsic_keyword; dictionary_intrinsic_explicit_type; dictionary_intrinsic_left_bracket; dictionary_intrinsic_members; dictionary_intrinsic_right_bracket; ] ) -> DictionaryIntrinsicExpression { dictionary_intrinsic_keyword; dictionary_intrinsic_explicit_type; dictionary_intrinsic_left_bracket; dictionary_intrinsic_members; dictionary_intrinsic_right_bracket; } | ( SyntaxKind.KeysetIntrinsicExpression, [ keyset_intrinsic_keyword; keyset_intrinsic_explicit_type; keyset_intrinsic_left_bracket; keyset_intrinsic_members; keyset_intrinsic_right_bracket; ] ) -> KeysetIntrinsicExpression { keyset_intrinsic_keyword; keyset_intrinsic_explicit_type; keyset_intrinsic_left_bracket; keyset_intrinsic_members; keyset_intrinsic_right_bracket; } | ( SyntaxKind.VarrayIntrinsicExpression, [ varray_intrinsic_keyword; varray_intrinsic_explicit_type; varray_intrinsic_left_bracket; varray_intrinsic_members; varray_intrinsic_right_bracket; ] ) -> VarrayIntrinsicExpression { varray_intrinsic_keyword; varray_intrinsic_explicit_type; varray_intrinsic_left_bracket; varray_intrinsic_members; varray_intrinsic_right_bracket; } | ( SyntaxKind.VectorIntrinsicExpression, [ vector_intrinsic_keyword; vector_intrinsic_explicit_type; vector_intrinsic_left_bracket; vector_intrinsic_members; vector_intrinsic_right_bracket; ] ) -> VectorIntrinsicExpression { vector_intrinsic_keyword; vector_intrinsic_explicit_type; vector_intrinsic_left_bracket; vector_intrinsic_members; vector_intrinsic_right_bracket; } | ( SyntaxKind.ElementInitializer, [element_key; element_arrow; element_value] ) -> ElementInitializer { element_key; element_arrow; element_value } | ( SyntaxKind.SubscriptExpression, [ subscript_receiver; subscript_left_bracket; subscript_index; subscript_right_bracket; ] ) -> SubscriptExpression { subscript_receiver; subscript_left_bracket; subscript_index; subscript_right_bracket; } | ( SyntaxKind.EmbeddedSubscriptExpression, [ embedded_subscript_receiver; embedded_subscript_left_bracket; embedded_subscript_index; embedded_subscript_right_bracket; ] ) -> EmbeddedSubscriptExpression { embedded_subscript_receiver; embedded_subscript_left_bracket; embedded_subscript_index; embedded_subscript_right_bracket; } | ( SyntaxKind.AwaitableCreationExpression, [ awaitable_attribute_spec; awaitable_async; awaitable_compound_statement; ] ) -> AwaitableCreationExpression { awaitable_attribute_spec; awaitable_async; awaitable_compound_statement; } | ( SyntaxKind.XHPChildrenDeclaration, [ xhp_children_keyword; xhp_children_expression; xhp_children_semicolon; ] ) -> XHPChildrenDeclaration { xhp_children_keyword; xhp_children_expression; xhp_children_semicolon; } | ( SyntaxKind.XHPChildrenParenthesizedList, [ xhp_children_list_left_paren; xhp_children_list_xhp_children; xhp_children_list_right_paren; ] ) -> XHPChildrenParenthesizedList { xhp_children_list_left_paren; xhp_children_list_xhp_children; xhp_children_list_right_paren; } | ( SyntaxKind.XHPCategoryDeclaration, [ xhp_category_keyword; xhp_category_categories; xhp_category_semicolon; ] ) -> XHPCategoryDeclaration { xhp_category_keyword; xhp_category_categories; xhp_category_semicolon; } | ( SyntaxKind.XHPEnumType, [ xhp_enum_like; xhp_enum_keyword; xhp_enum_left_brace; xhp_enum_values; xhp_enum_right_brace; ] ) -> XHPEnumType { xhp_enum_like; xhp_enum_keyword; xhp_enum_left_brace; xhp_enum_values; xhp_enum_right_brace; } | (SyntaxKind.XHPLateinit, [xhp_lateinit_at; xhp_lateinit_keyword]) -> XHPLateinit { xhp_lateinit_at; xhp_lateinit_keyword } | (SyntaxKind.XHPRequired, [xhp_required_at; xhp_required_keyword]) -> XHPRequired { xhp_required_at; xhp_required_keyword } | ( SyntaxKind.XHPClassAttributeDeclaration, [ xhp_attribute_keyword; xhp_attribute_attributes; xhp_attribute_semicolon; ] ) -> XHPClassAttributeDeclaration { xhp_attribute_keyword; xhp_attribute_attributes; xhp_attribute_semicolon; } | ( SyntaxKind.XHPClassAttribute, [ xhp_attribute_decl_type; xhp_attribute_decl_name; xhp_attribute_decl_initializer; xhp_attribute_decl_required; ] ) -> XHPClassAttribute { xhp_attribute_decl_type; xhp_attribute_decl_name; xhp_attribute_decl_initializer; xhp_attribute_decl_required; } | (SyntaxKind.XHPSimpleClassAttribute, [xhp_simple_class_attribute_type]) -> XHPSimpleClassAttribute { xhp_simple_class_attribute_type } | ( SyntaxKind.XHPSimpleAttribute, [ xhp_simple_attribute_name; xhp_simple_attribute_equal; xhp_simple_attribute_expression; ] ) -> XHPSimpleAttribute { xhp_simple_attribute_name; xhp_simple_attribute_equal; xhp_simple_attribute_expression; } | ( SyntaxKind.XHPSpreadAttribute, [ xhp_spread_attribute_left_brace; xhp_spread_attribute_spread_operator; xhp_spread_attribute_expression; xhp_spread_attribute_right_brace; ] ) -> XHPSpreadAttribute { xhp_spread_attribute_left_brace; xhp_spread_attribute_spread_operator; xhp_spread_attribute_expression; xhp_spread_attribute_right_brace; } | ( SyntaxKind.XHPOpen, [ xhp_open_left_angle; xhp_open_name; xhp_open_attributes; xhp_open_right_angle; ] ) -> XHPOpen { xhp_open_left_angle; xhp_open_name; xhp_open_attributes; xhp_open_right_angle; } | (SyntaxKind.XHPExpression, [xhp_open; xhp_body; xhp_close]) -> XHPExpression { xhp_open; xhp_body; xhp_close } | ( SyntaxKind.XHPClose, [xhp_close_left_angle; xhp_close_name; xhp_close_right_angle] ) -> XHPClose { xhp_close_left_angle; xhp_close_name; xhp_close_right_angle } | ( SyntaxKind.TypeConstant, [ type_constant_left_type; type_constant_separator; type_constant_right_type; ] ) -> TypeConstant { type_constant_left_type; type_constant_separator; type_constant_right_type; } | ( SyntaxKind.VectorTypeSpecifier, [ vector_type_keyword; vector_type_left_angle; vector_type_type; vector_type_trailing_comma; vector_type_right_angle; ] ) -> VectorTypeSpecifier { vector_type_keyword; vector_type_left_angle; vector_type_type; vector_type_trailing_comma; vector_type_right_angle; } | ( SyntaxKind.KeysetTypeSpecifier, [ keyset_type_keyword; keyset_type_left_angle; keyset_type_type; keyset_type_trailing_comma; keyset_type_right_angle; ] ) -> KeysetTypeSpecifier { keyset_type_keyword; keyset_type_left_angle; keyset_type_type; keyset_type_trailing_comma; keyset_type_right_angle; } | ( SyntaxKind.TupleTypeExplicitSpecifier, [ tuple_type_keyword; tuple_type_left_angle; tuple_type_types; tuple_type_right_angle; ] ) -> TupleTypeExplicitSpecifier { tuple_type_keyword; tuple_type_left_angle; tuple_type_types; tuple_type_right_angle; } | ( SyntaxKind.VarrayTypeSpecifier, [ varray_keyword; varray_left_angle; varray_type; varray_trailing_comma; varray_right_angle; ] ) -> VarrayTypeSpecifier { varray_keyword; varray_left_angle; varray_type; varray_trailing_comma; varray_right_angle; } | ( SyntaxKind.FunctionCtxTypeSpecifier, [function_ctx_type_keyword; function_ctx_type_variable] ) -> FunctionCtxTypeSpecifier { function_ctx_type_keyword; function_ctx_type_variable } | ( SyntaxKind.TypeParameter, [ type_attribute_spec; type_reified; type_variance; type_name; type_param_params; type_constraints; ] ) -> TypeParameter { type_attribute_spec; type_reified; type_variance; type_name; type_param_params; type_constraints; } | (SyntaxKind.TypeConstraint, [constraint_keyword; constraint_type]) -> TypeConstraint { constraint_keyword; constraint_type } | ( SyntaxKind.ContextConstraint, [ctx_constraint_keyword; ctx_constraint_ctx_list] ) -> ContextConstraint { ctx_constraint_keyword; ctx_constraint_ctx_list } | ( SyntaxKind.DarrayTypeSpecifier, [ darray_keyword; darray_left_angle; darray_key; darray_comma; darray_value; darray_trailing_comma; darray_right_angle; ] ) -> DarrayTypeSpecifier { darray_keyword; darray_left_angle; darray_key; darray_comma; darray_value; darray_trailing_comma; darray_right_angle; } | ( SyntaxKind.DictionaryTypeSpecifier, [ dictionary_type_keyword; dictionary_type_left_angle; dictionary_type_members; dictionary_type_right_angle; ] ) -> DictionaryTypeSpecifier { dictionary_type_keyword; dictionary_type_left_angle; dictionary_type_members; dictionary_type_right_angle; } | ( SyntaxKind.ClosureTypeSpecifier, [ closure_outer_left_paren; closure_readonly_keyword; closure_function_keyword; closure_inner_left_paren; closure_parameter_list; closure_inner_right_paren; closure_contexts; closure_colon; closure_readonly_return; closure_return_type; closure_outer_right_paren; ] ) -> ClosureTypeSpecifier { closure_outer_left_paren; closure_readonly_keyword; closure_function_keyword; closure_inner_left_paren; closure_parameter_list; closure_inner_right_paren; closure_contexts; closure_colon; closure_readonly_return; closure_return_type; closure_outer_right_paren; } | ( SyntaxKind.ClosureParameterTypeSpecifier, [ closure_parameter_call_convention; closure_parameter_readonly; closure_parameter_type; ] ) -> ClosureParameterTypeSpecifier { closure_parameter_call_convention; closure_parameter_readonly; closure_parameter_type; } | ( SyntaxKind.TypeRefinement, [ type_refinement_type; type_refinement_keyword; type_refinement_left_brace; type_refinement_members; type_refinement_right_brace; ] ) -> TypeRefinement { type_refinement_type; type_refinement_keyword; type_refinement_left_brace; type_refinement_members; type_refinement_right_brace; } | ( SyntaxKind.TypeInRefinement, [ type_in_refinement_keyword; type_in_refinement_name; type_in_refinement_type_parameters; type_in_refinement_constraints; type_in_refinement_equal; type_in_refinement_type; ] ) -> TypeInRefinement { type_in_refinement_keyword; type_in_refinement_name; type_in_refinement_type_parameters; type_in_refinement_constraints; type_in_refinement_equal; type_in_refinement_type; } | ( SyntaxKind.CtxInRefinement, [ ctx_in_refinement_keyword; ctx_in_refinement_name; ctx_in_refinement_type_parameters; ctx_in_refinement_constraints; ctx_in_refinement_equal; ctx_in_refinement_ctx_list; ] ) -> CtxInRefinement { ctx_in_refinement_keyword; ctx_in_refinement_name; ctx_in_refinement_type_parameters; ctx_in_refinement_constraints; ctx_in_refinement_equal; ctx_in_refinement_ctx_list; } | ( SyntaxKind.ClassnameTypeSpecifier, [ classname_keyword; classname_left_angle; classname_type; classname_trailing_comma; classname_right_angle; ] ) -> ClassnameTypeSpecifier { classname_keyword; classname_left_angle; classname_type; classname_trailing_comma; classname_right_angle; } | ( SyntaxKind.FieldSpecifier, [field_question; field_name; field_arrow; field_type] ) -> FieldSpecifier { field_question; field_name; field_arrow; field_type } | ( SyntaxKind.FieldInitializer, [ field_initializer_name; field_initializer_arrow; field_initializer_value; ] ) -> FieldInitializer { field_initializer_name; field_initializer_arrow; field_initializer_value; } | ( SyntaxKind.ShapeTypeSpecifier, [ shape_type_keyword; shape_type_left_paren; shape_type_fields; shape_type_ellipsis; shape_type_right_paren; ] ) -> ShapeTypeSpecifier { shape_type_keyword; shape_type_left_paren; shape_type_fields; shape_type_ellipsis; shape_type_right_paren; } | ( SyntaxKind.ShapeExpression, [ shape_expression_keyword; shape_expression_left_paren; shape_expression_fields; shape_expression_right_paren; ] ) -> ShapeExpression { shape_expression_keyword; shape_expression_left_paren; shape_expression_fields; shape_expression_right_paren; } | ( SyntaxKind.TupleExpression, [ tuple_expression_keyword; tuple_expression_left_paren; tuple_expression_items; tuple_expression_right_paren; ] ) -> TupleExpression { tuple_expression_keyword; tuple_expression_left_paren; tuple_expression_items; tuple_expression_right_paren; } | ( SyntaxKind.GenericTypeSpecifier, [generic_class_type; generic_argument_list] ) -> GenericTypeSpecifier { generic_class_type; generic_argument_list } | (SyntaxKind.NullableTypeSpecifier, [nullable_question; nullable_type]) -> NullableTypeSpecifier { nullable_question; nullable_type } | (SyntaxKind.LikeTypeSpecifier, [like_tilde; like_type]) -> LikeTypeSpecifier { like_tilde; like_type } | (SyntaxKind.SoftTypeSpecifier, [soft_at; soft_type]) -> SoftTypeSpecifier { soft_at; soft_type } | ( SyntaxKind.AttributizedSpecifier, [attributized_specifier_attribute_spec; attributized_specifier_type] ) -> AttributizedSpecifier { attributized_specifier_attribute_spec; attributized_specifier_type } | ( SyntaxKind.ReifiedTypeArgument, [reified_type_argument_reified; reified_type_argument_type] ) -> ReifiedTypeArgument { reified_type_argument_reified; reified_type_argument_type } | ( SyntaxKind.TypeArguments, [ type_arguments_left_angle; type_arguments_types; type_arguments_right_angle; ] ) -> TypeArguments { type_arguments_left_angle; type_arguments_types; type_arguments_right_angle; } | ( SyntaxKind.TypeParameters, [ type_parameters_left_angle; type_parameters_parameters; type_parameters_right_angle; ] ) -> TypeParameters { type_parameters_left_angle; type_parameters_parameters; type_parameters_right_angle; } | ( SyntaxKind.TupleTypeSpecifier, [tuple_left_paren; tuple_types; tuple_right_paren] ) -> TupleTypeSpecifier { tuple_left_paren; tuple_types; tuple_right_paren } | ( SyntaxKind.UnionTypeSpecifier, [union_left_paren; union_types; union_right_paren] ) -> UnionTypeSpecifier { union_left_paren; union_types; union_right_paren } | ( SyntaxKind.IntersectionTypeSpecifier, [ intersection_left_paren; intersection_types; intersection_right_paren; ] ) -> IntersectionTypeSpecifier { intersection_left_paren; intersection_types; intersection_right_paren; } | (SyntaxKind.ErrorSyntax, [error_error]) -> ErrorSyntax { error_error } | (SyntaxKind.ListItem, [list_item; list_separator]) -> ListItem { list_item; list_separator } | ( SyntaxKind.EnumClassLabelExpression, [ enum_class_label_qualifier; enum_class_label_hash; enum_class_label_expression; ] ) -> EnumClassLabelExpression { enum_class_label_qualifier; enum_class_label_hash; enum_class_label_expression; } | ( SyntaxKind.ModuleDeclaration, [ module_declaration_attribute_spec; module_declaration_new_keyword; module_declaration_module_keyword; module_declaration_name; module_declaration_left_brace; module_declaration_exports; module_declaration_imports; module_declaration_right_brace; ] ) -> ModuleDeclaration { module_declaration_attribute_spec; module_declaration_new_keyword; module_declaration_module_keyword; module_declaration_name; module_declaration_left_brace; module_declaration_exports; module_declaration_imports; module_declaration_right_brace; } | ( SyntaxKind.ModuleExports, [ module_exports_exports_keyword; module_exports_left_brace; module_exports_exports; module_exports_right_brace; ] ) -> ModuleExports { module_exports_exports_keyword; module_exports_left_brace; module_exports_exports; module_exports_right_brace; } | ( SyntaxKind.ModuleImports, [ module_imports_imports_keyword; module_imports_left_brace; module_imports_imports; module_imports_right_brace; ] ) -> ModuleImports { module_imports_imports_keyword; module_imports_left_brace; module_imports_imports; module_imports_right_brace; } | ( SyntaxKind.ModuleMembershipDeclaration, [ module_membership_declaration_module_keyword; module_membership_declaration_name; module_membership_declaration_semicolon; ] ) -> ModuleMembershipDeclaration { module_membership_declaration_module_keyword; module_membership_declaration_name; module_membership_declaration_semicolon; } | ( SyntaxKind.PackageExpression, [package_expression_keyword; package_expression_name] ) -> PackageExpression { package_expression_keyword; package_expression_name } | (SyntaxKind.Missing, []) -> Missing | (SyntaxKind.SyntaxList, items) -> SyntaxList items | _ -> failwith "syntax_from_children called with wrong number of children" let all_tokens node = let rec aux acc nodes = match nodes with | [] -> acc | h :: t -> begin match syntax h with | Token token -> aux (token :: acc) t | _ -> aux (aux acc (children h)) t end in List.rev (aux [] [node]) module type ValueBuilderType = sig val value_from_children : Full_fidelity_source_text.t -> int -> (* offset *) Full_fidelity_syntax_kind.t -> t list -> SyntaxValue.t val value_from_token : Token.t -> SyntaxValue.t val value_from_syntax : syntax -> SyntaxValue.t end module WithValueBuilder (ValueBuilder : ValueBuilderType) = struct let from_children text offset kind ts = let syntax = syntax_from_children kind ts in let value = ValueBuilder.value_from_children text offset kind ts in make syntax value let make_token token = let syntax = Token token in let value = ValueBuilder.value_from_token token in make syntax value let make_missing text offset = from_children text offset SyntaxKind.Missing [] (* An empty list is represented by Missing; everything else is a SyntaxList, even if the list has only one item. *) let make_list text offset items = match items with | [] -> make_missing text offset | _ -> from_children text offset SyntaxKind.SyntaxList items let make_end_of_file end_of_file_token = let syntax = EndOfFile { end_of_file_token } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_script script_declarations = let syntax = Script { script_declarations } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_qualified_name qualified_name_parts = let syntax = QualifiedName { qualified_name_parts } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_module_name module_name_parts = let syntax = ModuleName { module_name_parts } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_simple_type_specifier simple_type_specifier = let syntax = SimpleTypeSpecifier { simple_type_specifier } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_literal_expression literal_expression = let syntax = LiteralExpression { literal_expression } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_prefixed_string_expression prefixed_string_name prefixed_string_str = let syntax = PrefixedStringExpression { prefixed_string_name; prefixed_string_str } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_prefixed_code_expression prefixed_code_prefix prefixed_code_left_backtick prefixed_code_body prefixed_code_right_backtick = let syntax = PrefixedCodeExpression { prefixed_code_prefix; prefixed_code_left_backtick; prefixed_code_body; prefixed_code_right_backtick; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_variable_expression variable_expression = let syntax = VariableExpression { variable_expression } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_pipe_variable_expression pipe_variable_expression = let syntax = PipeVariableExpression { pipe_variable_expression } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_file_attribute_specification file_attribute_specification_left_double_angle file_attribute_specification_keyword file_attribute_specification_colon file_attribute_specification_attributes file_attribute_specification_right_double_angle = let syntax = FileAttributeSpecification { file_attribute_specification_left_double_angle; file_attribute_specification_keyword; file_attribute_specification_colon; file_attribute_specification_attributes; file_attribute_specification_right_double_angle; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_enum_declaration enum_attribute_spec enum_modifiers enum_keyword enum_name enum_colon enum_base enum_type enum_left_brace enum_use_clauses enum_enumerators enum_right_brace = let syntax = EnumDeclaration { enum_attribute_spec; enum_modifiers; enum_keyword; enum_name; enum_colon; enum_base; enum_type; enum_left_brace; enum_use_clauses; enum_enumerators; enum_right_brace; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_enum_use enum_use_keyword enum_use_names enum_use_semicolon = let syntax = EnumUse { enum_use_keyword; enum_use_names; enum_use_semicolon } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_enumerator enumerator_name enumerator_equal enumerator_value enumerator_semicolon = let syntax = Enumerator { enumerator_name; enumerator_equal; enumerator_value; enumerator_semicolon; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_enum_class_declaration enum_class_attribute_spec enum_class_modifiers enum_class_enum_keyword enum_class_class_keyword enum_class_name enum_class_colon enum_class_base enum_class_extends enum_class_extends_list enum_class_left_brace enum_class_elements enum_class_right_brace = let syntax = EnumClassDeclaration { enum_class_attribute_spec; enum_class_modifiers; enum_class_enum_keyword; enum_class_class_keyword; enum_class_name; enum_class_colon; enum_class_base; enum_class_extends; enum_class_extends_list; enum_class_left_brace; enum_class_elements; enum_class_right_brace; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_enum_class_enumerator enum_class_enumerator_modifiers enum_class_enumerator_type enum_class_enumerator_name enum_class_enumerator_initializer enum_class_enumerator_semicolon = let syntax = EnumClassEnumerator { enum_class_enumerator_modifiers; enum_class_enumerator_type; enum_class_enumerator_name; enum_class_enumerator_initializer; enum_class_enumerator_semicolon; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_alias_declaration alias_attribute_spec alias_modifiers alias_module_kw_opt alias_keyword alias_name alias_generic_parameter alias_constraint alias_equal alias_type alias_semicolon = let syntax = AliasDeclaration { alias_attribute_spec; alias_modifiers; alias_module_kw_opt; alias_keyword; alias_name; alias_generic_parameter; alias_constraint; alias_equal; alias_type; alias_semicolon; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_context_alias_declaration ctx_alias_attribute_spec ctx_alias_keyword ctx_alias_name ctx_alias_generic_parameter ctx_alias_as_constraint ctx_alias_equal ctx_alias_context ctx_alias_semicolon = let syntax = ContextAliasDeclaration { ctx_alias_attribute_spec; ctx_alias_keyword; ctx_alias_name; ctx_alias_generic_parameter; ctx_alias_as_constraint; ctx_alias_equal; ctx_alias_context; ctx_alias_semicolon; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_case_type_declaration case_type_attribute_spec case_type_modifiers case_type_case_keyword case_type_type_keyword case_type_name case_type_generic_parameter case_type_as case_type_bounds case_type_equal case_type_variants case_type_semicolon = let syntax = CaseTypeDeclaration { case_type_attribute_spec; case_type_modifiers; case_type_case_keyword; case_type_type_keyword; case_type_name; case_type_generic_parameter; case_type_as; case_type_bounds; case_type_equal; case_type_variants; case_type_semicolon; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_case_type_variant case_type_variant_bar case_type_variant_type = let syntax = CaseTypeVariant { case_type_variant_bar; case_type_variant_type } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_property_declaration property_attribute_spec property_modifiers property_type property_declarators property_semicolon = let syntax = PropertyDeclaration { property_attribute_spec; property_modifiers; property_type; property_declarators; property_semicolon; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_property_declarator property_name property_initializer = let syntax = PropertyDeclarator { property_name; property_initializer } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_namespace_declaration namespace_header namespace_body = let syntax = NamespaceDeclaration { namespace_header; namespace_body } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_namespace_declaration_header namespace_keyword namespace_name = let syntax = NamespaceDeclarationHeader { namespace_keyword; namespace_name } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_namespace_body namespace_left_brace namespace_declarations namespace_right_brace = let syntax = NamespaceBody { namespace_left_brace; namespace_declarations; namespace_right_brace; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_namespace_empty_body namespace_semicolon = let syntax = NamespaceEmptyBody { namespace_semicolon } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_namespace_use_declaration namespace_use_keyword namespace_use_kind namespace_use_clauses namespace_use_semicolon = let syntax = NamespaceUseDeclaration { namespace_use_keyword; namespace_use_kind; namespace_use_clauses; namespace_use_semicolon; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_namespace_group_use_declaration namespace_group_use_keyword namespace_group_use_kind namespace_group_use_prefix namespace_group_use_left_brace namespace_group_use_clauses namespace_group_use_right_brace namespace_group_use_semicolon = let syntax = NamespaceGroupUseDeclaration { namespace_group_use_keyword; namespace_group_use_kind; namespace_group_use_prefix; namespace_group_use_left_brace; namespace_group_use_clauses; namespace_group_use_right_brace; namespace_group_use_semicolon; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_namespace_use_clause namespace_use_clause_kind namespace_use_name namespace_use_as namespace_use_alias = let syntax = NamespaceUseClause { namespace_use_clause_kind; namespace_use_name; namespace_use_as; namespace_use_alias; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_function_declaration function_attribute_spec function_declaration_header function_body = let syntax = FunctionDeclaration { function_attribute_spec; function_declaration_header; function_body; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_function_declaration_header function_modifiers function_keyword function_name function_type_parameter_list function_left_paren function_parameter_list function_right_paren function_contexts function_colon function_readonly_return function_type function_where_clause = let syntax = FunctionDeclarationHeader { function_modifiers; function_keyword; function_name; function_type_parameter_list; function_left_paren; function_parameter_list; function_right_paren; function_contexts; function_colon; function_readonly_return; function_type; function_where_clause; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_contexts contexts_left_bracket contexts_types contexts_right_bracket = let syntax = Contexts { contexts_left_bracket; contexts_types; contexts_right_bracket } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_where_clause where_clause_keyword where_clause_constraints = let syntax = WhereClause { where_clause_keyword; where_clause_constraints } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_where_constraint where_constraint_left_type where_constraint_operator where_constraint_right_type = let syntax = WhereConstraint { where_constraint_left_type; where_constraint_operator; where_constraint_right_type; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_methodish_declaration methodish_attribute methodish_function_decl_header methodish_function_body methodish_semicolon = let syntax = MethodishDeclaration { methodish_attribute; methodish_function_decl_header; methodish_function_body; methodish_semicolon; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_methodish_trait_resolution methodish_trait_attribute methodish_trait_function_decl_header methodish_trait_equal methodish_trait_name methodish_trait_semicolon = let syntax = MethodishTraitResolution { methodish_trait_attribute; methodish_trait_function_decl_header; methodish_trait_equal; methodish_trait_name; methodish_trait_semicolon; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_classish_declaration classish_attribute classish_modifiers classish_xhp classish_keyword classish_name classish_type_parameters classish_extends_keyword classish_extends_list classish_implements_keyword classish_implements_list classish_where_clause classish_body = let syntax = ClassishDeclaration { classish_attribute; classish_modifiers; classish_xhp; classish_keyword; classish_name; classish_type_parameters; classish_extends_keyword; classish_extends_list; classish_implements_keyword; classish_implements_list; classish_where_clause; classish_body; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_classish_body classish_body_left_brace classish_body_elements classish_body_right_brace = let syntax = ClassishBody { classish_body_left_brace; classish_body_elements; classish_body_right_brace; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_trait_use trait_use_keyword trait_use_names trait_use_semicolon = let syntax = TraitUse { trait_use_keyword; trait_use_names; trait_use_semicolon } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_require_clause require_keyword require_kind require_name require_semicolon = let syntax = RequireClause { require_keyword; require_kind; require_name; require_semicolon } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_const_declaration const_attribute_spec const_modifiers const_keyword const_type_specifier const_declarators const_semicolon = let syntax = ConstDeclaration { const_attribute_spec; const_modifiers; const_keyword; const_type_specifier; const_declarators; const_semicolon; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_constant_declarator constant_declarator_name constant_declarator_initializer = let syntax = ConstantDeclarator { constant_declarator_name; constant_declarator_initializer } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_type_const_declaration type_const_attribute_spec type_const_modifiers type_const_keyword type_const_type_keyword type_const_name type_const_type_parameters type_const_type_constraints type_const_equal type_const_type_specifier type_const_semicolon = let syntax = TypeConstDeclaration { type_const_attribute_spec; type_const_modifiers; type_const_keyword; type_const_type_keyword; type_const_name; type_const_type_parameters; type_const_type_constraints; type_const_equal; type_const_type_specifier; type_const_semicolon; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_context_const_declaration context_const_modifiers context_const_const_keyword context_const_ctx_keyword context_const_name context_const_type_parameters context_const_constraint context_const_equal context_const_ctx_list context_const_semicolon = let syntax = ContextConstDeclaration { context_const_modifiers; context_const_const_keyword; context_const_ctx_keyword; context_const_name; context_const_type_parameters; context_const_constraint; context_const_equal; context_const_ctx_list; context_const_semicolon; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_decorated_expression decorated_expression_decorator decorated_expression_expression = let syntax = DecoratedExpression { decorated_expression_decorator; decorated_expression_expression } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_parameter_declaration parameter_attribute parameter_visibility parameter_call_convention parameter_readonly parameter_type parameter_name parameter_default_value = let syntax = ParameterDeclaration { parameter_attribute; parameter_visibility; parameter_call_convention; parameter_readonly; parameter_type; parameter_name; parameter_default_value; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_variadic_parameter variadic_parameter_call_convention variadic_parameter_type variadic_parameter_ellipsis = let syntax = VariadicParameter { variadic_parameter_call_convention; variadic_parameter_type; variadic_parameter_ellipsis; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_old_attribute_specification old_attribute_specification_left_double_angle old_attribute_specification_attributes old_attribute_specification_right_double_angle = let syntax = OldAttributeSpecification { old_attribute_specification_left_double_angle; old_attribute_specification_attributes; old_attribute_specification_right_double_angle; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_attribute_specification attribute_specification_attributes = let syntax = AttributeSpecification { attribute_specification_attributes } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_attribute attribute_at attribute_attribute_name = let syntax = Attribute { attribute_at; attribute_attribute_name } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_inclusion_expression inclusion_require inclusion_filename = let syntax = InclusionExpression { inclusion_require; inclusion_filename } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_inclusion_directive inclusion_expression inclusion_semicolon = let syntax = InclusionDirective { inclusion_expression; inclusion_semicolon } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_compound_statement compound_left_brace compound_statements compound_right_brace = let syntax = CompoundStatement { compound_left_brace; compound_statements; compound_right_brace } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_expression_statement expression_statement_expression expression_statement_semicolon = let syntax = ExpressionStatement { expression_statement_expression; expression_statement_semicolon } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_markup_section markup_hashbang markup_suffix = let syntax = MarkupSection { markup_hashbang; markup_suffix } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_markup_suffix markup_suffix_less_than_question markup_suffix_name = let syntax = MarkupSuffix { markup_suffix_less_than_question; markup_suffix_name } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_unset_statement unset_keyword unset_left_paren unset_variables unset_right_paren unset_semicolon = let syntax = UnsetStatement { unset_keyword; unset_left_paren; unset_variables; unset_right_paren; unset_semicolon; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_declare_local_statement declare_local_keyword declare_local_variable declare_local_colon declare_local_type declare_local_initializer declare_local_semicolon = let syntax = DeclareLocalStatement { declare_local_keyword; declare_local_variable; declare_local_colon; declare_local_type; declare_local_initializer; declare_local_semicolon; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_using_statement_block_scoped using_block_await_keyword using_block_using_keyword using_block_left_paren using_block_expressions using_block_right_paren using_block_body = let syntax = UsingStatementBlockScoped { using_block_await_keyword; using_block_using_keyword; using_block_left_paren; using_block_expressions; using_block_right_paren; using_block_body; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_using_statement_function_scoped using_function_await_keyword using_function_using_keyword using_function_expression using_function_semicolon = let syntax = UsingStatementFunctionScoped { using_function_await_keyword; using_function_using_keyword; using_function_expression; using_function_semicolon; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_while_statement while_keyword while_left_paren while_condition while_right_paren while_body = let syntax = WhileStatement { while_keyword; while_left_paren; while_condition; while_right_paren; while_body; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_if_statement if_keyword if_left_paren if_condition if_right_paren if_statement if_else_clause = let syntax = IfStatement { if_keyword; if_left_paren; if_condition; if_right_paren; if_statement; if_else_clause; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_else_clause else_keyword else_statement = let syntax = ElseClause { else_keyword; else_statement } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_try_statement try_keyword try_compound_statement try_catch_clauses try_finally_clause = let syntax = TryStatement { try_keyword; try_compound_statement; try_catch_clauses; try_finally_clause; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_catch_clause catch_keyword catch_left_paren catch_type catch_variable catch_right_paren catch_body = let syntax = CatchClause { catch_keyword; catch_left_paren; catch_type; catch_variable; catch_right_paren; catch_body; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_finally_clause finally_keyword finally_body = let syntax = FinallyClause { finally_keyword; finally_body } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_do_statement do_keyword do_body do_while_keyword do_left_paren do_condition do_right_paren do_semicolon = let syntax = DoStatement { do_keyword; do_body; do_while_keyword; do_left_paren; do_condition; do_right_paren; do_semicolon; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_for_statement for_keyword for_left_paren for_initializer for_first_semicolon for_control for_second_semicolon for_end_of_loop for_right_paren for_body = let syntax = ForStatement { for_keyword; for_left_paren; for_initializer; for_first_semicolon; for_control; for_second_semicolon; for_end_of_loop; for_right_paren; for_body; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_foreach_statement foreach_keyword foreach_left_paren foreach_collection foreach_await_keyword foreach_as foreach_key foreach_arrow foreach_value foreach_right_paren foreach_body = let syntax = ForeachStatement { foreach_keyword; foreach_left_paren; foreach_collection; foreach_await_keyword; foreach_as; foreach_key; foreach_arrow; foreach_value; foreach_right_paren; foreach_body; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_switch_statement switch_keyword switch_left_paren switch_expression switch_right_paren switch_left_brace switch_sections switch_right_brace = let syntax = SwitchStatement { switch_keyword; switch_left_paren; switch_expression; switch_right_paren; switch_left_brace; switch_sections; switch_right_brace; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_switch_section switch_section_labels switch_section_statements switch_section_fallthrough = let syntax = SwitchSection { switch_section_labels; switch_section_statements; switch_section_fallthrough; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_switch_fallthrough fallthrough_keyword fallthrough_semicolon = let syntax = SwitchFallthrough { fallthrough_keyword; fallthrough_semicolon } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_case_label case_keyword case_expression case_colon = let syntax = CaseLabel { case_keyword; case_expression; case_colon } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_default_label default_keyword default_colon = let syntax = DefaultLabel { default_keyword; default_colon } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_match_statement match_statement_keyword match_statement_left_paren match_statement_expression match_statement_right_paren match_statement_left_brace match_statement_arms match_statement_right_brace = let syntax = MatchStatement { match_statement_keyword; match_statement_left_paren; match_statement_expression; match_statement_right_paren; match_statement_left_brace; match_statement_arms; match_statement_right_brace; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_match_statement_arm match_statement_arm_pattern match_statement_arm_arrow match_statement_arm_body = let syntax = MatchStatementArm { match_statement_arm_pattern; match_statement_arm_arrow; match_statement_arm_body; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_return_statement return_keyword return_expression return_semicolon = let syntax = ReturnStatement { return_keyword; return_expression; return_semicolon } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_yield_break_statement yield_break_keyword yield_break_break yield_break_semicolon = let syntax = YieldBreakStatement { yield_break_keyword; yield_break_break; yield_break_semicolon } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_throw_statement throw_keyword throw_expression throw_semicolon = let syntax = ThrowStatement { throw_keyword; throw_expression; throw_semicolon } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_break_statement break_keyword break_semicolon = let syntax = BreakStatement { break_keyword; break_semicolon } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_continue_statement continue_keyword continue_semicolon = let syntax = ContinueStatement { continue_keyword; continue_semicolon } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_echo_statement echo_keyword echo_expressions echo_semicolon = let syntax = EchoStatement { echo_keyword; echo_expressions; echo_semicolon } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_concurrent_statement concurrent_keyword concurrent_statement = let syntax = ConcurrentStatement { concurrent_keyword; concurrent_statement } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_simple_initializer simple_initializer_equal simple_initializer_value = let syntax = SimpleInitializer { simple_initializer_equal; simple_initializer_value } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_anonymous_class anonymous_class_class_keyword anonymous_class_left_paren anonymous_class_argument_list anonymous_class_right_paren anonymous_class_extends_keyword anonymous_class_extends_list anonymous_class_implements_keyword anonymous_class_implements_list anonymous_class_body = let syntax = AnonymousClass { anonymous_class_class_keyword; anonymous_class_left_paren; anonymous_class_argument_list; anonymous_class_right_paren; anonymous_class_extends_keyword; anonymous_class_extends_list; anonymous_class_implements_keyword; anonymous_class_implements_list; anonymous_class_body; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_anonymous_function anonymous_attribute_spec anonymous_async_keyword anonymous_function_keyword anonymous_left_paren anonymous_parameters anonymous_right_paren anonymous_ctx_list anonymous_colon anonymous_readonly_return anonymous_type anonymous_use anonymous_body = let syntax = AnonymousFunction { anonymous_attribute_spec; anonymous_async_keyword; anonymous_function_keyword; anonymous_left_paren; anonymous_parameters; anonymous_right_paren; anonymous_ctx_list; anonymous_colon; anonymous_readonly_return; anonymous_type; anonymous_use; anonymous_body; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_anonymous_function_use_clause anonymous_use_keyword anonymous_use_left_paren anonymous_use_variables anonymous_use_right_paren = let syntax = AnonymousFunctionUseClause { anonymous_use_keyword; anonymous_use_left_paren; anonymous_use_variables; anonymous_use_right_paren; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_variable_pattern variable_pattern_variable = let syntax = VariablePattern { variable_pattern_variable } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_constructor_pattern constructor_pattern_constructor constructor_pattern_left_paren constructor_pattern_members constructor_pattern_right_paren = let syntax = ConstructorPattern { constructor_pattern_constructor; constructor_pattern_left_paren; constructor_pattern_members; constructor_pattern_right_paren; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_refinement_pattern refinement_pattern_variable refinement_pattern_colon refinement_pattern_specifier = let syntax = RefinementPattern { refinement_pattern_variable; refinement_pattern_colon; refinement_pattern_specifier; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_lambda_expression lambda_attribute_spec lambda_async lambda_signature lambda_arrow lambda_body = let syntax = LambdaExpression { lambda_attribute_spec; lambda_async; lambda_signature; lambda_arrow; lambda_body; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_lambda_signature lambda_left_paren lambda_parameters lambda_right_paren lambda_contexts lambda_colon lambda_readonly_return lambda_type = let syntax = LambdaSignature { lambda_left_paren; lambda_parameters; lambda_right_paren; lambda_contexts; lambda_colon; lambda_readonly_return; lambda_type; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_cast_expression cast_left_paren cast_type cast_right_paren cast_operand = let syntax = CastExpression { cast_left_paren; cast_type; cast_right_paren; cast_operand } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_scope_resolution_expression scope_resolution_qualifier scope_resolution_operator scope_resolution_name = let syntax = ScopeResolutionExpression { scope_resolution_qualifier; scope_resolution_operator; scope_resolution_name; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_member_selection_expression member_object member_operator member_name = let syntax = MemberSelectionExpression { member_object; member_operator; member_name } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_safe_member_selection_expression safe_member_object safe_member_operator safe_member_name = let syntax = SafeMemberSelectionExpression { safe_member_object; safe_member_operator; safe_member_name } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_embedded_member_selection_expression embedded_member_object embedded_member_operator embedded_member_name = let syntax = EmbeddedMemberSelectionExpression { embedded_member_object; embedded_member_operator; embedded_member_name; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_yield_expression yield_keyword yield_operand = let syntax = YieldExpression { yield_keyword; yield_operand } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_prefix_unary_expression prefix_unary_operator prefix_unary_operand = let syntax = PrefixUnaryExpression { prefix_unary_operator; prefix_unary_operand } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_postfix_unary_expression postfix_unary_operand postfix_unary_operator = let syntax = PostfixUnaryExpression { postfix_unary_operand; postfix_unary_operator } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_binary_expression binary_left_operand binary_operator binary_right_operand = let syntax = BinaryExpression { binary_left_operand; binary_operator; binary_right_operand } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_is_expression is_left_operand is_operator is_right_operand = let syntax = IsExpression { is_left_operand; is_operator; is_right_operand } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_as_expression as_left_operand as_operator as_right_operand = let syntax = AsExpression { as_left_operand; as_operator; as_right_operand } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_nullable_as_expression nullable_as_left_operand nullable_as_operator nullable_as_right_operand = let syntax = NullableAsExpression { nullable_as_left_operand; nullable_as_operator; nullable_as_right_operand; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_upcast_expression upcast_left_operand upcast_operator upcast_right_operand = let syntax = UpcastExpression { upcast_left_operand; upcast_operator; upcast_right_operand } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_conditional_expression conditional_test conditional_question conditional_consequence conditional_colon conditional_alternative = let syntax = ConditionalExpression { conditional_test; conditional_question; conditional_consequence; conditional_colon; conditional_alternative; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_eval_expression eval_keyword eval_left_paren eval_argument eval_right_paren = let syntax = EvalExpression { eval_keyword; eval_left_paren; eval_argument; eval_right_paren } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_isset_expression isset_keyword isset_left_paren isset_argument_list isset_right_paren = let syntax = IssetExpression { isset_keyword; isset_left_paren; isset_argument_list; isset_right_paren; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_function_call_expression function_call_receiver function_call_type_args function_call_left_paren function_call_argument_list function_call_right_paren = let syntax = FunctionCallExpression { function_call_receiver; function_call_type_args; function_call_left_paren; function_call_argument_list; function_call_right_paren; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_function_pointer_expression function_pointer_receiver function_pointer_type_args = let syntax = FunctionPointerExpression { function_pointer_receiver; function_pointer_type_args } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_parenthesized_expression parenthesized_expression_left_paren parenthesized_expression_expression parenthesized_expression_right_paren = let syntax = ParenthesizedExpression { parenthesized_expression_left_paren; parenthesized_expression_expression; parenthesized_expression_right_paren; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_braced_expression braced_expression_left_brace braced_expression_expression braced_expression_right_brace = let syntax = BracedExpression { braced_expression_left_brace; braced_expression_expression; braced_expression_right_brace; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_et_splice_expression et_splice_expression_dollar et_splice_expression_left_brace et_splice_expression_expression et_splice_expression_right_brace = let syntax = ETSpliceExpression { et_splice_expression_dollar; et_splice_expression_left_brace; et_splice_expression_expression; et_splice_expression_right_brace; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_embedded_braced_expression embedded_braced_expression_left_brace embedded_braced_expression_expression embedded_braced_expression_right_brace = let syntax = EmbeddedBracedExpression { embedded_braced_expression_left_brace; embedded_braced_expression_expression; embedded_braced_expression_right_brace; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_list_expression list_keyword list_left_paren list_members list_right_paren = let syntax = ListExpression { list_keyword; list_left_paren; list_members; list_right_paren } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_collection_literal_expression collection_literal_name collection_literal_left_brace collection_literal_initializers collection_literal_right_brace = let syntax = CollectionLiteralExpression { collection_literal_name; collection_literal_left_brace; collection_literal_initializers; collection_literal_right_brace; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_object_creation_expression object_creation_new_keyword object_creation_object = let syntax = ObjectCreationExpression { object_creation_new_keyword; object_creation_object } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_constructor_call constructor_call_type constructor_call_left_paren constructor_call_argument_list constructor_call_right_paren = let syntax = ConstructorCall { constructor_call_type; constructor_call_left_paren; constructor_call_argument_list; constructor_call_right_paren; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_darray_intrinsic_expression darray_intrinsic_keyword darray_intrinsic_explicit_type darray_intrinsic_left_bracket darray_intrinsic_members darray_intrinsic_right_bracket = let syntax = DarrayIntrinsicExpression { darray_intrinsic_keyword; darray_intrinsic_explicit_type; darray_intrinsic_left_bracket; darray_intrinsic_members; darray_intrinsic_right_bracket; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_dictionary_intrinsic_expression dictionary_intrinsic_keyword dictionary_intrinsic_explicit_type dictionary_intrinsic_left_bracket dictionary_intrinsic_members dictionary_intrinsic_right_bracket = let syntax = DictionaryIntrinsicExpression { dictionary_intrinsic_keyword; dictionary_intrinsic_explicit_type; dictionary_intrinsic_left_bracket; dictionary_intrinsic_members; dictionary_intrinsic_right_bracket; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_keyset_intrinsic_expression keyset_intrinsic_keyword keyset_intrinsic_explicit_type keyset_intrinsic_left_bracket keyset_intrinsic_members keyset_intrinsic_right_bracket = let syntax = KeysetIntrinsicExpression { keyset_intrinsic_keyword; keyset_intrinsic_explicit_type; keyset_intrinsic_left_bracket; keyset_intrinsic_members; keyset_intrinsic_right_bracket; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_varray_intrinsic_expression varray_intrinsic_keyword varray_intrinsic_explicit_type varray_intrinsic_left_bracket varray_intrinsic_members varray_intrinsic_right_bracket = let syntax = VarrayIntrinsicExpression { varray_intrinsic_keyword; varray_intrinsic_explicit_type; varray_intrinsic_left_bracket; varray_intrinsic_members; varray_intrinsic_right_bracket; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_vector_intrinsic_expression vector_intrinsic_keyword vector_intrinsic_explicit_type vector_intrinsic_left_bracket vector_intrinsic_members vector_intrinsic_right_bracket = let syntax = VectorIntrinsicExpression { vector_intrinsic_keyword; vector_intrinsic_explicit_type; vector_intrinsic_left_bracket; vector_intrinsic_members; vector_intrinsic_right_bracket; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_element_initializer element_key element_arrow element_value = let syntax = ElementInitializer { element_key; element_arrow; element_value } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_subscript_expression subscript_receiver subscript_left_bracket subscript_index subscript_right_bracket = let syntax = SubscriptExpression { subscript_receiver; subscript_left_bracket; subscript_index; subscript_right_bracket; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_embedded_subscript_expression embedded_subscript_receiver embedded_subscript_left_bracket embedded_subscript_index embedded_subscript_right_bracket = let syntax = EmbeddedSubscriptExpression { embedded_subscript_receiver; embedded_subscript_left_bracket; embedded_subscript_index; embedded_subscript_right_bracket; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_awaitable_creation_expression awaitable_attribute_spec awaitable_async awaitable_compound_statement = let syntax = AwaitableCreationExpression { awaitable_attribute_spec; awaitable_async; awaitable_compound_statement; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_xhp_children_declaration xhp_children_keyword xhp_children_expression xhp_children_semicolon = let syntax = XHPChildrenDeclaration { xhp_children_keyword; xhp_children_expression; xhp_children_semicolon; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_xhp_children_parenthesized_list xhp_children_list_left_paren xhp_children_list_xhp_children xhp_children_list_right_paren = let syntax = XHPChildrenParenthesizedList { xhp_children_list_left_paren; xhp_children_list_xhp_children; xhp_children_list_right_paren; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_xhp_category_declaration xhp_category_keyword xhp_category_categories xhp_category_semicolon = let syntax = XHPCategoryDeclaration { xhp_category_keyword; xhp_category_categories; xhp_category_semicolon; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_xhp_enum_type xhp_enum_like xhp_enum_keyword xhp_enum_left_brace xhp_enum_values xhp_enum_right_brace = let syntax = XHPEnumType { xhp_enum_like; xhp_enum_keyword; xhp_enum_left_brace; xhp_enum_values; xhp_enum_right_brace; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_xhp_lateinit xhp_lateinit_at xhp_lateinit_keyword = let syntax = XHPLateinit { xhp_lateinit_at; xhp_lateinit_keyword } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_xhp_required xhp_required_at xhp_required_keyword = let syntax = XHPRequired { xhp_required_at; xhp_required_keyword } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_xhp_class_attribute_declaration xhp_attribute_keyword xhp_attribute_attributes xhp_attribute_semicolon = let syntax = XHPClassAttributeDeclaration { xhp_attribute_keyword; xhp_attribute_attributes; xhp_attribute_semicolon; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_xhp_class_attribute xhp_attribute_decl_type xhp_attribute_decl_name xhp_attribute_decl_initializer xhp_attribute_decl_required = let syntax = XHPClassAttribute { xhp_attribute_decl_type; xhp_attribute_decl_name; xhp_attribute_decl_initializer; xhp_attribute_decl_required; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_xhp_simple_class_attribute xhp_simple_class_attribute_type = let syntax = XHPSimpleClassAttribute { xhp_simple_class_attribute_type } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_xhp_simple_attribute xhp_simple_attribute_name xhp_simple_attribute_equal xhp_simple_attribute_expression = let syntax = XHPSimpleAttribute { xhp_simple_attribute_name; xhp_simple_attribute_equal; xhp_simple_attribute_expression; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_xhp_spread_attribute xhp_spread_attribute_left_brace xhp_spread_attribute_spread_operator xhp_spread_attribute_expression xhp_spread_attribute_right_brace = let syntax = XHPSpreadAttribute { xhp_spread_attribute_left_brace; xhp_spread_attribute_spread_operator; xhp_spread_attribute_expression; xhp_spread_attribute_right_brace; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_xhp_open xhp_open_left_angle xhp_open_name xhp_open_attributes xhp_open_right_angle = let syntax = XHPOpen { xhp_open_left_angle; xhp_open_name; xhp_open_attributes; xhp_open_right_angle; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_xhp_expression xhp_open xhp_body xhp_close = let syntax = XHPExpression { xhp_open; xhp_body; xhp_close } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_xhp_close xhp_close_left_angle xhp_close_name xhp_close_right_angle = let syntax = XHPClose { xhp_close_left_angle; xhp_close_name; xhp_close_right_angle } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_type_constant type_constant_left_type type_constant_separator type_constant_right_type = let syntax = TypeConstant { type_constant_left_type; type_constant_separator; type_constant_right_type; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_vector_type_specifier vector_type_keyword vector_type_left_angle vector_type_type vector_type_trailing_comma vector_type_right_angle = let syntax = VectorTypeSpecifier { vector_type_keyword; vector_type_left_angle; vector_type_type; vector_type_trailing_comma; vector_type_right_angle; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_keyset_type_specifier keyset_type_keyword keyset_type_left_angle keyset_type_type keyset_type_trailing_comma keyset_type_right_angle = let syntax = KeysetTypeSpecifier { keyset_type_keyword; keyset_type_left_angle; keyset_type_type; keyset_type_trailing_comma; keyset_type_right_angle; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_tuple_type_explicit_specifier tuple_type_keyword tuple_type_left_angle tuple_type_types tuple_type_right_angle = let syntax = TupleTypeExplicitSpecifier { tuple_type_keyword; tuple_type_left_angle; tuple_type_types; tuple_type_right_angle; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_varray_type_specifier varray_keyword varray_left_angle varray_type varray_trailing_comma varray_right_angle = let syntax = VarrayTypeSpecifier { varray_keyword; varray_left_angle; varray_type; varray_trailing_comma; varray_right_angle; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_function_ctx_type_specifier function_ctx_type_keyword function_ctx_type_variable = let syntax = FunctionCtxTypeSpecifier { function_ctx_type_keyword; function_ctx_type_variable } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_type_parameter type_attribute_spec type_reified type_variance type_name type_param_params type_constraints = let syntax = TypeParameter { type_attribute_spec; type_reified; type_variance; type_name; type_param_params; type_constraints; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_type_constraint constraint_keyword constraint_type = let syntax = TypeConstraint { constraint_keyword; constraint_type } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_context_constraint ctx_constraint_keyword ctx_constraint_ctx_list = let syntax = ContextConstraint { ctx_constraint_keyword; ctx_constraint_ctx_list } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_darray_type_specifier darray_keyword darray_left_angle darray_key darray_comma darray_value darray_trailing_comma darray_right_angle = let syntax = DarrayTypeSpecifier { darray_keyword; darray_left_angle; darray_key; darray_comma; darray_value; darray_trailing_comma; darray_right_angle; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_dictionary_type_specifier dictionary_type_keyword dictionary_type_left_angle dictionary_type_members dictionary_type_right_angle = let syntax = DictionaryTypeSpecifier { dictionary_type_keyword; dictionary_type_left_angle; dictionary_type_members; dictionary_type_right_angle; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_closure_type_specifier closure_outer_left_paren closure_readonly_keyword closure_function_keyword closure_inner_left_paren closure_parameter_list closure_inner_right_paren closure_contexts closure_colon closure_readonly_return closure_return_type closure_outer_right_paren = let syntax = ClosureTypeSpecifier { closure_outer_left_paren; closure_readonly_keyword; closure_function_keyword; closure_inner_left_paren; closure_parameter_list; closure_inner_right_paren; closure_contexts; closure_colon; closure_readonly_return; closure_return_type; closure_outer_right_paren; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_closure_parameter_type_specifier closure_parameter_call_convention closure_parameter_readonly closure_parameter_type = let syntax = ClosureParameterTypeSpecifier { closure_parameter_call_convention; closure_parameter_readonly; closure_parameter_type; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_type_refinement type_refinement_type type_refinement_keyword type_refinement_left_brace type_refinement_members type_refinement_right_brace = let syntax = TypeRefinement { type_refinement_type; type_refinement_keyword; type_refinement_left_brace; type_refinement_members; type_refinement_right_brace; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_type_in_refinement type_in_refinement_keyword type_in_refinement_name type_in_refinement_type_parameters type_in_refinement_constraints type_in_refinement_equal type_in_refinement_type = let syntax = TypeInRefinement { type_in_refinement_keyword; type_in_refinement_name; type_in_refinement_type_parameters; type_in_refinement_constraints; type_in_refinement_equal; type_in_refinement_type; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_ctx_in_refinement ctx_in_refinement_keyword ctx_in_refinement_name ctx_in_refinement_type_parameters ctx_in_refinement_constraints ctx_in_refinement_equal ctx_in_refinement_ctx_list = let syntax = CtxInRefinement { ctx_in_refinement_keyword; ctx_in_refinement_name; ctx_in_refinement_type_parameters; ctx_in_refinement_constraints; ctx_in_refinement_equal; ctx_in_refinement_ctx_list; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_classname_type_specifier classname_keyword classname_left_angle classname_type classname_trailing_comma classname_right_angle = let syntax = ClassnameTypeSpecifier { classname_keyword; classname_left_angle; classname_type; classname_trailing_comma; classname_right_angle; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_field_specifier field_question field_name field_arrow field_type = let syntax = FieldSpecifier { field_question; field_name; field_arrow; field_type } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_field_initializer field_initializer_name field_initializer_arrow field_initializer_value = let syntax = FieldInitializer { field_initializer_name; field_initializer_arrow; field_initializer_value; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_shape_type_specifier shape_type_keyword shape_type_left_paren shape_type_fields shape_type_ellipsis shape_type_right_paren = let syntax = ShapeTypeSpecifier { shape_type_keyword; shape_type_left_paren; shape_type_fields; shape_type_ellipsis; shape_type_right_paren; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_shape_expression shape_expression_keyword shape_expression_left_paren shape_expression_fields shape_expression_right_paren = let syntax = ShapeExpression { shape_expression_keyword; shape_expression_left_paren; shape_expression_fields; shape_expression_right_paren; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_tuple_expression tuple_expression_keyword tuple_expression_left_paren tuple_expression_items tuple_expression_right_paren = let syntax = TupleExpression { tuple_expression_keyword; tuple_expression_left_paren; tuple_expression_items; tuple_expression_right_paren; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_generic_type_specifier generic_class_type generic_argument_list = let syntax = GenericTypeSpecifier { generic_class_type; generic_argument_list } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_nullable_type_specifier nullable_question nullable_type = let syntax = NullableTypeSpecifier { nullable_question; nullable_type } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_like_type_specifier like_tilde like_type = let syntax = LikeTypeSpecifier { like_tilde; like_type } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_soft_type_specifier soft_at soft_type = let syntax = SoftTypeSpecifier { soft_at; soft_type } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_attributized_specifier attributized_specifier_attribute_spec attributized_specifier_type = let syntax = AttributizedSpecifier { attributized_specifier_attribute_spec; attributized_specifier_type; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_reified_type_argument reified_type_argument_reified reified_type_argument_type = let syntax = ReifiedTypeArgument { reified_type_argument_reified; reified_type_argument_type } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_type_arguments type_arguments_left_angle type_arguments_types type_arguments_right_angle = let syntax = TypeArguments { type_arguments_left_angle; type_arguments_types; type_arguments_right_angle; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_type_parameters type_parameters_left_angle type_parameters_parameters type_parameters_right_angle = let syntax = TypeParameters { type_parameters_left_angle; type_parameters_parameters; type_parameters_right_angle; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_tuple_type_specifier tuple_left_paren tuple_types tuple_right_paren = let syntax = TupleTypeSpecifier { tuple_left_paren; tuple_types; tuple_right_paren } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_union_type_specifier union_left_paren union_types union_right_paren = let syntax = UnionTypeSpecifier { union_left_paren; union_types; union_right_paren } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_intersection_type_specifier intersection_left_paren intersection_types intersection_right_paren = let syntax = IntersectionTypeSpecifier { intersection_left_paren; intersection_types; intersection_right_paren; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_error error_error = let syntax = ErrorSyntax { error_error } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_list_item list_item list_separator = let syntax = ListItem { list_item; list_separator } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_enum_class_label_expression enum_class_label_qualifier enum_class_label_hash enum_class_label_expression = let syntax = EnumClassLabelExpression { enum_class_label_qualifier; enum_class_label_hash; enum_class_label_expression; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_module_declaration module_declaration_attribute_spec module_declaration_new_keyword module_declaration_module_keyword module_declaration_name module_declaration_left_brace module_declaration_exports module_declaration_imports module_declaration_right_brace = let syntax = ModuleDeclaration { module_declaration_attribute_spec; module_declaration_new_keyword; module_declaration_module_keyword; module_declaration_name; module_declaration_left_brace; module_declaration_exports; module_declaration_imports; module_declaration_right_brace; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_module_exports module_exports_exports_keyword module_exports_left_brace module_exports_exports module_exports_right_brace = let syntax = ModuleExports { module_exports_exports_keyword; module_exports_left_brace; module_exports_exports; module_exports_right_brace; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_module_imports module_imports_imports_keyword module_imports_left_brace module_imports_imports module_imports_right_brace = let syntax = ModuleImports { module_imports_imports_keyword; module_imports_left_brace; module_imports_imports; module_imports_right_brace; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_module_membership_declaration module_membership_declaration_module_keyword module_membership_declaration_name module_membership_declaration_semicolon = let syntax = ModuleMembershipDeclaration { module_membership_declaration_module_keyword; module_membership_declaration_name; module_membership_declaration_semicolon; } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let make_package_expression package_expression_keyword package_expression_name = let syntax = PackageExpression { package_expression_keyword; package_expression_name } in let value = ValueBuilder.value_from_syntax syntax in make syntax value let from_function_declaration { function_attribute_spec; function_declaration_header; function_body; } = FunctionDeclaration { function_attribute_spec; function_declaration_header; function_body; } let from_function_declaration_header { function_modifiers; function_keyword; function_name; function_type_parameter_list; function_left_paren; function_parameter_list; function_right_paren; function_contexts; function_colon; function_readonly_return; function_type; function_where_clause; } = FunctionDeclarationHeader { function_modifiers; function_keyword; function_name; function_type_parameter_list; function_left_paren; function_parameter_list; function_right_paren; function_contexts; function_colon; function_readonly_return; function_type; function_where_clause; } let from_methodish_declaration { methodish_attribute; methodish_function_decl_header; methodish_function_body; methodish_semicolon; } = MethodishDeclaration { methodish_attribute; methodish_function_decl_header; methodish_function_body; methodish_semicolon; } let from_anonymous_function { anonymous_attribute_spec; anonymous_async_keyword; anonymous_function_keyword; anonymous_left_paren; anonymous_parameters; anonymous_right_paren; anonymous_ctx_list; anonymous_colon; anonymous_readonly_return; anonymous_type; anonymous_use; anonymous_body; } = AnonymousFunction { anonymous_attribute_spec; anonymous_async_keyword; anonymous_function_keyword; anonymous_left_paren; anonymous_parameters; anonymous_right_paren; anonymous_ctx_list; anonymous_colon; anonymous_readonly_return; anonymous_type; anonymous_use; anonymous_body; } let from_lambda_expression { lambda_attribute_spec; lambda_async; lambda_signature; lambda_arrow; lambda_body; } = LambdaExpression { lambda_attribute_spec; lambda_async; lambda_signature; lambda_arrow; lambda_body; } let from_lambda_signature { lambda_left_paren; lambda_parameters; lambda_right_paren; lambda_contexts; lambda_colon; lambda_readonly_return; lambda_type; } = LambdaSignature { lambda_left_paren; lambda_parameters; lambda_right_paren; lambda_contexts; lambda_colon; lambda_readonly_return; lambda_type; } let from_closure_type_specifier { closure_outer_left_paren; closure_readonly_keyword; closure_function_keyword; closure_inner_left_paren; closure_parameter_list; closure_inner_right_paren; closure_contexts; closure_colon; closure_readonly_return; closure_return_type; closure_outer_right_paren; } = ClosureTypeSpecifier { closure_outer_left_paren; closure_readonly_keyword; closure_function_keyword; closure_inner_left_paren; closure_parameter_list; closure_inner_right_paren; closure_contexts; closure_colon; closure_readonly_return; closure_return_type; closure_outer_right_paren; } let get_function_declaration x = match x with | FunctionDeclaration { function_attribute_spec; function_declaration_header; function_body; } -> { function_attribute_spec; function_declaration_header; function_body; } | _ -> failwith "get_function_declaration: not a FunctionDeclaration" let get_function_declaration_header x = match x with | FunctionDeclarationHeader { function_modifiers; function_keyword; function_name; function_type_parameter_list; function_left_paren; function_parameter_list; function_right_paren; function_contexts; function_colon; function_readonly_return; function_type; function_where_clause; } -> { function_modifiers; function_keyword; function_name; function_type_parameter_list; function_left_paren; function_parameter_list; function_right_paren; function_contexts; function_colon; function_readonly_return; function_type; function_where_clause; } | _ -> failwith "get_function_declaration_header: not a FunctionDeclarationHeader" let get_methodish_declaration x = match x with | MethodishDeclaration { methodish_attribute; methodish_function_decl_header; methodish_function_body; methodish_semicolon; } -> { methodish_attribute; methodish_function_decl_header; methodish_function_body; methodish_semicolon; } | _ -> failwith "get_methodish_declaration: not a MethodishDeclaration" let get_anonymous_function x = match x with | AnonymousFunction { anonymous_attribute_spec; anonymous_async_keyword; anonymous_function_keyword; anonymous_left_paren; anonymous_parameters; anonymous_right_paren; anonymous_ctx_list; anonymous_colon; anonymous_readonly_return; anonymous_type; anonymous_use; anonymous_body; } -> { anonymous_attribute_spec; anonymous_async_keyword; anonymous_function_keyword; anonymous_left_paren; anonymous_parameters; anonymous_right_paren; anonymous_ctx_list; anonymous_colon; anonymous_readonly_return; anonymous_type; anonymous_use; anonymous_body; } | _ -> failwith "get_anonymous_function: not a AnonymousFunction" let get_lambda_expression x = match x with | LambdaExpression { lambda_attribute_spec; lambda_async; lambda_signature; lambda_arrow; lambda_body; } -> { lambda_attribute_spec; lambda_async; lambda_signature; lambda_arrow; lambda_body; } | _ -> failwith "get_lambda_expression: not a LambdaExpression" let get_lambda_signature x = match x with | LambdaSignature { lambda_left_paren; lambda_parameters; lambda_right_paren; lambda_contexts; lambda_colon; lambda_readonly_return; lambda_type; } -> { lambda_left_paren; lambda_parameters; lambda_right_paren; lambda_contexts; lambda_colon; lambda_readonly_return; lambda_type; } | _ -> failwith "get_lambda_signature: not a LambdaSignature" let get_closure_type_specifier x = match x with | ClosureTypeSpecifier { closure_outer_left_paren; closure_readonly_keyword; closure_function_keyword; closure_inner_left_paren; closure_parameter_list; closure_inner_right_paren; closure_contexts; closure_colon; closure_readonly_return; closure_return_type; closure_outer_right_paren; } -> { closure_outer_left_paren; closure_readonly_keyword; closure_function_keyword; closure_inner_left_paren; closure_parameter_list; closure_inner_right_paren; closure_contexts; closure_colon; closure_readonly_return; closure_return_type; closure_outer_right_paren; } | _ -> failwith "get_closure_type_specifier: not a ClosureTypeSpecifier" end end end
OCaml
hhvm/hphp/hack/src/parser/full_fidelity_syntax_error.ml
(* * Copyright (c) 2016, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Sexplib.Std (* TODO: Integrate these with the rest of the Hack error messages. *) type error_type = | ParseError | RuntimeError [@@deriving show, sexp_of] type syntax_quickfix = { title: string; edits: (int * int * string) list; } [@@deriving show, sexp_of] type t = { child: t option; start_offset: int; end_offset: int; error_type: error_type; message: string; quickfixes: syntax_quickfix list; } [@@deriving show, sexp_of] exception ParserFatal of t * Pos.t let make ?(child = None) ?(error_type = ParseError) ?(quickfixes = []) start_offset end_offset message = { child; error_type; start_offset; end_offset; message; quickfixes } let rec to_positioned_string error offset_to_position = let child = match error.child with | Some child -> Printf.sprintf "\n %s" (to_positioned_string child offset_to_position) | _ -> "" in let (sl, sc) = offset_to_position error.start_offset in let (el, ec) = offset_to_position error.end_offset in Printf.sprintf "(%d,%d)-(%d,%d) %s%s" sl sc el ec error.message child let compare err1 err2 = if err1.start_offset < err2.start_offset then -1 else if err1.start_offset > err2.start_offset then 1 else if err1.end_offset < err2.end_offset then -1 else if err1.end_offset > err2.end_offset then 1 else 0 let exactly_equal err1 err2 = err1.start_offset = err2.start_offset && err1.end_offset = err2.end_offset && err1.message = err2.message let error_type err = err.error_type let message err = err.message let start_offset err = err.start_offset let end_offset err = err.end_offset let this_in_static = "Don't use $this in a static method, use static:: instead" let toplevel_await_use = "Await cannot be used in a toplevel statement"
OCaml Interface
hhvm/hphp/hack/src/parser/full_fidelity_syntax_error.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 error_type = | ParseError | RuntimeError [@@deriving show, sexp_of] type syntax_quickfix = { title: string; edits: (int * int * string) list; } [@@deriving show, sexp_of] type t = { child: t option; start_offset: int; end_offset: int; error_type: error_type; message: string; quickfixes: syntax_quickfix list; } [@@deriving show, sexp_of] exception ParserFatal of t * Pos.t val make : ?child:t option -> ?error_type:error_type -> ?quickfixes:syntax_quickfix list -> int -> int -> string -> t val to_positioned_string : t -> (int -> int * int) -> string val compare : t -> t -> int val exactly_equal : t -> t -> bool val error_type : t -> error_type val message : t -> string val start_offset : t -> int val end_offset : t -> int val this_in_static : string val toplevel_await_use : string
OCaml
hhvm/hphp/hack/src/parser/full_fidelity_syntax_kind.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. An additional * directory. * ** * * THIS FILE IS @generated; DO NOT EDIT IT * To regenerate this file, run * * buck run //hphp/hack/src:generate_full_fidelity * ** * *) type t = | Token of Full_fidelity_token_kind.t | Missing | SyntaxList | EndOfFile | Script | QualifiedName | ModuleName | SimpleTypeSpecifier | LiteralExpression | PrefixedStringExpression | PrefixedCodeExpression | VariableExpression | PipeVariableExpression | FileAttributeSpecification | EnumDeclaration | EnumUse | Enumerator | EnumClassDeclaration | EnumClassEnumerator | AliasDeclaration | ContextAliasDeclaration | CaseTypeDeclaration | CaseTypeVariant | PropertyDeclaration | PropertyDeclarator | NamespaceDeclaration | NamespaceDeclarationHeader | NamespaceBody | NamespaceEmptyBody | NamespaceUseDeclaration | NamespaceGroupUseDeclaration | NamespaceUseClause | FunctionDeclaration | FunctionDeclarationHeader | Contexts | WhereClause | WhereConstraint | MethodishDeclaration | MethodishTraitResolution | ClassishDeclaration | ClassishBody | TraitUse | RequireClause | ConstDeclaration | ConstantDeclarator | TypeConstDeclaration | ContextConstDeclaration | DecoratedExpression | ParameterDeclaration | VariadicParameter | OldAttributeSpecification | AttributeSpecification | Attribute | InclusionExpression | InclusionDirective | CompoundStatement | ExpressionStatement | MarkupSection | MarkupSuffix | UnsetStatement | DeclareLocalStatement | UsingStatementBlockScoped | UsingStatementFunctionScoped | WhileStatement | IfStatement | ElseClause | TryStatement | CatchClause | FinallyClause | DoStatement | ForStatement | ForeachStatement | SwitchStatement | SwitchSection | SwitchFallthrough | CaseLabel | DefaultLabel | MatchStatement | MatchStatementArm | ReturnStatement | YieldBreakStatement | ThrowStatement | BreakStatement | ContinueStatement | EchoStatement | ConcurrentStatement | SimpleInitializer | AnonymousClass | AnonymousFunction | AnonymousFunctionUseClause | VariablePattern | ConstructorPattern | RefinementPattern | LambdaExpression | LambdaSignature | CastExpression | ScopeResolutionExpression | MemberSelectionExpression | SafeMemberSelectionExpression | EmbeddedMemberSelectionExpression | YieldExpression | PrefixUnaryExpression | PostfixUnaryExpression | BinaryExpression | IsExpression | AsExpression | NullableAsExpression | UpcastExpression | ConditionalExpression | EvalExpression | IssetExpression | FunctionCallExpression | FunctionPointerExpression | ParenthesizedExpression | BracedExpression | ETSpliceExpression | EmbeddedBracedExpression | ListExpression | CollectionLiteralExpression | ObjectCreationExpression | ConstructorCall | DarrayIntrinsicExpression | DictionaryIntrinsicExpression | KeysetIntrinsicExpression | VarrayIntrinsicExpression | VectorIntrinsicExpression | ElementInitializer | SubscriptExpression | EmbeddedSubscriptExpression | AwaitableCreationExpression | XHPChildrenDeclaration | XHPChildrenParenthesizedList | XHPCategoryDeclaration | XHPEnumType | XHPLateinit | XHPRequired | XHPClassAttributeDeclaration | XHPClassAttribute | XHPSimpleClassAttribute | XHPSimpleAttribute | XHPSpreadAttribute | XHPOpen | XHPExpression | XHPClose | TypeConstant | VectorTypeSpecifier | KeysetTypeSpecifier | TupleTypeExplicitSpecifier | VarrayTypeSpecifier | FunctionCtxTypeSpecifier | TypeParameter | TypeConstraint | ContextConstraint | DarrayTypeSpecifier | DictionaryTypeSpecifier | ClosureTypeSpecifier | ClosureParameterTypeSpecifier | TypeRefinement | TypeInRefinement | CtxInRefinement | ClassnameTypeSpecifier | FieldSpecifier | FieldInitializer | ShapeTypeSpecifier | ShapeExpression | TupleExpression | GenericTypeSpecifier | NullableTypeSpecifier | LikeTypeSpecifier | SoftTypeSpecifier | AttributizedSpecifier | ReifiedTypeArgument | TypeArguments | TypeParameters | TupleTypeSpecifier | UnionTypeSpecifier | IntersectionTypeSpecifier | ErrorSyntax | ListItem | EnumClassLabelExpression | ModuleDeclaration | ModuleExports | ModuleImports | ModuleMembershipDeclaration | PackageExpression [@@deriving show, eq] let to_string kind = match kind with | Token _ -> "token" | Missing -> "missing" | SyntaxList -> "list" | EndOfFile -> "end_of_file" | Script -> "script" | QualifiedName -> "qualified_name" | ModuleName -> "module_name" | SimpleTypeSpecifier -> "simple_type_specifier" | LiteralExpression -> "literal" | PrefixedStringExpression -> "prefixed_string" | PrefixedCodeExpression -> "prefixed_code" | VariableExpression -> "variable" | PipeVariableExpression -> "pipe_variable" | FileAttributeSpecification -> "file_attribute_specification" | EnumDeclaration -> "enum_declaration" | EnumUse -> "enum_use" | Enumerator -> "enumerator" | EnumClassDeclaration -> "enum_class_declaration" | EnumClassEnumerator -> "enum_class_enumerator" | AliasDeclaration -> "alias_declaration" | ContextAliasDeclaration -> "context_alias_declaration" | CaseTypeDeclaration -> "case_type_declaration" | CaseTypeVariant -> "case_type_variant" | PropertyDeclaration -> "property_declaration" | PropertyDeclarator -> "property_declarator" | NamespaceDeclaration -> "namespace_declaration" | NamespaceDeclarationHeader -> "namespace_declaration_header" | NamespaceBody -> "namespace_body" | NamespaceEmptyBody -> "namespace_empty_body" | NamespaceUseDeclaration -> "namespace_use_declaration" | NamespaceGroupUseDeclaration -> "namespace_group_use_declaration" | NamespaceUseClause -> "namespace_use_clause" | FunctionDeclaration -> "function_declaration" | FunctionDeclarationHeader -> "function_declaration_header" | Contexts -> "contexts" | WhereClause -> "where_clause" | WhereConstraint -> "where_constraint" | MethodishDeclaration -> "methodish_declaration" | MethodishTraitResolution -> "methodish_trait_resolution" | ClassishDeclaration -> "classish_declaration" | ClassishBody -> "classish_body" | TraitUse -> "trait_use" | RequireClause -> "require_clause" | ConstDeclaration -> "const_declaration" | ConstantDeclarator -> "constant_declarator" | TypeConstDeclaration -> "type_const_declaration" | ContextConstDeclaration -> "context_const_declaration" | DecoratedExpression -> "decorated_expression" | ParameterDeclaration -> "parameter_declaration" | VariadicParameter -> "variadic_parameter" | OldAttributeSpecification -> "old_attribute_specification" | AttributeSpecification -> "attribute_specification" | Attribute -> "attribute" | InclusionExpression -> "inclusion_expression" | InclusionDirective -> "inclusion_directive" | CompoundStatement -> "compound_statement" | ExpressionStatement -> "expression_statement" | MarkupSection -> "markup_section" | MarkupSuffix -> "markup_suffix" | UnsetStatement -> "unset_statement" | DeclareLocalStatement -> "declare_local_statement" | UsingStatementBlockScoped -> "using_statement_block_scoped" | UsingStatementFunctionScoped -> "using_statement_function_scoped" | WhileStatement -> "while_statement" | IfStatement -> "if_statement" | ElseClause -> "else_clause" | TryStatement -> "try_statement" | CatchClause -> "catch_clause" | FinallyClause -> "finally_clause" | DoStatement -> "do_statement" | ForStatement -> "for_statement" | ForeachStatement -> "foreach_statement" | SwitchStatement -> "switch_statement" | SwitchSection -> "switch_section" | SwitchFallthrough -> "switch_fallthrough" | CaseLabel -> "case_label" | DefaultLabel -> "default_label" | MatchStatement -> "match_statement" | MatchStatementArm -> "match_statement_arm" | ReturnStatement -> "return_statement" | YieldBreakStatement -> "yield_break_statement" | ThrowStatement -> "throw_statement" | BreakStatement -> "break_statement" | ContinueStatement -> "continue_statement" | EchoStatement -> "echo_statement" | ConcurrentStatement -> "concurrent_statement" | SimpleInitializer -> "simple_initializer" | AnonymousClass -> "anonymous_class" | AnonymousFunction -> "anonymous_function" | AnonymousFunctionUseClause -> "anonymous_function_use_clause" | VariablePattern -> "variable_pattern" | ConstructorPattern -> "constructor_pattern" | RefinementPattern -> "refinement_pattern" | LambdaExpression -> "lambda_expression" | LambdaSignature -> "lambda_signature" | CastExpression -> "cast_expression" | ScopeResolutionExpression -> "scope_resolution_expression" | MemberSelectionExpression -> "member_selection_expression" | SafeMemberSelectionExpression -> "safe_member_selection_expression" | EmbeddedMemberSelectionExpression -> "embedded_member_selection_expression" | YieldExpression -> "yield_expression" | PrefixUnaryExpression -> "prefix_unary_expression" | PostfixUnaryExpression -> "postfix_unary_expression" | BinaryExpression -> "binary_expression" | IsExpression -> "is_expression" | AsExpression -> "as_expression" | NullableAsExpression -> "nullable_as_expression" | UpcastExpression -> "upcast_expression" | ConditionalExpression -> "conditional_expression" | EvalExpression -> "eval_expression" | IssetExpression -> "isset_expression" | FunctionCallExpression -> "function_call_expression" | FunctionPointerExpression -> "function_pointer_expression" | ParenthesizedExpression -> "parenthesized_expression" | BracedExpression -> "braced_expression" | ETSpliceExpression -> "et_splice_expression" | EmbeddedBracedExpression -> "embedded_braced_expression" | ListExpression -> "list_expression" | CollectionLiteralExpression -> "collection_literal_expression" | ObjectCreationExpression -> "object_creation_expression" | ConstructorCall -> "constructor_call" | DarrayIntrinsicExpression -> "darray_intrinsic_expression" | DictionaryIntrinsicExpression -> "dictionary_intrinsic_expression" | KeysetIntrinsicExpression -> "keyset_intrinsic_expression" | VarrayIntrinsicExpression -> "varray_intrinsic_expression" | VectorIntrinsicExpression -> "vector_intrinsic_expression" | ElementInitializer -> "element_initializer" | SubscriptExpression -> "subscript_expression" | EmbeddedSubscriptExpression -> "embedded_subscript_expression" | AwaitableCreationExpression -> "awaitable_creation_expression" | XHPChildrenDeclaration -> "xhp_children_declaration" | XHPChildrenParenthesizedList -> "xhp_children_parenthesized_list" | XHPCategoryDeclaration -> "xhp_category_declaration" | XHPEnumType -> "xhp_enum_type" | XHPLateinit -> "xhp_lateinit" | XHPRequired -> "xhp_required" | XHPClassAttributeDeclaration -> "xhp_class_attribute_declaration" | XHPClassAttribute -> "xhp_class_attribute" | XHPSimpleClassAttribute -> "xhp_simple_class_attribute" | XHPSimpleAttribute -> "xhp_simple_attribute" | XHPSpreadAttribute -> "xhp_spread_attribute" | XHPOpen -> "xhp_open" | XHPExpression -> "xhp_expression" | XHPClose -> "xhp_close" | TypeConstant -> "type_constant" | VectorTypeSpecifier -> "vector_type_specifier" | KeysetTypeSpecifier -> "keyset_type_specifier" | TupleTypeExplicitSpecifier -> "tuple_type_explicit_specifier" | VarrayTypeSpecifier -> "varray_type_specifier" | FunctionCtxTypeSpecifier -> "function_ctx_type_specifier" | TypeParameter -> "type_parameter" | TypeConstraint -> "type_constraint" | ContextConstraint -> "context_constraint" | DarrayTypeSpecifier -> "darray_type_specifier" | DictionaryTypeSpecifier -> "dictionary_type_specifier" | ClosureTypeSpecifier -> "closure_type_specifier" | ClosureParameterTypeSpecifier -> "closure_parameter_type_specifier" | TypeRefinement -> "type_refinement" | TypeInRefinement -> "type_in_refinement" | CtxInRefinement -> "ctx_in_refinement" | ClassnameTypeSpecifier -> "classname_type_specifier" | FieldSpecifier -> "field_specifier" | FieldInitializer -> "field_initializer" | ShapeTypeSpecifier -> "shape_type_specifier" | ShapeExpression -> "shape_expression" | TupleExpression -> "tuple_expression" | GenericTypeSpecifier -> "generic_type_specifier" | NullableTypeSpecifier -> "nullable_type_specifier" | LikeTypeSpecifier -> "like_type_specifier" | SoftTypeSpecifier -> "soft_type_specifier" | AttributizedSpecifier -> "attributized_specifier" | ReifiedTypeArgument -> "reified_type_argument" | TypeArguments -> "type_arguments" | TypeParameters -> "type_parameters" | TupleTypeSpecifier -> "tuple_type_specifier" | UnionTypeSpecifier -> "union_type_specifier" | IntersectionTypeSpecifier -> "intersection_type_specifier" | ErrorSyntax -> "error" | ListItem -> "list_item" | EnumClassLabelExpression -> "enum_class_label" | ModuleDeclaration -> "module_declaration" | ModuleExports -> "module_exports" | ModuleImports -> "module_imports" | ModuleMembershipDeclaration -> "module_membership_declaration" | PackageExpression -> "package_expression"
OCaml
hhvm/hphp/hack/src/parser/full_fidelity_syntax_tree.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. * *) (** * A syntax tree is just a thin wrapper around all the output of the parser: * the source text that was parsed, the root of the parse tree, and a * collection of parser and lexer errors. * * "Making" a syntax tree from text parses the text. * *) open Hh_prelude module SourceText = Full_fidelity_source_text module Env = Full_fidelity_parser_env module SyntaxError = Full_fidelity_syntax_error module WithSyntax (Syntax : Syntax_sig.Syntax_S) = struct module WithSmartConstructors (SCI : SmartConstructors.SmartConstructors_S with type r = Syntax.t with module Token = Syntax.Token) = struct module Parser_ = Full_fidelity_parser.WithSyntax (Syntax) module Parser = Parser_.WithSmartConstructors (SCI) open Syntax type t = { text: SourceText.t; root: Syntax.t; rust_tree: Rust_pointer.t option; errors: SyntaxError.t list; mode: FileInfo.mode option; state: SCI.t; } [@@deriving show, sexp_of] let remove_duplicates errors equals = (* Assumes the list is sorted so that equal items are together. *) let rec aux errors acc = match errors with | [] -> acc | h1 :: t1 -> begin match t1 with | [] -> h1 :: acc | h2 :: t2 -> if equals h1 h2 then aux (h1 :: t2) acc else aux t1 (h1 :: acc) end in let result = aux errors [] in List.rev result let build (text : SourceText.t) (root : Syntax.t) (rust_tree : Rust_pointer.t option) (errors : SyntaxError.t list) (mode : FileInfo.mode option) (state : SCI.t) : t = { text; root; rust_tree; errors; mode; state } let process_errors errors = (* We've got the lexical errors and the parser errors together, both with lexically later errors earlier in the list. We want to reverse the list so that later errors come later, and then do a stable sort to put the lexical and parser errors together. *) let errors = List.rev errors in let errors = List.stable_sort ~compare:SyntaxError.compare errors in remove_duplicates errors SyntaxError.exactly_equal let create text root rust_tree errors mode state = let errors = process_errors errors in build text root rust_tree errors mode state let make ?(env = Env.default) text = let mode = Full_fidelity_parser.parse_mode text in let parser = Parser.make env text in let (parser, root, rust_tree) = Parser.parse_script parser in let errors = Parser.errors parser in let state = Parser.sc_state parser in create text root rust_tree errors mode state let root tree = tree.root let rust_tree tree = tree.rust_tree let text tree = tree.text let all_errors tree = tree.errors let remove_cascading errors = let equals e1 e2 = SyntaxError.compare e1 e2 = 0 in remove_duplicates errors equals let mode tree = tree.mode let sc_state tree = tree.state let is_strict tree = match tree.mode with | Some FileInfo.Mstrict -> true | _ -> false let is_hhi tree = match tree.mode with | Some FileInfo.Mhhi -> true | _ -> false let errors_no_bodies tree = let not_in_body error = not (is_in_body tree.root error.SyntaxError.start_offset) in List.filter ~f:not_in_body tree.errors (* By default we strip out (1) all cascading errors, and (2) in decl mode, all errors that happen in a body. *) let errors tree = let e = if is_hhi tree then errors_no_bodies tree else all_errors tree in remove_cascading e let parse_tree_to_json ?with_value ?ignore_missing tree = Syntax.to_json ?with_value ?ignore_missing tree.root let to_json ?with_value ?ignore_missing tree = let version = Full_fidelity_schema.full_fidelity_schema_version_number in let root = parse_tree_to_json ?with_value ?ignore_missing tree in let text = Hh_json.JSON_String (SourceText.text tree.text) in Hh_json.JSON_Object [ ("parse_tree", root); ("program_text", text); ("version", Hh_json.JSON_String version); ] end include WithSmartConstructors (SyntaxSmartConstructors.WithSyntax (Syntax)) let create text root errors mode = create text root None errors mode () let build text root errors mode = build text root None errors mode () end
OCaml Interface
hhvm/hphp/hack/src/parser/full_fidelity_syntax_tree.mli
(* * 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 WithSyntax (Syntax : Syntax_sig.Syntax_S) : sig module WithSmartConstructors (SmartConstructors : SmartConstructors.SmartConstructors_S with type r = Syntax.t with module Token = Syntax.Token) : sig type t [@@deriving show, sexp_of] val make : ?env:Full_fidelity_parser_env.t -> Full_fidelity_source_text.t -> t val create : Full_fidelity_source_text.t -> Syntax.t -> Rust_pointer.t option -> Full_fidelity_syntax_error.t list -> FileInfo.mode option -> SmartConstructors.t -> t val build : Full_fidelity_source_text.t -> Syntax.t -> Rust_pointer.t option -> Full_fidelity_syntax_error.t list -> FileInfo.mode option -> SmartConstructors.t -> t val root : t -> Syntax.t val rust_tree : t -> Rust_pointer.t option val text : t -> Full_fidelity_source_text.t val sc_state : t -> SmartConstructors.t val all_errors : t -> Full_fidelity_syntax_error.t list val errors : t -> Full_fidelity_syntax_error.t list val mode : t -> FileInfo.mode option val is_strict : t -> bool val is_hhi : t -> bool val to_json : ?with_value:bool -> ?ignore_missing:bool -> t -> Hh_json.json val parse_tree_to_json : ?with_value:bool -> ?ignore_missing:bool -> t -> Hh_json.json end include module type of WithSmartConstructors (SyntaxSmartConstructors.WithSyntax (Syntax)) val create : Full_fidelity_source_text.t -> Syntax.t -> Full_fidelity_syntax_error.t list -> FileInfo.mode option -> t val build : Full_fidelity_source_text.t -> Syntax.t -> Full_fidelity_syntax_error.t list -> FileInfo.mode option -> t end
OCaml
hhvm/hphp/hack/src/parser/full_fidelity_syntax_type.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. An additional * directory. * ** * * THIS FILE IS @generated; DO NOT EDIT IT * To regenerate this file, run * * buck run //hphp/hack/src:generate_full_fidelity * ** * * This module contains the type describing the structure of a syntax tree. * * The structure of the syntax tree is described by the collection of recursive * types that makes up the bulk of this file. The type `t` is the type of a node * in the syntax tree; each node has associated with it an arbitrary value of * type `SyntaxValue.t`, and syntax node proper, which has structure given by * the `syntax` type. * * Note that every child in the syntax tree is of type `t`, except for the * `Token.t` type. This should be the *only* child of a type other than `t`. * We are explicitly NOT attempting to impose a type structure on the parse * tree beyond what is already implied by the types here. For example, * we are not attempting to put into the type system here the restriction that * the children of a binary operator must be expressions. The reason for this * is because we are potentially parsing code as it is being typed, and we * do not want to restrict our ability to make good error recovery by imposing * a restriction that will only be valid in correct program text. * * That said, it would of course be ideal if the only children of a compound * statement were statements, and so on. But those invariants should be * imposed by the design of the parser, not by the type system of the syntax * tree code. * * We want to be able to use different kinds of tokens, with different * performance characteristics. Moreover, we want to associate arbitrary values * with the syntax nodes, so that we can construct syntax trees with various * properties -- trees that only know their widths and are thereby cheap to * serialize, trees that have full position data for each node, trees where the * tokens know their text and can therefore be edited, trees that have name * annotations or type annotations, and so on. * * We wish to associate arbitrary values with the syntax nodes so that we can * construct syntax trees with various properties -- trees that only know * their widths and are thereby cheap to serialize, trees that have full * position data for each node, trees where the tokens know their text and * can therefore be edited, trees that have name annotations or type * annotations, and so on. * * Therefore this module is functorized by the types for token and value to be * associated with the node. *) open Sexplib.Std module type TokenType = sig module Trivia : Lexable_trivia_sig.LexableTrivia_S type t [@@deriving show, eq, sexp_of] val kind : t -> Full_fidelity_token_kind.t val to_json : t -> Hh_json.json val leading : t -> Trivia.t list end module type SyntaxValueType = sig type t [@@deriving show, eq, sexp_of] val to_json : t -> Hh_json.json end (* This functor describe the shape of a parse tree that has a particular kind of * token in the leaves, and a particular kind of value associated with each * node. *) module MakeSyntaxType (Token : TokenType) (SyntaxValue : SyntaxValueType) = struct type value = SyntaxValue.t [@@deriving show, eq, sexp_of] type t = { syntax: syntax; value: value; } [@@deriving show, eq, sexp_of] and function_declaration = { function_attribute_spec: t; function_declaration_header: t; function_body: t; } and function_declaration_header = { function_modifiers: t; function_keyword: t; function_name: t; function_type_parameter_list: t; function_left_paren: t; function_parameter_list: t; function_right_paren: t; function_contexts: t; function_colon: t; function_readonly_return: t; function_type: t; function_where_clause: t; } and methodish_declaration = { methodish_attribute: t; methodish_function_decl_header: t; methodish_function_body: t; methodish_semicolon: t; } and anonymous_function = { anonymous_attribute_spec: t; anonymous_async_keyword: t; anonymous_function_keyword: t; anonymous_left_paren: t; anonymous_parameters: t; anonymous_right_paren: t; anonymous_ctx_list: t; anonymous_colon: t; anonymous_readonly_return: t; anonymous_type: t; anonymous_use: t; anonymous_body: t; } and lambda_expression = { lambda_attribute_spec: t; lambda_async: t; lambda_signature: t; lambda_arrow: t; lambda_body: t; } and lambda_signature = { lambda_left_paren: t; lambda_parameters: t; lambda_right_paren: t; lambda_contexts: t; lambda_colon: t; lambda_readonly_return: t; lambda_type: t; } and closure_type_specifier = { closure_outer_left_paren: t; closure_readonly_keyword: t; closure_function_keyword: t; closure_inner_left_paren: t; closure_parameter_list: t; closure_inner_right_paren: t; closure_contexts: t; closure_colon: t; closure_readonly_return: t; closure_return_type: t; closure_outer_right_paren: t; } and syntax = | Token of Token.t | Missing | SyntaxList of t list | EndOfFile of { end_of_file_token: t } | Script of { script_declarations: t } | QualifiedName of { qualified_name_parts: t } | ModuleName of { module_name_parts: t } | SimpleTypeSpecifier of { simple_type_specifier: t } | LiteralExpression of { literal_expression: t } | PrefixedStringExpression of { prefixed_string_name: t; prefixed_string_str: t; } | PrefixedCodeExpression of { prefixed_code_prefix: t; prefixed_code_left_backtick: t; prefixed_code_body: t; prefixed_code_right_backtick: t; } | VariableExpression of { variable_expression: t } | PipeVariableExpression of { pipe_variable_expression: t } | FileAttributeSpecification of { file_attribute_specification_left_double_angle: t; file_attribute_specification_keyword: t; file_attribute_specification_colon: t; file_attribute_specification_attributes: t; file_attribute_specification_right_double_angle: t; } | EnumDeclaration of { enum_attribute_spec: t; enum_modifiers: t; enum_keyword: t; enum_name: t; enum_colon: t; enum_base: t; enum_type: t; enum_left_brace: t; enum_use_clauses: t; enum_enumerators: t; enum_right_brace: t; } | EnumUse of { enum_use_keyword: t; enum_use_names: t; enum_use_semicolon: t; } | Enumerator of { enumerator_name: t; enumerator_equal: t; enumerator_value: t; enumerator_semicolon: t; } | EnumClassDeclaration of { enum_class_attribute_spec: t; enum_class_modifiers: t; enum_class_enum_keyword: t; enum_class_class_keyword: t; enum_class_name: t; enum_class_colon: t; enum_class_base: t; enum_class_extends: t; enum_class_extends_list: t; enum_class_left_brace: t; enum_class_elements: t; enum_class_right_brace: t; } | EnumClassEnumerator of { enum_class_enumerator_modifiers: t; enum_class_enumerator_type: t; enum_class_enumerator_name: t; enum_class_enumerator_initializer: t; enum_class_enumerator_semicolon: t; } | AliasDeclaration of { alias_attribute_spec: t; alias_modifiers: t; alias_module_kw_opt: t; alias_keyword: t; alias_name: t; alias_generic_parameter: t; alias_constraint: t; alias_equal: t; alias_type: t; alias_semicolon: t; } | ContextAliasDeclaration of { ctx_alias_attribute_spec: t; ctx_alias_keyword: t; ctx_alias_name: t; ctx_alias_generic_parameter: t; ctx_alias_as_constraint: t; ctx_alias_equal: t; ctx_alias_context: t; ctx_alias_semicolon: t; } | CaseTypeDeclaration of { case_type_attribute_spec: t; case_type_modifiers: t; case_type_case_keyword: t; case_type_type_keyword: t; case_type_name: t; case_type_generic_parameter: t; case_type_as: t; case_type_bounds: t; case_type_equal: t; case_type_variants: t; case_type_semicolon: t; } | CaseTypeVariant of { case_type_variant_bar: t; case_type_variant_type: t; } | PropertyDeclaration of { property_attribute_spec: t; property_modifiers: t; property_type: t; property_declarators: t; property_semicolon: t; } | PropertyDeclarator of { property_name: t; property_initializer: t; } | NamespaceDeclaration of { namespace_header: t; namespace_body: t; } | NamespaceDeclarationHeader of { namespace_keyword: t; namespace_name: t; } | NamespaceBody of { namespace_left_brace: t; namespace_declarations: t; namespace_right_brace: t; } | NamespaceEmptyBody of { namespace_semicolon: t } | NamespaceUseDeclaration of { namespace_use_keyword: t; namespace_use_kind: t; namespace_use_clauses: t; namespace_use_semicolon: t; } | NamespaceGroupUseDeclaration of { namespace_group_use_keyword: t; namespace_group_use_kind: t; namespace_group_use_prefix: t; namespace_group_use_left_brace: t; namespace_group_use_clauses: t; namespace_group_use_right_brace: t; namespace_group_use_semicolon: t; } | NamespaceUseClause of { namespace_use_clause_kind: t; namespace_use_name: t; namespace_use_as: t; namespace_use_alias: t; } | FunctionDeclaration of { function_attribute_spec: t; function_declaration_header: t; function_body: t; } | FunctionDeclarationHeader of { function_modifiers: t; function_keyword: t; function_name: t; function_type_parameter_list: t; function_left_paren: t; function_parameter_list: t; function_right_paren: t; function_contexts: t; function_colon: t; function_readonly_return: t; function_type: t; function_where_clause: t; } | Contexts of { contexts_left_bracket: t; contexts_types: t; contexts_right_bracket: t; } | WhereClause of { where_clause_keyword: t; where_clause_constraints: t; } | WhereConstraint of { where_constraint_left_type: t; where_constraint_operator: t; where_constraint_right_type: t; } | MethodishDeclaration of { methodish_attribute: t; methodish_function_decl_header: t; methodish_function_body: t; methodish_semicolon: t; } | MethodishTraitResolution of { methodish_trait_attribute: t; methodish_trait_function_decl_header: t; methodish_trait_equal: t; methodish_trait_name: t; methodish_trait_semicolon: t; } | ClassishDeclaration of { classish_attribute: t; classish_modifiers: t; classish_xhp: t; classish_keyword: t; classish_name: t; classish_type_parameters: t; classish_extends_keyword: t; classish_extends_list: t; classish_implements_keyword: t; classish_implements_list: t; classish_where_clause: t; classish_body: t; } | ClassishBody of { classish_body_left_brace: t; classish_body_elements: t; classish_body_right_brace: t; } | TraitUse of { trait_use_keyword: t; trait_use_names: t; trait_use_semicolon: t; } | RequireClause of { require_keyword: t; require_kind: t; require_name: t; require_semicolon: t; } | ConstDeclaration of { const_attribute_spec: t; const_modifiers: t; const_keyword: t; const_type_specifier: t; const_declarators: t; const_semicolon: t; } | ConstantDeclarator of { constant_declarator_name: t; constant_declarator_initializer: t; } | TypeConstDeclaration of { type_const_attribute_spec: t; type_const_modifiers: t; type_const_keyword: t; type_const_type_keyword: t; type_const_name: t; type_const_type_parameters: t; type_const_type_constraints: t; type_const_equal: t; type_const_type_specifier: t; type_const_semicolon: t; } | ContextConstDeclaration of { context_const_modifiers: t; context_const_const_keyword: t; context_const_ctx_keyword: t; context_const_name: t; context_const_type_parameters: t; context_const_constraint: t; context_const_equal: t; context_const_ctx_list: t; context_const_semicolon: t; } | DecoratedExpression of { decorated_expression_decorator: t; decorated_expression_expression: t; } | ParameterDeclaration of { parameter_attribute: t; parameter_visibility: t; parameter_call_convention: t; parameter_readonly: t; parameter_type: t; parameter_name: t; parameter_default_value: t; } | VariadicParameter of { variadic_parameter_call_convention: t; variadic_parameter_type: t; variadic_parameter_ellipsis: t; } | OldAttributeSpecification of { old_attribute_specification_left_double_angle: t; old_attribute_specification_attributes: t; old_attribute_specification_right_double_angle: t; } | AttributeSpecification of { attribute_specification_attributes: t } | Attribute of { attribute_at: t; attribute_attribute_name: t; } | InclusionExpression of { inclusion_require: t; inclusion_filename: t; } | InclusionDirective of { inclusion_expression: t; inclusion_semicolon: t; } | CompoundStatement of { compound_left_brace: t; compound_statements: t; compound_right_brace: t; } | ExpressionStatement of { expression_statement_expression: t; expression_statement_semicolon: t; } | MarkupSection of { markup_hashbang: t; markup_suffix: t; } | MarkupSuffix of { markup_suffix_less_than_question: t; markup_suffix_name: t; } | UnsetStatement of { unset_keyword: t; unset_left_paren: t; unset_variables: t; unset_right_paren: t; unset_semicolon: t; } | DeclareLocalStatement of { declare_local_keyword: t; declare_local_variable: t; declare_local_colon: t; declare_local_type: t; declare_local_initializer: t; declare_local_semicolon: t; } | UsingStatementBlockScoped of { using_block_await_keyword: t; using_block_using_keyword: t; using_block_left_paren: t; using_block_expressions: t; using_block_right_paren: t; using_block_body: t; } | UsingStatementFunctionScoped of { using_function_await_keyword: t; using_function_using_keyword: t; using_function_expression: t; using_function_semicolon: t; } | WhileStatement of { while_keyword: t; while_left_paren: t; while_condition: t; while_right_paren: t; while_body: t; } | IfStatement of { if_keyword: t; if_left_paren: t; if_condition: t; if_right_paren: t; if_statement: t; if_else_clause: t; } | ElseClause of { else_keyword: t; else_statement: t; } | TryStatement of { try_keyword: t; try_compound_statement: t; try_catch_clauses: t; try_finally_clause: t; } | CatchClause of { catch_keyword: t; catch_left_paren: t; catch_type: t; catch_variable: t; catch_right_paren: t; catch_body: t; } | FinallyClause of { finally_keyword: t; finally_body: t; } | DoStatement of { do_keyword: t; do_body: t; do_while_keyword: t; do_left_paren: t; do_condition: t; do_right_paren: t; do_semicolon: t; } | ForStatement of { for_keyword: t; for_left_paren: t; for_initializer: t; for_first_semicolon: t; for_control: t; for_second_semicolon: t; for_end_of_loop: t; for_right_paren: t; for_body: t; } | ForeachStatement of { foreach_keyword: t; foreach_left_paren: t; foreach_collection: t; foreach_await_keyword: t; foreach_as: t; foreach_key: t; foreach_arrow: t; foreach_value: t; foreach_right_paren: t; foreach_body: t; } | SwitchStatement of { switch_keyword: t; switch_left_paren: t; switch_expression: t; switch_right_paren: t; switch_left_brace: t; switch_sections: t; switch_right_brace: t; } | SwitchSection of { switch_section_labels: t; switch_section_statements: t; switch_section_fallthrough: t; } | SwitchFallthrough of { fallthrough_keyword: t; fallthrough_semicolon: t; } | CaseLabel of { case_keyword: t; case_expression: t; case_colon: t; } | DefaultLabel of { default_keyword: t; default_colon: t; } | MatchStatement of { match_statement_keyword: t; match_statement_left_paren: t; match_statement_expression: t; match_statement_right_paren: t; match_statement_left_brace: t; match_statement_arms: t; match_statement_right_brace: t; } | MatchStatementArm of { match_statement_arm_pattern: t; match_statement_arm_arrow: t; match_statement_arm_body: t; } | ReturnStatement of { return_keyword: t; return_expression: t; return_semicolon: t; } | YieldBreakStatement of { yield_break_keyword: t; yield_break_break: t; yield_break_semicolon: t; } | ThrowStatement of { throw_keyword: t; throw_expression: t; throw_semicolon: t; } | BreakStatement of { break_keyword: t; break_semicolon: t; } | ContinueStatement of { continue_keyword: t; continue_semicolon: t; } | EchoStatement of { echo_keyword: t; echo_expressions: t; echo_semicolon: t; } | ConcurrentStatement of { concurrent_keyword: t; concurrent_statement: t; } | SimpleInitializer of { simple_initializer_equal: t; simple_initializer_value: t; } | AnonymousClass of { anonymous_class_class_keyword: t; anonymous_class_left_paren: t; anonymous_class_argument_list: t; anonymous_class_right_paren: t; anonymous_class_extends_keyword: t; anonymous_class_extends_list: t; anonymous_class_implements_keyword: t; anonymous_class_implements_list: t; anonymous_class_body: t; } | AnonymousFunction of { anonymous_attribute_spec: t; anonymous_async_keyword: t; anonymous_function_keyword: t; anonymous_left_paren: t; anonymous_parameters: t; anonymous_right_paren: t; anonymous_ctx_list: t; anonymous_colon: t; anonymous_readonly_return: t; anonymous_type: t; anonymous_use: t; anonymous_body: t; } | AnonymousFunctionUseClause of { anonymous_use_keyword: t; anonymous_use_left_paren: t; anonymous_use_variables: t; anonymous_use_right_paren: t; } | VariablePattern of { variable_pattern_variable: t } | ConstructorPattern of { constructor_pattern_constructor: t; constructor_pattern_left_paren: t; constructor_pattern_members: t; constructor_pattern_right_paren: t; } | RefinementPattern of { refinement_pattern_variable: t; refinement_pattern_colon: t; refinement_pattern_specifier: t; } | LambdaExpression of { lambda_attribute_spec: t; lambda_async: t; lambda_signature: t; lambda_arrow: t; lambda_body: t; } | LambdaSignature of { lambda_left_paren: t; lambda_parameters: t; lambda_right_paren: t; lambda_contexts: t; lambda_colon: t; lambda_readonly_return: t; lambda_type: t; } | CastExpression of { cast_left_paren: t; cast_type: t; cast_right_paren: t; cast_operand: t; } | ScopeResolutionExpression of { scope_resolution_qualifier: t; scope_resolution_operator: t; scope_resolution_name: t; } | MemberSelectionExpression of { member_object: t; member_operator: t; member_name: t; } | SafeMemberSelectionExpression of { safe_member_object: t; safe_member_operator: t; safe_member_name: t; } | EmbeddedMemberSelectionExpression of { embedded_member_object: t; embedded_member_operator: t; embedded_member_name: t; } | YieldExpression of { yield_keyword: t; yield_operand: t; } | PrefixUnaryExpression of { prefix_unary_operator: t; prefix_unary_operand: t; } | PostfixUnaryExpression of { postfix_unary_operand: t; postfix_unary_operator: t; } | BinaryExpression of { binary_left_operand: t; binary_operator: t; binary_right_operand: t; } | IsExpression of { is_left_operand: t; is_operator: t; is_right_operand: t; } | AsExpression of { as_left_operand: t; as_operator: t; as_right_operand: t; } | NullableAsExpression of { nullable_as_left_operand: t; nullable_as_operator: t; nullable_as_right_operand: t; } | UpcastExpression of { upcast_left_operand: t; upcast_operator: t; upcast_right_operand: t; } | ConditionalExpression of { conditional_test: t; conditional_question: t; conditional_consequence: t; conditional_colon: t; conditional_alternative: t; } | EvalExpression of { eval_keyword: t; eval_left_paren: t; eval_argument: t; eval_right_paren: t; } | IssetExpression of { isset_keyword: t; isset_left_paren: t; isset_argument_list: t; isset_right_paren: t; } | FunctionCallExpression of { function_call_receiver: t; function_call_type_args: t; function_call_left_paren: t; function_call_argument_list: t; function_call_right_paren: t; } | FunctionPointerExpression of { function_pointer_receiver: t; function_pointer_type_args: t; } | ParenthesizedExpression of { parenthesized_expression_left_paren: t; parenthesized_expression_expression: t; parenthesized_expression_right_paren: t; } | BracedExpression of { braced_expression_left_brace: t; braced_expression_expression: t; braced_expression_right_brace: t; } | ETSpliceExpression of { et_splice_expression_dollar: t; et_splice_expression_left_brace: t; et_splice_expression_expression: t; et_splice_expression_right_brace: t; } | EmbeddedBracedExpression of { embedded_braced_expression_left_brace: t; embedded_braced_expression_expression: t; embedded_braced_expression_right_brace: t; } | ListExpression of { list_keyword: t; list_left_paren: t; list_members: t; list_right_paren: t; } | CollectionLiteralExpression of { collection_literal_name: t; collection_literal_left_brace: t; collection_literal_initializers: t; collection_literal_right_brace: t; } | ObjectCreationExpression of { object_creation_new_keyword: t; object_creation_object: t; } | ConstructorCall of { constructor_call_type: t; constructor_call_left_paren: t; constructor_call_argument_list: t; constructor_call_right_paren: t; } | DarrayIntrinsicExpression of { darray_intrinsic_keyword: t; darray_intrinsic_explicit_type: t; darray_intrinsic_left_bracket: t; darray_intrinsic_members: t; darray_intrinsic_right_bracket: t; } | DictionaryIntrinsicExpression of { dictionary_intrinsic_keyword: t; dictionary_intrinsic_explicit_type: t; dictionary_intrinsic_left_bracket: t; dictionary_intrinsic_members: t; dictionary_intrinsic_right_bracket: t; } | KeysetIntrinsicExpression of { keyset_intrinsic_keyword: t; keyset_intrinsic_explicit_type: t; keyset_intrinsic_left_bracket: t; keyset_intrinsic_members: t; keyset_intrinsic_right_bracket: t; } | VarrayIntrinsicExpression of { varray_intrinsic_keyword: t; varray_intrinsic_explicit_type: t; varray_intrinsic_left_bracket: t; varray_intrinsic_members: t; varray_intrinsic_right_bracket: t; } | VectorIntrinsicExpression of { vector_intrinsic_keyword: t; vector_intrinsic_explicit_type: t; vector_intrinsic_left_bracket: t; vector_intrinsic_members: t; vector_intrinsic_right_bracket: t; } | ElementInitializer of { element_key: t; element_arrow: t; element_value: t; } | SubscriptExpression of { subscript_receiver: t; subscript_left_bracket: t; subscript_index: t; subscript_right_bracket: t; } | EmbeddedSubscriptExpression of { embedded_subscript_receiver: t; embedded_subscript_left_bracket: t; embedded_subscript_index: t; embedded_subscript_right_bracket: t; } | AwaitableCreationExpression of { awaitable_attribute_spec: t; awaitable_async: t; awaitable_compound_statement: t; } | XHPChildrenDeclaration of { xhp_children_keyword: t; xhp_children_expression: t; xhp_children_semicolon: t; } | XHPChildrenParenthesizedList of { xhp_children_list_left_paren: t; xhp_children_list_xhp_children: t; xhp_children_list_right_paren: t; } | XHPCategoryDeclaration of { xhp_category_keyword: t; xhp_category_categories: t; xhp_category_semicolon: t; } | XHPEnumType of { xhp_enum_like: t; xhp_enum_keyword: t; xhp_enum_left_brace: t; xhp_enum_values: t; xhp_enum_right_brace: t; } | XHPLateinit of { xhp_lateinit_at: t; xhp_lateinit_keyword: t; } | XHPRequired of { xhp_required_at: t; xhp_required_keyword: t; } | XHPClassAttributeDeclaration of { xhp_attribute_keyword: t; xhp_attribute_attributes: t; xhp_attribute_semicolon: t; } | XHPClassAttribute of { xhp_attribute_decl_type: t; xhp_attribute_decl_name: t; xhp_attribute_decl_initializer: t; xhp_attribute_decl_required: t; } | XHPSimpleClassAttribute of { xhp_simple_class_attribute_type: t } | XHPSimpleAttribute of { xhp_simple_attribute_name: t; xhp_simple_attribute_equal: t; xhp_simple_attribute_expression: t; } | XHPSpreadAttribute of { xhp_spread_attribute_left_brace: t; xhp_spread_attribute_spread_operator: t; xhp_spread_attribute_expression: t; xhp_spread_attribute_right_brace: t; } | XHPOpen of { xhp_open_left_angle: t; xhp_open_name: t; xhp_open_attributes: t; xhp_open_right_angle: t; } | XHPExpression of { xhp_open: t; xhp_body: t; xhp_close: t; } | XHPClose of { xhp_close_left_angle: t; xhp_close_name: t; xhp_close_right_angle: t; } | TypeConstant of { type_constant_left_type: t; type_constant_separator: t; type_constant_right_type: t; } | VectorTypeSpecifier of { vector_type_keyword: t; vector_type_left_angle: t; vector_type_type: t; vector_type_trailing_comma: t; vector_type_right_angle: t; } | KeysetTypeSpecifier of { keyset_type_keyword: t; keyset_type_left_angle: t; keyset_type_type: t; keyset_type_trailing_comma: t; keyset_type_right_angle: t; } | TupleTypeExplicitSpecifier of { tuple_type_keyword: t; tuple_type_left_angle: t; tuple_type_types: t; tuple_type_right_angle: t; } | VarrayTypeSpecifier of { varray_keyword: t; varray_left_angle: t; varray_type: t; varray_trailing_comma: t; varray_right_angle: t; } | FunctionCtxTypeSpecifier of { function_ctx_type_keyword: t; function_ctx_type_variable: t; } | TypeParameter of { type_attribute_spec: t; type_reified: t; type_variance: t; type_name: t; type_param_params: t; type_constraints: t; } | TypeConstraint of { constraint_keyword: t; constraint_type: t; } | ContextConstraint of { ctx_constraint_keyword: t; ctx_constraint_ctx_list: t; } | DarrayTypeSpecifier of { darray_keyword: t; darray_left_angle: t; darray_key: t; darray_comma: t; darray_value: t; darray_trailing_comma: t; darray_right_angle: t; } | DictionaryTypeSpecifier of { dictionary_type_keyword: t; dictionary_type_left_angle: t; dictionary_type_members: t; dictionary_type_right_angle: t; } | ClosureTypeSpecifier of { closure_outer_left_paren: t; closure_readonly_keyword: t; closure_function_keyword: t; closure_inner_left_paren: t; closure_parameter_list: t; closure_inner_right_paren: t; closure_contexts: t; closure_colon: t; closure_readonly_return: t; closure_return_type: t; closure_outer_right_paren: t; } | ClosureParameterTypeSpecifier of { closure_parameter_call_convention: t; closure_parameter_readonly: t; closure_parameter_type: t; } | TypeRefinement of { type_refinement_type: t; type_refinement_keyword: t; type_refinement_left_brace: t; type_refinement_members: t; type_refinement_right_brace: t; } | TypeInRefinement of { type_in_refinement_keyword: t; type_in_refinement_name: t; type_in_refinement_type_parameters: t; type_in_refinement_constraints: t; type_in_refinement_equal: t; type_in_refinement_type: t; } | CtxInRefinement of { ctx_in_refinement_keyword: t; ctx_in_refinement_name: t; ctx_in_refinement_type_parameters: t; ctx_in_refinement_constraints: t; ctx_in_refinement_equal: t; ctx_in_refinement_ctx_list: t; } | ClassnameTypeSpecifier of { classname_keyword: t; classname_left_angle: t; classname_type: t; classname_trailing_comma: t; classname_right_angle: t; } | FieldSpecifier of { field_question: t; field_name: t; field_arrow: t; field_type: t; } | FieldInitializer of { field_initializer_name: t; field_initializer_arrow: t; field_initializer_value: t; } | ShapeTypeSpecifier of { shape_type_keyword: t; shape_type_left_paren: t; shape_type_fields: t; shape_type_ellipsis: t; shape_type_right_paren: t; } | ShapeExpression of { shape_expression_keyword: t; shape_expression_left_paren: t; shape_expression_fields: t; shape_expression_right_paren: t; } | TupleExpression of { tuple_expression_keyword: t; tuple_expression_left_paren: t; tuple_expression_items: t; tuple_expression_right_paren: t; } | GenericTypeSpecifier of { generic_class_type: t; generic_argument_list: t; } | NullableTypeSpecifier of { nullable_question: t; nullable_type: t; } | LikeTypeSpecifier of { like_tilde: t; like_type: t; } | SoftTypeSpecifier of { soft_at: t; soft_type: t; } | AttributizedSpecifier of { attributized_specifier_attribute_spec: t; attributized_specifier_type: t; } | ReifiedTypeArgument of { reified_type_argument_reified: t; reified_type_argument_type: t; } | TypeArguments of { type_arguments_left_angle: t; type_arguments_types: t; type_arguments_right_angle: t; } | TypeParameters of { type_parameters_left_angle: t; type_parameters_parameters: t; type_parameters_right_angle: t; } | TupleTypeSpecifier of { tuple_left_paren: t; tuple_types: t; tuple_right_paren: t; } | UnionTypeSpecifier of { union_left_paren: t; union_types: t; union_right_paren: t; } | IntersectionTypeSpecifier of { intersection_left_paren: t; intersection_types: t; intersection_right_paren: t; } | ErrorSyntax of { error_error: t } | ListItem of { list_item: t; list_separator: t; } | EnumClassLabelExpression of { enum_class_label_qualifier: t; enum_class_label_hash: t; enum_class_label_expression: t; } | ModuleDeclaration of { module_declaration_attribute_spec: t; module_declaration_new_keyword: t; module_declaration_module_keyword: t; module_declaration_name: t; module_declaration_left_brace: t; module_declaration_exports: t; module_declaration_imports: t; module_declaration_right_brace: t; } | ModuleExports of { module_exports_exports_keyword: t; module_exports_left_brace: t; module_exports_exports: t; module_exports_right_brace: t; } | ModuleImports of { module_imports_imports_keyword: t; module_imports_left_brace: t; module_imports_imports: t; module_imports_right_brace: t; } | ModuleMembershipDeclaration of { module_membership_declaration_module_keyword: t; module_membership_declaration_name: t; module_membership_declaration_semicolon: t; } | PackageExpression of { package_expression_keyword: t; package_expression_name: t; } [@@deriving sexp_of] end
OCaml
hhvm/hphp/hack/src/parser/full_fidelity_token_kind.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. An additional * directory. * ** * * THIS FILE IS @generated; DO NOT EDIT IT * To regenerate this file, run * * buck run //hphp/hack/src:generate_full_fidelity * ** * *) type t = (* No text tokens *) | EndOfFile (* Given text tokens *) | Abstract | Arraykey | As | Async | Attribute | Await | Backslash | Binary | Bool | Boolean | Break | Case | Catch | Category | Children | Class | Classname | Clone | Concurrent | Const | Construct | Continue | Ctx | Darray | Default | Dict | Do | Double | Echo | Else | Empty | Endif | Enum | Eval | Exports | Extends | Fallthrough | Float | File | Final | Finally | For | Foreach | Function | Global | If | Implements | Imports | Include | Include_once | Inout | Instanceof | Insteadof | Int | Integer | Interface | Is | Isset | Keyset | Lateinit | List | Match | Mixed | Module | Namespace | New | Newctx | Newtype | Noreturn | Num | Parent | Print | Private | Protected | Public | Real | Reify | Require | Require_once | Required | Resource | Return | Self | Shape | Static | String | Super | Switch | This | Throw | Trait | Try | Tuple | Type | Unset | Upcast | Use | Using | Var | Varray | Vec | Void | With | Where | While | Yield | NullLiteral | LeftBracket | RightBracket | LeftParen | RightParen | LeftBrace | RightBrace | Dot | MinusGreaterThan | PlusPlus | MinusMinus | StarStar | Star | Plus | Minus | Tilde | Exclamation | Dollar | Slash | Percent | LessThanEqualGreaterThan | LessThanLessThan | GreaterThanGreaterThan | LessThan | GreaterThan | LessThanEqual | GreaterThanEqual | EqualEqual | EqualEqualEqual | ExclamationEqual | ExclamationEqualEqual | Carat | Bar | Ampersand | AmpersandAmpersand | BarBar | Question | QuestionAs | QuestionColon | QuestionQuestion | QuestionQuestionEqual | Colon | Semicolon | Equal | StarStarEqual | StarEqual | SlashEqual | PercentEqual | PlusEqual | MinusEqual | DotEqual | LessThanLessThanEqual | GreaterThanGreaterThanEqual | AmpersandEqual | CaratEqual | BarEqual | Comma | At | ColonColon | EqualGreaterThan | EqualEqualGreaterThan | QuestionMinusGreaterThan | DotDotDot | DollarDollar | BarGreaterThan | SlashGreaterThan | LessThanSlash | LessThanQuestion | Backtick | XHP | Hash | Readonly | Internal | Package | Let (* Variable text tokens *) | ErrorToken | Name | Variable | DecimalLiteral | OctalLiteral | HexadecimalLiteral | BinaryLiteral | FloatingLiteral | SingleQuotedStringLiteral | DoubleQuotedStringLiteral | DoubleQuotedStringLiteralHead | StringLiteralBody | DoubleQuotedStringLiteralTail | HeredocStringLiteral | HeredocStringLiteralHead | HeredocStringLiteralTail | NowdocStringLiteral | BooleanLiteral | XHPCategoryName | XHPElementName | XHPClassName | XHPStringLiteral | XHPBody | XHPComment | Hashbang [@@deriving show, eq, sexp_of] let from_string keyword ~only_reserved = match keyword with | "true" when not only_reserved -> Some BooleanLiteral | "false" when not only_reserved -> Some BooleanLiteral | "abstract" -> Some Abstract | "arraykey" when not only_reserved -> Some Arraykey | "as" -> Some As | "async" -> Some Async | "attribute" when not only_reserved -> Some Attribute | "await" -> Some Await | "\\" -> Some Backslash | "binary" when not only_reserved -> Some Binary | "bool" when not only_reserved -> Some Bool | "boolean" when not only_reserved -> Some Boolean | "break" -> Some Break | "case" -> Some Case | "catch" -> Some Catch | "category" when not only_reserved -> Some Category | "children" when not only_reserved -> Some Children | "class" -> Some Class | "classname" when not only_reserved -> Some Classname | "clone" -> Some Clone | "concurrent" -> Some Concurrent | "const" -> Some Const | "__construct" -> Some Construct | "continue" -> Some Continue | "ctx" -> Some Ctx | "darray" when not only_reserved -> Some Darray | "default" -> Some Default | "dict" when not only_reserved -> Some Dict | "do" -> Some Do | "double" when not only_reserved -> Some Double | "echo" -> Some Echo | "else" -> Some Else | "empty" -> Some Empty | "endif" -> Some Endif | "enum" when not only_reserved -> Some Enum | "eval" -> Some Eval | "exports" when not only_reserved -> Some Exports | "extends" -> Some Extends | "fallthrough" when not only_reserved -> Some Fallthrough | "float" when not only_reserved -> Some Float | "file" when not only_reserved -> Some File | "final" -> Some Final | "finally" -> Some Finally | "for" -> Some For | "foreach" -> Some Foreach | "function" -> Some Function | "global" -> Some Global | "if" -> Some If | "implements" -> Some Implements | "imports" when not only_reserved -> Some Imports | "include" -> Some Include | "include_once" -> Some Include_once | "inout" -> Some Inout | "instanceof" -> Some Instanceof | "insteadof" -> Some Insteadof | "int" when not only_reserved -> Some Int | "integer" when not only_reserved -> Some Integer | "interface" -> Some Interface | "is" when not only_reserved -> Some Is | "isset" -> Some Isset | "keyset" when not only_reserved -> Some Keyset | "lateinit" -> Some Lateinit | "list" -> Some List | "match" when not only_reserved -> Some Match | "mixed" when not only_reserved -> Some Mixed | "module" -> Some Module | "namespace" -> Some Namespace | "new" -> Some New | "newctx" when not only_reserved -> Some Newctx | "newtype" when not only_reserved -> Some Newtype | "noreturn" when not only_reserved -> Some Noreturn | "num" when not only_reserved -> Some Num | "parent" when not only_reserved -> Some Parent | "print" -> Some Print | "private" -> Some Private | "protected" -> Some Protected | "public" -> Some Public | "real" when not only_reserved -> Some Real | "reify" when not only_reserved -> Some Reify | "require" -> Some Require | "require_once" -> Some Require_once | "required" -> Some Required | "resource" when not only_reserved -> Some Resource | "return" -> Some Return | "self" when not only_reserved -> Some Self | "shape" -> Some Shape | "static" -> Some Static | "string" when not only_reserved -> Some String | "super" when not only_reserved -> Some Super | "switch" -> Some Switch | "this" when not only_reserved -> Some This | "throw" -> Some Throw | "trait" -> Some Trait | "try" -> Some Try | "tuple" -> Some Tuple | "type" when not only_reserved -> Some Type | "unset" -> Some Unset | "upcast" when not only_reserved -> Some Upcast | "use" -> Some Use | "using" -> Some Using | "var" -> Some Var | "varray" when not only_reserved -> Some Varray | "vec" when not only_reserved -> Some Vec | "void" when not only_reserved -> Some Void | "with" when not only_reserved -> Some With | "where" when not only_reserved -> Some Where | "while" -> Some While | "yield" -> Some Yield | "null" when not only_reserved -> Some NullLiteral | "[" -> Some LeftBracket | "]" -> Some RightBracket | "(" -> Some LeftParen | ")" -> Some RightParen | "{" -> Some LeftBrace | "}" -> Some RightBrace | "." -> Some Dot | "->" -> Some MinusGreaterThan | "++" -> Some PlusPlus | "--" -> Some MinusMinus | "**" -> Some StarStar | "*" -> Some Star | "+" -> Some Plus | "-" -> Some Minus | "~" -> Some Tilde | "!" -> Some Exclamation | "$" -> Some Dollar | "/" -> Some Slash | "%" -> Some Percent | "<=>" -> Some LessThanEqualGreaterThan | "<<" -> Some LessThanLessThan | ">>" -> Some GreaterThanGreaterThan | "<" -> Some LessThan | ">" -> Some GreaterThan | "<=" -> Some LessThanEqual | ">=" -> Some GreaterThanEqual | "==" -> Some EqualEqual | "===" -> Some EqualEqualEqual | "!=" -> Some ExclamationEqual | "!==" -> Some ExclamationEqualEqual | "^" -> Some Carat | "|" -> Some Bar | "&" -> Some Ampersand | "&&" -> Some AmpersandAmpersand | "||" -> Some BarBar | "?" -> Some Question | "?as" -> Some QuestionAs | "?:" -> Some QuestionColon | "??" -> Some QuestionQuestion | "??=" -> Some QuestionQuestionEqual | ":" -> Some Colon | ";" -> Some Semicolon | "=" -> Some Equal | "**=" -> Some StarStarEqual | "*=" -> Some StarEqual | "/=" -> Some SlashEqual | "%=" -> Some PercentEqual | "+=" -> Some PlusEqual | "-=" -> Some MinusEqual | ".=" -> Some DotEqual | "<<=" -> Some LessThanLessThanEqual | ">>=" -> Some GreaterThanGreaterThanEqual | "&=" -> Some AmpersandEqual | "^=" -> Some CaratEqual | "|=" -> Some BarEqual | "," -> Some Comma | "@" -> Some At | "::" -> Some ColonColon | "=>" -> Some EqualGreaterThan | "==>" -> Some EqualEqualGreaterThan | "?->" -> Some QuestionMinusGreaterThan | "..." -> Some DotDotDot | "$$" -> Some DollarDollar | "|>" -> Some BarGreaterThan | "/>" -> Some SlashGreaterThan | "</" -> Some LessThanSlash | "<?" -> Some LessThanQuestion | "`" -> Some Backtick | "xhp" when not only_reserved -> Some XHP | "#" -> Some Hash | "readonly" -> Some Readonly | "internal" when not only_reserved -> Some Internal | "package" -> Some Package | "let" when not only_reserved -> Some Let | _ -> None let to_string kind = match kind with (* No text tokens *) | EndOfFile -> "end_of_file" (* Given text tokens *) | Abstract -> "abstract" | Arraykey -> "arraykey" | As -> "as" | Async -> "async" | Attribute -> "attribute" | Await -> "await" | Backslash -> "\\" | Binary -> "binary" | Bool -> "bool" | Boolean -> "boolean" | Break -> "break" | Case -> "case" | Catch -> "catch" | Category -> "category" | Children -> "children" | Class -> "class" | Classname -> "classname" | Clone -> "clone" | Concurrent -> "concurrent" | Const -> "const" | Construct -> "__construct" | Continue -> "continue" | Ctx -> "ctx" | Darray -> "darray" | Default -> "default" | Dict -> "dict" | Do -> "do" | Double -> "double" | Echo -> "echo" | Else -> "else" | Empty -> "empty" | Endif -> "endif" | Enum -> "enum" | Eval -> "eval" | Exports -> "exports" | Extends -> "extends" | Fallthrough -> "fallthrough" | Float -> "float" | File -> "file" | Final -> "final" | Finally -> "finally" | For -> "for" | Foreach -> "foreach" | Function -> "function" | Global -> "global" | If -> "if" | Implements -> "implements" | Imports -> "imports" | Include -> "include" | Include_once -> "include_once" | Inout -> "inout" | Instanceof -> "instanceof" | Insteadof -> "insteadof" | Int -> "int" | Integer -> "integer" | Interface -> "interface" | Is -> "is" | Isset -> "isset" | Keyset -> "keyset" | Lateinit -> "lateinit" | List -> "list" | Match -> "match" | Mixed -> "mixed" | Module -> "module" | Namespace -> "namespace" | New -> "new" | Newctx -> "newctx" | Newtype -> "newtype" | Noreturn -> "noreturn" | Num -> "num" | Parent -> "parent" | Print -> "print" | Private -> "private" | Protected -> "protected" | Public -> "public" | Real -> "real" | Reify -> "reify" | Require -> "require" | Require_once -> "require_once" | Required -> "required" | Resource -> "resource" | Return -> "return" | Self -> "self" | Shape -> "shape" | Static -> "static" | String -> "string" | Super -> "super" | Switch -> "switch" | This -> "this" | Throw -> "throw" | Trait -> "trait" | Try -> "try" | Tuple -> "tuple" | Type -> "type" | Unset -> "unset" | Upcast -> "upcast" | Use -> "use" | Using -> "using" | Var -> "var" | Varray -> "varray" | Vec -> "vec" | Void -> "void" | With -> "with" | Where -> "where" | While -> "while" | Yield -> "yield" | NullLiteral -> "null" | LeftBracket -> "[" | RightBracket -> "]" | LeftParen -> "(" | RightParen -> ")" | LeftBrace -> "{" | RightBrace -> "}" | Dot -> "." | MinusGreaterThan -> "->" | PlusPlus -> "++" | MinusMinus -> "--" | StarStar -> "**" | Star -> "*" | Plus -> "+" | Minus -> "-" | Tilde -> "~" | Exclamation -> "!" | Dollar -> "$" | Slash -> "/" | Percent -> "%" | LessThanEqualGreaterThan -> "<=>" | LessThanLessThan -> "<<" | GreaterThanGreaterThan -> ">>" | LessThan -> "<" | GreaterThan -> ">" | LessThanEqual -> "<=" | GreaterThanEqual -> ">=" | EqualEqual -> "==" | EqualEqualEqual -> "===" | ExclamationEqual -> "!=" | ExclamationEqualEqual -> "!==" | Carat -> "^" | Bar -> "|" | Ampersand -> "&" | AmpersandAmpersand -> "&&" | BarBar -> "||" | Question -> "?" | QuestionAs -> "?as" | QuestionColon -> "?:" | QuestionQuestion -> "??" | QuestionQuestionEqual -> "??=" | Colon -> ":" | Semicolon -> ";" | Equal -> "=" | StarStarEqual -> "**=" | StarEqual -> "*=" | SlashEqual -> "/=" | PercentEqual -> "%=" | PlusEqual -> "+=" | MinusEqual -> "-=" | DotEqual -> ".=" | LessThanLessThanEqual -> "<<=" | GreaterThanGreaterThanEqual -> ">>=" | AmpersandEqual -> "&=" | CaratEqual -> "^=" | BarEqual -> "|=" | Comma -> "," | At -> "@" | ColonColon -> "::" | EqualGreaterThan -> "=>" | EqualEqualGreaterThan -> "==>" | QuestionMinusGreaterThan -> "?->" | DotDotDot -> "..." | DollarDollar -> "$$" | BarGreaterThan -> "|>" | SlashGreaterThan -> "/>" | LessThanSlash -> "</" | LessThanQuestion -> "<?" | Backtick -> "`" | XHP -> "xhp" | Hash -> "#" | Readonly -> "readonly" | Internal -> "internal" | Package -> "package" | Let -> "let" (* Variable text tokens *) | ErrorToken -> "error_token" | Name -> "name" | Variable -> "variable" | DecimalLiteral -> "decimal_literal" | OctalLiteral -> "octal_literal" | HexadecimalLiteral -> "hexadecimal_literal" | BinaryLiteral -> "binary_literal" | FloatingLiteral -> "floating_literal" | SingleQuotedStringLiteral -> "single_quoted_string_literal" | DoubleQuotedStringLiteral -> "double_quoted_string_literal" | DoubleQuotedStringLiteralHead -> "double_quoted_string_literal_head" | StringLiteralBody -> "string_literal_body" | DoubleQuotedStringLiteralTail -> "double_quoted_string_literal_tail" | HeredocStringLiteral -> "heredoc_string_literal" | HeredocStringLiteralHead -> "heredoc_string_literal_head" | HeredocStringLiteralTail -> "heredoc_string_literal_tail" | NowdocStringLiteral -> "nowdoc_string_literal" | BooleanLiteral -> "boolean_literal" | XHPCategoryName -> "XHP_category_name" | XHPElementName -> "XHP_element_name" | XHPClassName -> "XHP_class_name" | XHPStringLiteral -> "XHP_string_literal" | XHPBody -> "XHP_body" | XHPComment -> "XHP_comment" | Hashbang -> "hashbang" let is_variable_text kind = match kind with | ErrorToken -> true | Name -> true | Variable -> true | DecimalLiteral -> true | OctalLiteral -> true | HexadecimalLiteral -> true | BinaryLiteral -> true | FloatingLiteral -> true | SingleQuotedStringLiteral -> true | DoubleQuotedStringLiteral -> true | DoubleQuotedStringLiteralHead -> true | StringLiteralBody -> true | DoubleQuotedStringLiteralTail -> true | HeredocStringLiteral -> true | HeredocStringLiteralHead -> true | HeredocStringLiteralTail -> true | NowdocStringLiteral -> true | BooleanLiteral -> true | XHPCategoryName -> true | XHPElementName -> true | XHPClassName -> true | XHPStringLiteral -> true | XHPBody -> true | XHPComment -> true | Hashbang -> true | _ -> false
OCaml
hhvm/hphp/hack/src/parser/full_fidelity_trivia_kind.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. An additional * directory. * ** * * THIS FILE IS @generated; DO NOT EDIT IT * To regenerate this file, run * * buck run //hphp/hack/src:generate_full_fidelity * ** * *) type t = | WhiteSpace | EndOfLine | DelimitedComment | SingleLineComment | FixMe | IgnoreError | FallThrough | ExtraTokenError [@@deriving show, enum, eq, sexp_of] let to_string kind = match kind with | WhiteSpace -> "whitespace" | EndOfLine -> "end_of_line" | DelimitedComment -> "delimited_comment" | SingleLineComment -> "single_line_comment" | FixMe -> "fix_me" | IgnoreError -> "ignore_error" | FallThrough -> "fall_through" | ExtraTokenError -> "extra_token_error"
OCaml
hhvm/hphp/hack/src/parser/hh_autoimport.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. * *) open Hh_prelude (** The names of autoimport types. *) let types = [ "AnyArray"; "AsyncFunctionWaitHandle"; "AsyncGenerator"; "AsyncGeneratorWaitHandle"; "AsyncIterator"; "AsyncKeyedIterator"; "Awaitable"; "AwaitAllWaitHandle"; "classname"; "Collection"; "ConcurrentWaitHandle"; "ConditionWaitHandle"; "Container"; "darray"; "dict"; "ExternalThreadEventWaitHandle"; "IMemoizeParam"; "UNSAFESingletonMemoizeParam"; "ImmMap"; "ImmSet"; "ImmVector"; "InvariantException"; "Iterable"; "Iterator"; "KeyedContainer"; "KeyedIterable"; "KeyedIterator"; "KeyedTraversable"; "keyset"; "Map"; "ObjprofObjectStats"; "ObjprofPathsStats"; "ObjprofStringStats"; "Pair"; "RescheduleWaitHandle"; "ResumableWaitHandle"; "Set"; "Shapes"; "SleepWaitHandle"; "StaticWaitHandle"; "supportdyn"; "Traversable"; "typename"; "TypeStructure"; "TypeStructureKind"; "varray_or_darray"; "varray"; "vec_or_dict"; "vec"; "Vector"; "WaitableWaitHandle"; "XenonSample"; ] (** The names of autoimport functions. *) let funcs = [ "asio_get_current_context_idx"; "asio_get_running_in_context"; "asio_get_running"; "class_meth"; "darray"; "dict"; "fun"; "heapgraph_create"; "heapgraph_dfs_edges"; "heapgraph_dfs_nodes"; "heapgraph_edge"; "heapgraph_foreach_edge"; "heapgraph_foreach_node"; "heapgraph_foreach_root"; "heapgraph_node_in_edges"; "heapgraph_node_out_edges"; "heapgraph_node"; "heapgraph_stats"; "idx"; "idx_readonly"; "inst_meth"; "invariant_callback_register"; "invariant_violation"; "invariant"; "is_darray"; "is_dict"; "is_keyset"; "is_varray"; "is_vec"; "keyset"; "meth_caller"; "objprof_get_data"; "objprof_get_paths"; "server_warmup_status"; "thread_mark_stack"; "thread_memory_stats"; "type_structure"; "type_structure_for_alias"; "varray"; "vec"; "xenon_get_data"; ] (** The names of autoimport constants. *) let consts = [] (** The names of autoimport namespaces. *) let namespaces = ["Rx"] (** Whether the given string is the name of an autoimport type. *) let is_hh_autoimport = let h = HashSet.of_list types in (fun x -> HashSet.mem h x) (** Strip any `HH\\` prefix from the provided string if the string is the name of a autoimport type. *) let strip_HH_namespace_if_autoimport id = match String.chop_prefix ~prefix:"HH\\" id with | Some stripped_id when is_hh_autoimport stripped_id -> stripped_id | _ -> id
OCaml Interface
hhvm/hphp/hack/src/parser/hh_autoimport.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. * *) (** The names of autoimport types. *) val types : string list (** The names of autoimport functions. *) val funcs : string list (** The names of autoimport constants. *) val consts : string list (** The names of autoimport namespaces. *) val namespaces : string list (** Strip any `HH\\` prefix from the provided string if the string is the name of a autoimport type. *) val strip_HH_namespace_if_autoimport : string -> string
Rust
hhvm/hphp/hack/src/parser/hh_autoimport.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::collections::BTreeMap; use lazy_static::lazy_static; lazy_static! { pub static ref TYPES_MAP: BTreeMap<String, String> = make_map(TYPES); pub static ref FUNCS_MAP: BTreeMap<String, String> = make_map(FUNCS); pub static ref CONSTS_MAP: BTreeMap<String, String> = make_map(CONSTS); pub static ref NAMESPACES_MAP: BTreeMap<String, String> = make_map(NAMESPACES); } pub static TYPES: &[&str] = &[ "AnyArray", "AsyncFunctionWaitHandle", "AsyncGenerator", "AsyncGeneratorWaitHandle", "AsyncIterator", "AsyncKeyedIterator", "Awaitable", "AwaitAllWaitHandle", "classname", "Collection", "ConcurrentWaitHandle", "ConditionWaitHandle", "Container", "darray", "dict", "ExternalThreadEventWaitHandle", "IMemoizeParam", "UNSAFESingletonMemoizeParam", "ImmMap", "ImmSet", "ImmVector", "InvariantException", "Iterable", "Iterator", "KeyedContainer", "KeyedIterable", "KeyedIterator", "KeyedTraversable", "keyset", "Map", "ObjprofObjectStats", "ObjprofPathsStats", "ObjprofStringStats", "Pair", "RescheduleWaitHandle", "ResumableWaitHandle", "Set", "Shapes", "SleepWaitHandle", "StaticWaitHandle", "supportdyn", "Traversable", "typename", "TypeStructure", "TypeStructureKind", "varray_or_darray", "varray", "vec_or_dict", "vec", "Vector", "WaitableWaitHandle", "XenonSample", ]; static FUNCS: &[&str] = &[ "asio_get_current_context_idx", "asio_get_running_in_context", "asio_get_running", "class_meth", "darray", "dict", "fun", "heapgraph_create", "heapgraph_dfs_edges", "heapgraph_dfs_nodes", "heapgraph_edge", "heapgraph_foreach_edge", "heapgraph_foreach_node", "heapgraph_foreach_root", "heapgraph_node_in_edges", "heapgraph_node_out_edges", "heapgraph_node", "heapgraph_stats", "idx", "idx_readonly", "inst_meth", "invariant_callback_register", "invariant_violation", "invariant", "is_darray", "is_dict", "is_keyset", "is_varray", "is_vec", "keyset", "meth_caller", "objprof_get_data", "objprof_get_paths", "package_exists", "server_warmup_status", "thread_mark_stack", "thread_memory_stats", "type_structure", "type_structure_for_alias", "varray", "vec", "xenon_get_data", ]; static CONSTS: &[&str] = &[]; pub static NAMESPACES: &[&str] = &["Rx"]; fn make_map(items: &[&str]) -> BTreeMap<String, String> { items.iter().fold(BTreeMap::new(), |mut map, s| { let prefix = "HH\\"; let v = String::with_capacity(prefix.len() + s.len()); map.insert(s.to_string(), v + prefix + s); map }) } pub fn is_hh_autoimport(s: &str) -> bool { TYPES_MAP.contains_key(s) } pub fn is_hh_autoimport_fun(s: &str) -> bool { FUNCS.contains(&s) } #[cfg(test)] mod tests { use crate::is_hh_autoimport; use crate::is_hh_autoimport_fun; #[test] fn test_is_hh_autoimport() { assert!(is_hh_autoimport("vec")); assert!(is_hh_autoimport("KeyedIterable")); assert!(!is_hh_autoimport("non-exisit")); assert!(is_hh_autoimport_fun("keyset")); assert!(!is_hh_autoimport_fun("KeyedIterable")); } }
OCaml
hhvm/hphp/hack/src/parser/ide_parser_cache.ml
(* * Copyright (c) 2018, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude module SyntaxTree = Full_fidelity_syntax_tree.WithSyntax (Full_fidelity_positioned_syntax) let is_active_ref : [ `Disabled | `Active | `Inactive ] ref = ref `Disabled let enable () = Hh_logger.log "Enabling Ide_parser_cache"; is_active_ref := `Inactive let is_enabled () = match !is_active_ref with | `Disabled -> false | _ -> true let is_active () = match !is_active_ref with | `Active -> true | _ -> false let activate () = if is_enabled () then is_active_ref := `Active let deactivate () = if is_enabled () then is_active_ref := `Inactive let with_ide_cache f = Utils.try_finally ~f: begin fun () -> activate (); f () end ~finally:deactivate module IdeAstCache = SharedMem.FreqCache (StringKey) (struct type t = Parser_return.t * Fixme_provider.fixme_map * Errors.t let description = "IdeAstCache" end) (struct let capacity = 10 end) module IdeCstCache = SharedMem.FreqCache (StringKey) (struct type t = SyntaxTree.t let description = "IdeCstCache" end) (struct let capacity = 10 end) let get_digest path content = let string_path = Relative_path.to_absolute path in Md5.(digest_string (string_path ^ content) |> to_binary) let get_cst source_text = assert (is_active ()); let digest = get_digest (Full_fidelity_source_text.file_path source_text) (Full_fidelity_source_text.text source_text) in match IdeCstCache.get digest with | Some cst -> cst | None -> let env = Full_fidelity_parser_env.default in let cst = SyntaxTree.make ~env source_text in IdeCstCache.add digest cst; cst let get_ast tcopt path content = assert (is_active ()); let digest = get_digest path content in match IdeAstCache.get digest with | Some (ast, fixmes, errors) -> Errors.merge_into_current errors; Fixme_provider.provide_hh_fixmes path fixmes; ast | None -> let (errors, ast) = Errors.do_ @@ fun () -> Full_fidelity_ast.defensive_program ~include_line_comments:true ~quick:false tcopt path content in Errors.merge_into_current errors; let fixmes = Fixme_provider.get_hh_fixmes path |> Option.value ~default:IMap.empty in IdeAstCache.add digest (ast, fixmes, errors); ast let get_ast_if_active tcopt path content = if not (is_active ()) then None else Some (get_ast tcopt path content)
OCaml Interface
hhvm/hphp/hack/src/parser/ide_parser_cache.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. * *) (* Main on/off switch used to control using this cache. You should not be calling * get_ast/get_cst methods without calling enable() first *) val enable : unit -> unit val is_enabled : unit -> bool (* To be on the safe side, we don't want ASTs from this cache to "leak" to non-IDE * scenarios (i.e. to be used to compute declarations that will be persisted in shared memory). * Activate/deactivate can be used to mark those "safe" sections, but it's up to the caller * to check if they really are safe. *) val activate : unit -> unit val deactivate : unit -> unit (* Wraps a method in activate / deactivate *) val with_ide_cache : (unit -> 'a) -> 'a (* Cache key assigned to the file with this path and contents *) val get_digest : Relative_path.t -> string -> string (* Gets the AST from cache (or compute it if missing). The cache is keyed by hash * of path and content, and we assume that all callers will pass in ParserOptions * that result in equivalent AST. * Under this assumption, it's safe never invalidate this cache. *) val get_ast : ParserOptions.t -> Relative_path.t -> string -> Parser_return.t (* Optional version of get_ast that can be used on code paths that are shared between * "safe" and "unsafe" code paths *) val get_ast_if_active : ParserOptions.t -> Relative_path.t -> string -> Parser_return.t option val get_cst : Full_fidelity_source_text.t -> Full_fidelity_syntax_tree.WithSyntax(Full_fidelity_positioned_syntax).t
Rust
hhvm/hphp/hack/src/parser/indexed_source_text.rs
// Copyright (c) 2019, Facebook, Inc. // All rights reserved. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::rc::Rc; use line_break_map::LineBreakMap; use crate::source_text::SourceText; #[derive(Debug)] pub struct IndexedSourceTextImpl<'a> { pub source_text: SourceText<'a>, offset_map: LineBreakMap, } #[derive(Clone, Debug)] pub struct IndexedSourceText<'a>(Rc<IndexedSourceTextImpl<'a>>); impl<'a> IndexedSourceText<'a> { pub fn new(source_text: SourceText<'a>) -> Self { let text = source_text.text(); Self(Rc::new(IndexedSourceTextImpl { source_text, offset_map: LineBreakMap::new(text), })) } pub fn source_text(&self) -> &SourceText<'a> { &self.0.source_text } pub fn offset_to_position(&self, offset: isize) -> (isize, isize) { self.0.offset_map.offset_to_position(offset) } pub fn relative_pos(&self, start_offset: usize, end_offset: usize) -> Pos { Pos { path: self.0.source_text.file_path_rc(), start: self.0.offset_map.offset_to_file_pos_triple(start_offset), end: self.0.offset_map.offset_to_file_pos_triple(end_offset), } } pub fn offset_to_file_pos_triple(&self, offset: usize) -> (usize, usize, usize) { self.0.offset_map.offset_to_file_pos_triple(offset) } } pub struct Pos { pub path: std::sync::Arc<relative_path::RelativePath>, /// The three usizes represent (lnum, bol, offset): /// - lnum: Line number. Starts at 1. /// - bol: Byte offset from beginning of file to the beginning of the line /// containing this position. The column number is therefore offset - bol. /// Starts at 0. /// - offset: Byte offset from the beginning of the file. Starts at 0. pub start: (usize, usize, usize), /// (lnum, bol, offset), as above pub end: (usize, usize, usize), }
OCaml
hhvm/hphp/hack/src/parser/lambda_analyzer.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. * *) open Hh_prelude module SourceText = Full_fidelity_source_text module Syntax = Full_fidelity_editable_positioned_syntax module Token = Syntax.Token module TokenKind = Full_fidelity_token_kind open Syntax (* We have a lambda in hand, and the chain of parents in its parse tree. We wish to know all the local variables which appear immediately in any parent that are used anywhere inside the lambda. These are the "outer variables" of the lambda. This is trickier than it sounds. Consider the first lambda here: function foo($a, $e) { $b = 123; m( ($b, $c, $f) ==> m($a, $b, $c, () ==> { ... $d = $e ... }), () ==> { ... $d = $b; ... }); } * $a is an outer variable of the lambda; it appears outside and is used inside. * $b is not an outer variable of the lambda. It appears outside, but the $b used inside the lambda is a different $b. * $c is not an outer variable of the lambda; it does not appear outside. * $d is not an outer variable of the lambda, even though it appears outside the lambda and is used inside the lambda. * $e is an outer variable; it appears outside, and is used indirectly inside. * $f is not an outer variable; it does not appear outside. The first problem we're going to solve is finding all the variables used *without recursing into child lambdas*. Variables which are declared as formal parameters are considered used; they are implicitly assigned a value. For our example above: * the variables used by foo are $a, $b and $e * the variables used by the first lambda are $a, $b, $c, $f * the variables used by the second lambda are $d and $e * the variables used by the third lambda are $b and $d TODO: We need to figure out how to make cases like { $x = 123; ... () ==> "${x}" ... } work correctly. String identity on locals doesn't really work here. *) let fold_no_lambdas folder acc node = let rec aux acc node = if is_lambda_expression node || is_anonymous_function node then acc else let acc = folder acc node in List.fold_left ~f:aux ~init:acc (Syntax.children node) in aux acc node let token_to_string node = match syntax node with | Token t -> Some (Token.text t) | _ -> None let param_name node = match syntax node with | ListItem { list_item = { syntax = ParameterDeclaration { parameter_name; _ }; _ }; _; } -> token_to_string parameter_name | _ -> None let use_name node = match syntax node with | ListItem { list_item = { syntax = Token _; _ } as list_item; _ } -> token_to_string list_item | _ -> None let rec get_params_list node = match syntax node with | FunctionDeclaration { function_declaration_header; _ } -> get_params_list function_declaration_header | FunctionDeclarationHeader { function_parameter_list; _ } -> function_parameter_list | LambdaExpression { lambda_signature; _ } -> get_params_list lambda_signature | LambdaSignature { lambda_parameters; _ } -> lambda_parameters | AnonymousFunction { anonymous_parameters; _ } -> anonymous_parameters | MethodishDeclaration { methodish_function_decl_header; _ } -> get_params_list methodish_function_decl_header | _ -> make_missing SourceText.empty 0 let get_params node = let param_list = get_params_list node in let param_list = syntax_node_to_list param_list in let param_list = List.filter_map param_list ~f:param_name in SSet.of_list param_list let get_body node = match syntax node with | FunctionDeclaration { function_body; _ } -> function_body | LambdaExpression { lambda_body; _ } -> lambda_body | AnonymousFunction { anonymous_body; _ } -> anonymous_body | MethodishDeclaration { methodish_function_body; _ } -> methodish_function_body | _ -> make_missing SourceText.empty 0 (* TODO: This does not consider situations like "${x}" as the use of a local.*) let add_local acc node = match syntax node with | Token ({ Token.kind = TokenKind.Variable; _ } as token) -> SSet.add (Token.text token) acc | _ -> acc (** * Returns a set of all local variables and parameters in a body * Excluded variables and parameters in lambdas * Locals are stripped of their initial `$` * Excludes `$this` *) let all_locals node = fold_no_lambdas add_local SSet.empty node |> SSet.remove "$this" let outer_from_use use_clause = match syntax use_clause with | AnonymousFunctionUseClause { anonymous_use_variables; _ } -> let use_list = syntax_node_to_list anonymous_use_variables in let use_list = List.filter_map use_list ~f:use_name in SSet.of_list use_list | _ -> SSet.empty let use_clause_variables node = match syntax node with | AnonymousFunction { anonymous_use; _ } -> outer_from_use anonymous_use | _ -> SSet.empty let local_variables acc node = let params = get_params node in let body = get_body node in let locals = fold_no_lambdas add_local params body in let used_vars = use_clause_variables node in let acc = SSet.union acc used_vars in SSet.union acc locals let filter_parents parents = (* We want all the parents that are relevant to computing outer variables. Since outer variables are indicated in a "use" clause of an anonymous function, we can stop looking when we encounter one. Otherwise, we just filter out anything that is not a lambda, function or method. *) let rec aux acc parents = match parents with | [] -> acc | h :: t -> begin match syntax h with | FunctionDeclaration _ | MethodishDeclaration _ | AnonymousFunction _ -> h :: acc | LambdaExpression _ -> aux (h :: acc) t | _ -> aux acc t end in List.rev (aux [] parents) let compute_outer_variables parents node = match syntax node with | AnonymousFunction { anonymous_use; _ } -> outer_from_use anonymous_use | _ -> let parents = filter_parents parents in List.fold_left parents ~f:local_variables ~init:SSet.empty let partition_used_locals parents node = (* Set of function parameters *) let params = get_params_list node |> syntax_node_to_list |> List.filter_map ~f:param_name in let param_set = SSet.of_list params in (* Set of all variables referenced in the body except for $this *) let all_used = fold_no_lambdas add_local SSet.empty (get_body node) |> SSet.remove "$this" in let all_outer = compute_outer_variables parents node in let used_outer = SSet.diff (SSet.inter all_used all_outer) param_set in let inner = SSet.diff all_used (SSet.union param_set used_outer) in let inner_strings = SSet.to_string inner in let used_outer_strings = SSet.to_string used_outer in let _ = (inner_strings, used_outer_strings) in (inner, used_outer, params)
OCaml
hhvm/hphp/hack/src/parser/lexable_positioned_token_sig.ml
(* * Copyright (c) 2017, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) module type LexablePositionedToken_S = sig module Trivia : module type of Full_fidelity_positioned_trivia include Lexable_token_sig.LexableToken_S with module Trivia := Trivia val text : t -> string val concatenate : t -> t -> t val trim_left : n:int -> t -> t val trim_right : n:int -> t -> t end
Rust
hhvm/hphp/hack/src/parser/lexable_token.rs
// Copyright (c) 2019, Facebook, Inc. // All rights reserved. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::fmt::Debug; use crate::lexable_trivia::LexableTrivia; use crate::positioned_trivia::PositionedTrivium; use crate::source_text::SourceText; use crate::token_kind::TokenKind; use crate::trivia_kind::TriviaKind; pub trait LexableToken: Clone + Debug { type Trivia: LexableTrivia; fn kind(&self) -> TokenKind; /// Returns the leading offset if meaningful /// (note: each implementor will either always return Some(offset) or always return None). fn leading_start_offset(&self) -> Option<usize>; fn width(&self) -> usize; fn leading_width(&self) -> usize; fn trailing_width(&self) -> usize; fn full_width(&self) -> usize; fn clone_leading(&self) -> Self::Trivia; fn clone_trailing(&self) -> Self::Trivia; fn leading_is_empty(&self) -> bool; fn trailing_is_empty(&self) -> bool; fn has_leading_trivia_kind(&self, kind: TriviaKind) -> bool; fn has_trailing_trivia_kind(&self, kind: TriviaKind) -> bool; fn has_trivia_kind(&self, kind: TriviaKind) -> bool { self.has_leading_trivia_kind(kind) || self.has_trailing_trivia_kind(kind) } fn into_trivia_and_width(self) -> (Self::Trivia, usize, Self::Trivia); } pub trait LexablePositionedToken: LexableToken where Self: Debug, { fn text<'b>(&self, source_text: &'b SourceText<'_>) -> &'b str; fn text_raw<'b>(&self, source_text: &'b SourceText<'_>) -> &'b [u8]; fn clone_value(&self) -> Self; fn positioned_leading(&self) -> &[PositionedTrivium]; fn positioned_trailing(&self) -> &[PositionedTrivium]; }
OCaml
hhvm/hphp/hack/src/parser/lexable_token_sig.ml
(* * Copyright (c) 2017, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) module TriviaKind = Full_fidelity_trivia_kind module type LexableToken_S = sig module Trivia : Lexable_trivia_sig.LexableTrivia_S type t [@@deriving show] val make : Full_fidelity_token_kind.t -> (* kind *) Full_fidelity_source_text.t -> (* source *) int -> (* offset *) int -> (* width *) Trivia.t list -> (* leading *) Trivia.t list -> (* trailing *) t val kind : t -> Full_fidelity_token_kind.t val leading_start_offset : t -> int val text : t -> string val source_text : t -> Full_fidelity_source_text.t val width : t -> int val trailing_width : t -> int val leading_width : t -> int val trailing : t -> Trivia.t list val leading : t -> Trivia.t list val with_leading : Trivia.t list -> t -> t val with_kind : t -> Full_fidelity_token_kind.t -> t val with_trailing : Trivia.t list -> t -> t val filter_leading_trivia_by_kind : t -> TriviaKind.t -> Trivia.t list val has_trivia_kind : t -> TriviaKind.t -> bool end
Rust
hhvm/hphp/hack/src/parser/lexable_trivia.rs
// Copyright (c) 2019, Facebook, Inc. // All rights reserved. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::fmt::Debug; use crate::trivia_kind::TriviaKind; pub trait LexableTrivia: Clone + Debug { type Trivium: LexableTrivium; fn is_empty(&self) -> bool; fn has_kind(&self, kind: TriviaKind) -> bool; fn push(&mut self, trivium: Self::Trivium); fn extend(&mut self, other: Self); #[inline] fn make_whitespace(offset: usize, width: usize) -> Self::Trivium { Self::Trivium::make_whitespace(offset, width) } #[inline] fn make_eol(offset: usize, width: usize) -> Self::Trivium { Self::Trivium::make_eol(offset, width) } #[inline] fn make_single_line_comment(offset: usize, width: usize) -> Self::Trivium { Self::Trivium::make_single_line_comment(offset, width) } #[inline] fn make_fallthrough(offset: usize, width: usize) -> Self::Trivium { Self::Trivium::make_fallthrough(offset, width) } #[inline] fn make_fix_me(offset: usize, width: usize) -> Self::Trivium { Self::Trivium::make_fix_me(offset, width) } #[inline] fn make_ignore_error(offset: usize, width: usize) -> Self::Trivium { Self::Trivium::make_ignore_error(offset, width) } #[inline] fn make_extra_token_error(offset: usize, width: usize) -> Self::Trivium { Self::Trivium::make_extra_token_error(offset, width) } #[inline] fn make_delimited_comment(offset: usize, width: usize) -> Self::Trivium { Self::Trivium::make_delimited_comment(offset, width) } } pub trait LexableTrivium: Clone + PartialEq + Debug { fn make_whitespace(offset: usize, width: usize) -> Self; fn make_eol(offset: usize, width: usize) -> Self; fn make_single_line_comment(offset: usize, width: usize) -> Self; fn make_fallthrough(offset: usize, width: usize) -> Self; fn make_fix_me(offset: usize, width: usize) -> Self; fn make_ignore_error(offset: usize, width: usize) -> Self; fn make_extra_token_error(offset: usize, width: usize) -> Self; fn make_delimited_comment(offset: usize, width: usize) -> Self; fn kind(&self) -> TriviaKind; fn width(&self) -> usize; }
OCaml
hhvm/hphp/hack/src/parser/lexable_trivia_sig.ml
(* * Copyright (c) 2017, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) module SourceText = Full_fidelity_source_text module TriviaKind = Full_fidelity_trivia_kind module type LexableTrivia_S = sig type t [@@deriving show] val make_whitespace : SourceText.t -> int -> int -> t val make_eol : SourceText.t -> int -> int -> t val make_single_line_comment : SourceText.t -> int -> int -> t val make_fallthrough : SourceText.t -> int -> int -> t val make_fix_me : SourceText.t -> int -> int -> t val make_ignore_error : SourceText.t -> int -> int -> t val make_extra_token_error : SourceText.t -> int -> int -> t val make_delimited_comment : SourceText.t -> int -> int -> t val kind : t -> TriviaKind.t val width : t -> int end