language
stringlengths
0
24
filename
stringlengths
9
214
code
stringlengths
99
9.93M
Markdown
hhvm/hphp/hack/manual/hack/12-generics/04-type-parameters.md
A type parameter is a placeholder for a type that is supplied when a generic type is instantiated, or a generic method or function is invoked. A type parameter is a compile-time construct. At run-time, each type parameter is matched to a run-time type that was specified by a type argument. The name of a type parameter is visible from its point of definition through the end of the type, method, or function declaration on which it is defined. However, the name does not conflict with a name of the same spelling used in non-type contexts (such as the names of a class constant, an attribute, a method, an enum constant, or a namespace). All type-parameter names *must* begin with the letter T. In the following case, class `Vector` has one type parameter, `Tv`. Method `map` also has one type parameter, `Tu`. ```Hack no-extract final class Vector<Tv> implements MutableVector<Tv> { // ... public function map<Tu>((function(Tv): Tu) $callback): Vector<Tu> { ... } } ``` In the following case, class `Map` has two type parameters, `Tk` and `Tv`. Method `zip` has one, `Tu`. ```Hack no-extract final class Map<Tk, Tv> implements MutableMap<Tk, Tv> { // ... public function zip<Tu>(Traversable<Tu> $iter): Map<Tk, Pair<Tv, Tu>> { ... } } ``` In the following case, function `max_value` has one type parameter, `T`. ```Hack function max_value<T>(T $p1, T $p2): T { throw new Exception("unimplemented"); } ``` Generic type constraints are discussed in [type constraints](type-constraints.md).
Markdown
hhvm/hphp/hack/manual/hack/12-generics/07-type-constraints.md
A *type constraint* on a generic type parameter indicates a requirement that a type must fulfill in order to be accepted as a type argument for that type parameter. (For example, it might have to be a given class type or a subtype of that class type, or it might have to implement a given interface.) A constraint can have one of three forms: * `T as sometype`, meaning that `T` must be a subtype of `sometype` * `T super sometype`, meaning that `T` must be a supertype of `sometype` * `T = sometype`, meaning that `T` must be equivalent to `sometype`. (This is like saying both `T as sometype` *and* `T super sometype`.) Consider the following example in which function `max_val` has one type parameter, `T`, and that has a constraint, `num`: ```Hack function max_val<T as num>(T $p1, T $p2): T { return $p1 > $p2 ? $p1 : $p2; } <<__EntryPoint>> function main(): void { echo "max_val(10, 20) = ".max_val(10, 20)."\n"; echo "max_val(15.6, -20.78) = ".max_val(15.6, -20.78)."\n"; } ``` Without the `num` constraint, the expression `$p1 > $p2` is ill-formed, as a greater-than operator is not defined for all types. By constraining the type of `T` to `num`, we limit `T` to being an `int` or `float`, both of which do have that operator defined. Unlike an `as` constraint, `T super U` asserts that `T` must be a supertype of `U`. This kind of constraint is rather exotic, but solves an interesting problem encountered when multiple types "collide". Here is an example of how it's used on method `concat` in the library interface type `ConstVector`: ```Hack no-extract interface ConstVector<+T> { public function concat<Tu super T>(ConstVector<Tu> $x): ConstVector<Tu>; // ... } ``` Consider the case in which we call `concat` to concatenate a `Vector<float>` and a `Vector<int>`. As these have a common supertype, `num`, the `super` constraint allows the checker to determine that `num` is the inferred type of `Tu`. Now, while a type parameter on a class can be annotated to require that it is a subtype or supertype of a particular type, for generic parameters on classes, constraints on the type parameters can be assumed in *any* method in the class. But sometimes some methods want to use some features of the type parameter, and others want to use some different features, and not all instances of the class will satisfy all constraints. This can be done by specifying constraints that are *local* to particular methods. For example: ```Hack no-extract class MyWidget<Telem> { public function showIt(): void where Telem as IPrintable { ... } public function countIt(): int where Telem as ICountable { ... } } ``` Constraints can make use of the type parameter itself. They can also make use of generic type parameters on the method. For example: ```Hack class MyList<T> { public function flatten<Tu>(): MyList<Tu> where T = MyList<Tu> { throw new Exception('unimplemented'); } } ``` Here we might create a list of lists of int, of type `MyList<MyList<int>>`, and then invoke `flatten` on it to get a `MyList<int>`. Here's another example: ```Hack class MyList<T> { public function compact<Tu>(): MyList<Tu> where T = ?Tu { throw new Exception('unimplemented'); } } ``` A `where` constraint permits multiple constraints supported; just separate the constraints with commas. For example: ```Hack no-extract class SomeClass<T> { function foo(T $x) where T as MyInterface, T as MyOtherInterface } ``` If a method overrides another method that has declared `where` constraints, it's necessary to redeclare those constraints, but only if they are actually used by the overriding method. (It's valid, and reasonable, to require less of the overriding method.)
Markdown
hhvm/hphp/hack/manual/hack/12-generics/10-variance.md
Hack supports both generic *covariance* and *contravariance* on a type parameter. Each generic parameter can optionally be marked separately with a variance indicator: * `+` for covariance * `-` for contravariance If no variance is indicated, the parameter is invariant. ## Covariance If `Foo<int>` is a subtype of `Foo<num>`, then `Foo` is covariant on `T`. 'co' means 'with'; and the subtype relationship of the generic type goes with the subtype relationship of arguments to a covariant type parameter. Here is an example: ```Hack // This class is readonly. Had we put in a setter for $this->t, we could not // use covariance. e.g., if we had function setMe(T $x), you would get this // cov.php:9:25,25: Illegal usage of a covariant type parameter (Typing[4120]) // cov.php:7:10,10: This is where the parameter was declared as covariant (+) // cov.php:9:25,25: Function parameters are contravariant class C<+T> { public function __construct(private T $t) {} } class Animal {} class Cat extends Animal {} function f(C<Animal> $p1): void { \var_dump($p1); } function g(varray<Animal> $p1): void { \var_dump($p1); } <<__EntryPoint>> function run(): void { f(new C(new Animal())); f(new C(new Cat())); // accepted g(varray[new Animal(), new Animal()]); g(varray[new Cat(), new Cat(), new Animal()]); // arrays are covariant } ``` A covariant type parameter is for read-only types. Thus, if the type can somehow be set, then you cannot use covariance. Covariance cannot be used as the type of a parameter on any method, or as the type of any mutable property, in that class. ## Contravariance If `Foo<num>` is a subtype of `Foo<int>`, then `Foo` is contravariant on `T`. 'contra' means 'against'; and the subtype relationship of the generic type goes against the subtype relationship of arguments to a contravariant type parameter. Here is an example: ```Hack // This class is write only. Had we put in a getter for $this->t, we could not // use contravariance. e.g., if we had function getMe(T $x): T, you would get // con.php:10:28,28: Illegal usage of a contravariant type // parameter (Typing[4121]) // con.php:5:10,10: This is where the parameter was declared as // contravariant (-) // con.php:10:28,28: Function return types are covariant class C<-T> { public function __construct(private T $t) {} public function set_me(T $val): void { $this->t = $val; } } class Animal {} class Cat extends Animal {} <<__EntryPoint>> function main(): void { $animal = new Animal(); $cat = new Cat(); $c = new C($cat); // calling set_me with Animal on an instance of C that was initialized with Cat $c->set_me($animal); \var_dump($c); } ``` A contravariant type parameter is for write-only types. Thus, if the type can somehow be read, then you cannot use contravariant. (e.g., serialization functions are a good use case). A contravariant type parameter cannot be used as the return type of any method in that class.
Markdown
hhvm/hphp/hack/manual/hack/12-generics/19-type-erasure.md
Parameterized types with generics give you type safety without runtime checks. Generic type information is not available at runtime: this is called "erasure". If you need this information, consider using [reified generics](reified-generics). ```Hack function takes_ints(vec<int> $items): vec<int> { return $items; } ``` When the type checker runs, a call `takes_ints(vec["hello"])` will produce a type error. At runtime, since the parameter `int` is erased, we only check that the argument and return type is a `vec`. ## Awaitable Types For async functions, Hack will also enforce the wrapped return type at runtime. For example, the following function will produce a runtime error: ```Hack error async function my_foo(): Awaitable<int> { return "not an int"; } ``` ## Erasure Limitations Erasure prevents you using a generic type parameter `T` in the following situations: * Creating instances: `new T()` * Calling static methods: `T::aStaticMethod()` * Type checks: `is T` * As the type of a static property. * As the type of the exception in a catch block: `catch (T $exception)` For passing around class names for instantiation, Hack provides [`classname<T>`](../built-in-types/classname.md) that extends the representation of `Foo::class`.
Markdown
hhvm/hphp/hack/manual/hack/13-contexts-and-capabilities/01-introduction.md
**Note:** Context and capabilities are enabled by default since [HHVM 4.93](https://hhvm.com/blog/2021/01/19/hhvm-4.93.html). Contexts and capabilities provide a way to specify a set of capabilities for a function's implementation and a permission system for its callers. These capabilities may be in terms of what functions may be used in the implementation (e.g. a pure function cannot call non-pure functions), or in terms of other language features (e.g. a pure function can not write properties on `$this`). Capabilities are permissions or descriptions of a permission. For example, one might consider the ability to do IO or access globals as capabilities. Contexts are a higher level representation of a set of capabilities. A function may be comprised of one or more contexts which represent the set union of the underlying capabilities. ## Defining contexts and capabilities At present, all declarations of contexts and capabilities live within the typechecker and runtime. There are no plans to change this in the immediate future. ## Basic Declarations A function or method may optionally choose to list one or more contexts: ```hack no-extract function no_listed_contexts(): void {/* some fn body */} function empty_context()[]: void {/* some fn body */} function one_context()[C]: void {/* some fn body */} function many_context()[C1, C2, Cn]: void {/* some fn body */} ``` There exists a context named `defaults` that represents the set of capabilities present in a function prior to the introduction of this feature. When a function is not annotated with a context list, it implicitly received a list containing only the default context. The above declaration of `no_listed_contexts` is fully equivalent to the following: ```hack function no_listed_contexts()[defaults]: void {/* some fn body */} ``` Additionally, the context list may appear in function types: ```hack no-extract function has_fn_args( (function (): void) $no_list, (function ()[io, rand]: void) $list, (function ()[]: void) $empty_list, ): void {/* some fn body */} ``` ## Interaction of Contextful Functions In order to invoke a function, one must have access to all capabilities required by the callee. However, the caller may have more capabilities than is required by the callee, in which case simply not all capabilities are "passed" to the callee. In the following example, assume the existence of a `rand` context representing the capability set `{Rand}`, an `io` context representing the capability set `{IO}`, and that the `defaults` contexts represents the capability set `{Rand, IO}`. ```hack no-extract /* has {} capability set */ function pure_fun()[]: void { return; } function rand_int()[rand]: int { return HH\Lib\PseudoRandom\int(); } function rand_fun()[rand]: void { pure_fun(); // fine: {} ⊆ {Rand} rand_int(); // fine: {Rand} ⊆ {Rand} } // recall that this has the `defaults` context function unannotated_fun(): void { rand_fun(); // fine: {Rand} ⊆ {IO, Rand,} } ``` ## Parameterized Contexts While most contexts and capabilities represent the binary options of existence and lack thereof, it is also possible for either/both to be parameterized. In the following example, assume the existence of a `throws<T>` context representing the capability set `{Throws<T>}`. Rather than describing that a function *can* throw, this would describe which classes of exceptions a function may throw. In that scenario, the context would require a parameter representing the exception class: `throws<-T as Exception>`. ```hack no-extract function throws_foo_exception()[throws<FooException>]: void { // {Throws<FooException>} throw new FooException(); } function throws_bar_exception()[throws<BarException>]: void { // {Throws<BarException>} throw new BarException(); } function throws_foo_or_bar_exception(bool $cond)[ throws<FooException>, throws<BarException> // {Throws<FooException>, Throws<BarException>} ]: void { if ($cond) { throws_foo_exception(); } else { throws_bar_exception(); } } ``` The above would indicate that throws_foo_or_bar_exception may throw any of the listed exception classes. # Implications for Backwards Compatibility We may add additional capabilities in the future. As capabilities are specified in terms of what's permitted rather than what is not, the more restrictive your capability annotations are, the more likely it is that future changes will be incompatible with your code. This is especially true for functions that have the empty capability set. This should be considered as a tradeoff against increased confidence in more restricted code.
Markdown
hhvm/hphp/hack/manual/hack/13-contexts-and-capabilities/02-local-operations.md
**Note:** Context and capabilities are enabled by default since [HHVM 4.93](https://hhvm.com/blog/2021/01/19/hhvm-4.93.html). The existence of a capability (or lack thereof) within the contexts of a function plays a direct role in the operations allowed within that function. Consider the following potential (although not necessarily planned) contexts (with implied matching capabilities): * `throws<T>`, representing the permission to throw an exception type `Te <: T` * `io`, representing the permission to do io * `statics`, representing the permission to access static members and global variables * `write_prop`, representing the permission to mutate properties of objects * `dynamic`, representing the permission to cast a value to the `dynamic` type In all of the below cases, the relevant local operations successfully typecheck due to the matching capabilities within the context of the function. ```hack no-extract function io_good()[io]: void { echo "good"; // ok print "also ok"; // also ok } ``` ```hack no-extract class FooException extends Exception {} class FooChildException extends FooException {} class BarException extends Exception {} function throws_foo_exception()[throws<FooException>]: void { throw new FooException(); // ok: FooException <: FooException throw new FooChildException(); // ok: FooChildException <: FooException } function throws_bar_exception()[throws<BarException>]: void { throw new BarException(); // ok: BarException <: BarException } function throws_foo_and_bar_exceptions()[throws<FooException>, throws<BarException>]: void { throw new FooException(); // ok: FooException <: FooException throw new FooChildException(); // ok: FooChildException <: FooException throw new BarException(); // ok: BarException <: BarException } ``` ```hack no-extract class HasAStatic { public static int $i = 0; } function reads_and_writes_static()[statics]: void { HasAStatic::$i++; } ``` ```hack class SomeClass { public int $i = 0; } function reads_and_writes_prop(SomeClass $sc)[write_props]: void { $sc->i++; } ``` ```hack no-extract function casts_to_dynamic(int $in)[dynamic]: void { invokes_off_dynamic($in as dynamic); } function invokes_off_dynamic(dynamic $in)[]: void { $in->thisIsbananasAndDefinitelyThrowsButTypechecks(); } ```
Markdown
hhvm/hphp/hack/manual/hack/13-contexts-and-capabilities/03-closures.md
**Note:** Context and capabilities are enabled by default since [HHVM 4.93](https://hhvm.com/blog/2021/01/19/hhvm-4.93.html). As with standard functions, closures may optionally choose to list one or more contexts. Note that the outer function may or may not have its own context list. Lambdas wishing to specify a list of contexts must include a (possibly empty) parenthesized argument list. ```hack no-extract function some_function(): void { $no_list = () ==> {/* some fn body */}; $single = ()[C] ==> {/* some fn body */}; $multiple = ()[C1, C2, Cn] ==> {/* some fn body */}; $with_types = ()[C]: void ==> {/* some fn body */}; // legacy functions work too $legacy = function()[C]: void {}; } ``` By default, closures require the same capabilities as the context in which they are created. ```hack no-extract function foo()[io]: void { // scope has {IO} $callable1 = () ==> {/* some fn body */}; // requires {IO} - By far the most common usage } ``` Explicitly annotating the closure can be used to opt-out of this implicit behaviour. This is most useful when requiring the capabilities of the outer scope result in unnecessary restrictions, such as if the closure is returned rather than being invoked within the enclosing scope. ```hack no-extract function foo()[io]: void { // scope has {IO} $callable = ()[] ==> {/* some fn body */}; // requires {} $uncallable1 = ()[rand] ==> {/* some fn body */}; // requires {Rand} $uncallable2 = ()[defaults] ==> {/* some fn body */}; // requires the default set } ``` Note that in the previous example, `$uncallable1` cannot be called as foo cannot provide the required Rand capability. `$callable` is invocable because it requires strictly fewer capabilities than `foo` can provide.
Markdown
hhvm/hphp/hack/manual/hack/13-contexts-and-capabilities/04-higher-order-functions.md
**Note:** Context and capabilities are enabled by default since [HHVM 4.93](https://hhvm.com/blog/2021/01/19/hhvm-4.93.html). One may define a higher order function whose context depends on the dynamic context of one or more passed in function arguments. ```hack function has_dependent_fn_arg( (function()[_]: void) $f, )[ctx $f]: void { /* some code */ $f(); /* more code */ } ``` One may reference the dependent context of a function argument in later arguments as well as in the return type. ```hack no-extract function has_double_dependent_fn_arg( (function()[_]: void) $f1, (function()[ctx $f1]: void) $f2, )[rand, ctx $f1]: void { $f1(); $f2(); } function has_dependent_return( (function()[_]: void) $f, )[ctx $f, io]: (function()[ctx $f]: void) { $f(); return $f; } ``` The semantics of the argument-dependent-context are such that the higher order function's type is specialized per invocation. ```hack no-extract function callee( (function()[_]: void) $f, )[rand, ctx $f]: void { /* some code */ $f(); /* more code */ } function caller()[io, rand]: void { // pass pure closure callee(()[] ==> {/* some fn body */}); // specialized callee is {Rand} // pass {IO} closure callee(()[io] ==> {echo "output"; }); // specialized callee is {Rand, IO} // pass {IO, Rand} closure callee(() ==> {/* some fn body */}); // callee is {Rand, IO} } ``` Note that this suggests and requires that all other statements within `callee` require only the Rand capability, as the actual capabilities of the passed argument cannot be depended upon to be any specific capability.
Markdown
hhvm/hphp/hack/manual/hack/13-contexts-and-capabilities/05-contexts-and-subtyping.md
**Note:** Context and capabilities are enabled by default since [HHVM 4.93](https://hhvm.com/blog/2021/01/19/hhvm-4.93.html). Capabilities are contravariant. This implies that a closure that requires a set of capabilities S<sub>a</sub> may be passed where the expected type is a function that requires S<sub>b</sub> as long as S<sub>a</sub> ⊆ S<sub>b</sub>. For the following example, assume that the default context includes *at least* {Rand, IO} ```hack no-extract function requires_rand_io_arg((function()[rand, io]: void) $f): void { $f(); } function caller(): void { // passing a function that requires fewer capabilities requires_rand_io_arg(()[rand] ==> {/* some fn body */}); // passing a function that requires no capabilities requires_rand_io_arg(()[] ==> {/* some fn body */}); } ``` Additionally, this has the standard implication on inheritance hierarchies. Note that if S<sub>a</sub> ⊆ S<sub>b</sub> it is the case that S<sub>b</sub> is a subtype of S<sub>a</sub>. For the following, assume the default set contains {IO, Rand, Throws<mixed>}. ```hack no-extract class Parent_ { public function maybeRand()[rand]: void {/* some fn body */} // {Rand} public function maybePure(): void {/* some fn body */} // {Throws<mixed>, IO, Rand} } class Mid extends Parent_ { public function maybeRand()[rand]: void {/* some fn body */} // {Rand} -> fine {Rand} ⊆ {Rand} public function maybePure()[io]: void {/* some fn body */} // {IO} -> fine {IO} ⊆ {Throws<mixed>, IO, Rand} } class Child extends Mid { public function maybeRand()[]: void {/* some fn body */} // {} -> fine {} ⊆ {Rand} public function maybePure()[]: void {/* some fn body */} // {} -> fine {} ⊆ {IO} } ``` ### Capability subtyping In reality, there may also exist a subtyping relationship between capabilities. Thus, whenever some capability B that is subtype of capability A is available, any function or operation that requires A may be called or performed, respectively. This works identically to standard type subtyping. For the following, assume that the following contexts and capabilities exist: Rand, ReadFile <: Rand, rand: {Rand}, readfile: {Readfile} ```hack no-extract function requires_rand()[rand]: void {/* some fn body */} function has_readfile()[readfile]: void { requires_rand(); // fine {readfile} ⊆ {Rand} since readfile <: rand } ```
Markdown
hhvm/hphp/hack/manual/hack/13-contexts-and-capabilities/06-context-constants.md
**Note:** Context and capabilities are enabled by default since [HHVM 4.93](https://hhvm.com/blog/2021/01/19/hhvm-4.93.html). **Note:** Context constant *constraints* are available since HHVM 4.108. Classes and interfaces may define context constants: ```hack no-extract class WithConstant { const ctx C = [io]; public function has_io()[self::C]: void { echo "I have IO!"; } } ``` They may be abstract, ```hack interface IWithConstant { abstract const ctx C; } ``` may have one or more bounds, ```hack no-extract abstract class WithConstant { // Subclasses must require *at least* [io] abstract const ctx CAnotherOne as [io]; // Subclasses must require *at most* [defaults] abstract const ctx COne super [defaults]; // Subclasses must require *at most* [defaults] and *at least* [io, rand] abstract const ctx CMany super [defaults] as [io, rand]; } ``` and may have defaults, though only when abstract ```hack no-extract interface IWithConstant { abstract const ctx C = [defaults]; abstract const ctx CWithBound super [defaults] = [io]; } ``` When inheriting a class containing a context constant with a default, the first non-abstract class that doesn’t define an implementation of that constant gets the default synthesized for it. One may define a member function whose context depends on the `this` type or the exact value of context constant. ```hack no-extract class ClassWithConstant { const ctx C = [io]; } abstract class AnotherClassWithConstant { abstract const ctx C; abstract public function usesC()[this::C, ClassWithConstant::C]: void; } ``` One may define a function whose context depends on the dynamic context constant of one or more passed in arguments. ```hack no-extract function uses_const_ctx(SomeClassWithConstant $t)[$t::C]: void { $t->usesC(); } ``` One may reference the dependent context constant of a argument in later arguments as well as in the return type. ```hack no-extract function uses_const_ctx_more( SomeClassWithConstant $t, (function()[$t::C]: void) $f )[$t::C]: (function()[$t::C]: void) { $f(); $t->usesC(); return $f; } ```
Markdown
hhvm/hphp/hack/manual/hack/13-contexts-and-capabilities/07-dependent-contexts-continued.md
**Note:** Context and capabilities are enabled by default since [HHVM 4.93](https://hhvm.com/blog/2021/01/19/hhvm-4.93.html). Dependent contexts may be accessed off of nullable parameters. If the dynamic value of the parameter is null, then the capability set required by that parameter is empty. ```hack no-extract function type_const( ?SomeClassWithConstant $t, )[$t::C]: void { $t?->foo(); } function fn_arg( ?(function()[_]: void) $f, )[ctx $f]: void { if ($f is nonnull) { $f(); } } ``` Parameters used for accessing a dependent context may not be reassigned. ```hack no-extract function nope(SomeClassWithConstant $t, (function()[_]: void) $f)[$t::C, ctx $f]: void { // both disallowed $t = get_some_other_value(); $f = get_some_other_value(); } ``` Dependent contexts may not be referenced within the body of a function. This restriction may be relaxed in a future version. ```hack no-extract function f( (function()[_]: void $f, SomeClassWithConstant $t, )[rand, ctx $f, $t::C]: void { (()[ctx $f] ==> 1)(); // Disallowed (()[$t::C] ==> 1)(); // Disallowed (()[rand] ==> 1)(); // Allowed, not a dependent context (()[] ==> 1)(); // Allowed (() ==> 1)(); // Allowed. Note that this is logically equivalent to [rand, ctx $f, $t::C] } ```
Markdown
hhvm/hphp/hack/manual/hack/13-contexts-and-capabilities/08-available-contexts-and-capabilities.md
**Note:** Context and capabilities are enabled by default since [HHVM 4.93](https://hhvm.com/blog/2021/01/19/hhvm-4.93.html). The following contexts and capabilities are implemented at present. ## Capabilities ### IO This gates the ability to use the `echo` and `print` intrinsics within function bodies. Additionally, built-in functions that perform output operations such as file writes and DB reads will require this capablity. ```Hack function does_echo_and_print(): void { echo 'like this'; print 'or like this'; } ``` ### WriteProperty This gates the ability to modify objects within function bodies. Built-in functions that modify their inputs or methods that modify `$this` will require this capability. At present, all constructors have the ability to modify `$this`. Note that this does *not* imply that constructors can call functions requiring the WriteProperty capability. ```Hack // Valid example class SomeClass { public string $s = ''; public function modifyThis()[write_props]: void { $this->s = 'this applies as well'; } } function can_write_props(SomeClass $sc)[write_props]: void { $sc->s = 'like this'; $sc2 = new SomeClass(); $sc2->s = 'or like this'; } ``` ```Hack error // Invalid example class SomeClass { public string $s = ''; public function modifyThis()[]: void { // pure (empty context list) $this->s = 'this applies as well'; } } function pure_function(SomeClass $sc)[]: void { $sc->s = 'like this'; } ``` Hack Collections, being objects, require this capability to use the array access operator in a write context. ```Hack function modify_collection()[write_props]: void { $v = Vector {}; $v[] = 'like this'; $m = Map {}; $m['or'] = 'like this'; } ``` ### AccessGlobals This gates the ability to access static variables and globals. Built-in functions that make use of mutable global state or expose the php-style superglobals will require this capability. ```Hack // Valid example class SomeClass { public static string $s = ''; public function accessStatic()[globals]: void { self::$s; // like this } } function access_static()[globals]: void { SomeClass::$s; // or like this } ``` ```Hack error // Invalid example class SomeClass { public static string $s = ''; public function pureMethod()[]: void { self::$s; // like this } } function pure_function()[]: void { SomeClass::$s; // or like this } ``` ## Contexts - `defaults` represents the capability set {IO, WriteProperty, AccessGlobals}. - `write_props` represents the capability set {WriteProperty}. - `globals` represents the capability set {AccessGlobals}. ### The Empty List The empty context list, `[]`, has no capabilities. A function with no capabilities is the closest thing Hack has to 'pure' functions. As additional capabilities are added to Hack in the future, the restriction on these functions will increase. As such, this is sometimes referred to as the 'pure context'.
Markdown
hhvm/hphp/hack/manual/hack/14-reified-generics/01-introduction.md
**Topics covered in this section** * [Reified Generics](reified-generics.md) * [Reified Generics Migration](reified-generics-migration.md)
Markdown
hhvm/hphp/hack/manual/hack/14-reified-generics/02-reified-generics.md
# Reified Generics A _Reified Generic_ is a [Generic](/hack/generics/some-basics) with type information accessible at runtime. ## Introduction Generics are currently implemented in HHVM through erasure, in which the runtime drops all information about generics. This means that generics are not available at runtime. Although the typechecker is able to use the generic types for static typechecking, we are unable to enforce generic types at runtime. In Hack, generics are opt-in. The goal of opt-in reified generics is to bridge the gap between generics and runtime availability while keeping erasure available to maintain performance when reification is not needed. To mark a generic as reified, simply add the `reify` keyword at the declaration site. ## Parameter and return type verification ```hack no-extract class C<reify T> {} function f(C<int> $c): void {} <<__EntryPoint>> function main(): void { $c1 = new C<int>(); f($c1); // success $c2 = new C<string>(); f($c2); // parameter type hint violation } ``` The reified type parameter is checked as well: ```hack no-extract class C<reify T> {} function f<reify T>(T $x): C<T> { return new C<int>(); } <<__EntryPoint>> function main(): void { f<int>(1); // success f<int>("yep"); // parameter type hint violation f<string>("yep"); // return type hint violation } ``` ## Type testing and assertion with `is` and `as` expressions Suppose you have a `vec<mixed>` and you want to extract all types `T` from it. Prior to reified generics, you'd need to implement a new function for each type `T` but with reified generics you can do this in a generic way. Start by adding the keyword `reify` to the type parameter list. ```Hack function filter<<<__Enforceable>> reify T>(vec<mixed> $list): vec<T> { $ret = vec[]; foreach ($list as $elem) { if ($elem is T) { $ret[] = $elem; } } return $ret; } <<__EntryPoint>> function main(): void { filter<int>(vec[1, "hi", true]); // => vec[1] filter<string>(vec[1, "hi", true]); // => vec["hi"] } ``` Notice that the reified type parameter has the attribute `<<__Enforceable>>`. In order to use type testing and type assertion, the reified type parameter must be marked as `<<__Enforceable>>`, which means that we can fully enforce this type parameter, i.e. it does not contain any erased generics, not a function type, etc. ```Hack no-extract class A {} class B<reify T> {} class C<reify Ta, Tb> {} int // enforceable A // enforceable B<int> // enforceable B<A> // enforceable C<int, string> // NOT enforceable as C's second generic is erased ``` ## Creating an instance of a class with `new` Prior to reified generics, in order to create a new instance of a class without a constant class name, you'd need to pass it as `classname<T>` which is not type safe. In the runtime, classnames are strings. ```hack error <<__ConsistentConstruct>> abstract class A {} class B extends A {} class C extends A {} function f<<<__Newable>> reify T as A>(): T { return new T(); } <<__EntryPoint>> function main(): void { f<A>(); // not newable since it is abstract class f<B>(); // success f<C>(); // success } ``` Notice that the reified type parameter has the attribute `<<__Newable>>`. In order for a type to be `<<__Newable>>`, the type must represent a class that's not abstract and has a consistent constructor or be a final class. Creating a new instance using the reified generics also carries across the generics given. For example, ```Hack error final class A<reify T> {} function f<<<__Newable>> reify T as A<string>>(): A<string> { return new T(); } function demo(): void { // creates a new A<int> and since f's return type is A<string>, // this raises a type hint violation f<A<int>>(); } ``` ## Accessing a class constant / static class method ```Hack class C { const string class_const = "hi"; public static function h<reify T>(): void {} } // Without reified generics function f<T as C>(classname<T> $x): void { $x::class_const; $x::h<int>(); } // With reified generics function g<reify T as C>(): void { T::class_const; T::h<int>(); } ``` Accessing static class properties (`T::$class_property`) is currently not supported. ## Hack Arrays Hack Arrays can be used as inner type for classes since we do not need to check whether each element of the `vec` is `string`. Look at the limitations section for more information on when Hack Arrays cannot be used. ```Hack error class Box<reify T> {} function foo(): Box<vec<string>> { return new Box<vec<int>>(); // Type hint violation } ``` # Limitations * No support for subtyping (reified type parameter on classes are invariant, they cannot be co/contra-variant ```Hack error class C<reify +Ta> {} // Cannot make the generic covariant ``` * Static class methods cannot use the reified type parameter of its class ```Hack error class C<reify T> { public static function f(): void { return new T(); // Cannot use T } } ``` * Hack arrays cannot be reified when used as containers with `__Enforceable` or `__Newable` ```Hack error function f<<<__Enforceable>> reify T>(T $x): void { $x is vec<int>; // Cannot use vec<int> $x is T; } function demo(): void { f<vec<int>>(); // not enforceable } ``` but can be used as inner type for classes * If a type parameter is reified, it must be provided at all call sites; it cannot be inferred. ```Hack error function f<reify T>(): void {} function foo(): void { f(); // need to provide the generics here } ``` # Migration Features In order to make migrating to reified generics easier, we have added some [Migration Features](reified-generics-migration.md).
Markdown
hhvm/hphp/hack/manual/hack/14-reified-generics/03-reified-generics-migration.md
# Migration Features for Reified Generics In order to make migrating to reified generics easier, we have added the following migration features: * The `<<__Soft>>` annotation on a type parameter implies the intent to switch it to reified state. If generics at call sites are not provided the type checker will raise an error, and the runtime will raise a warning so you can capture these locations through logging. The generic cannot be used in the body of the function. * The `<<__Warn>>` annotation on a type parameter implies that if the reified generic is incorrect at parameter or return type hints locations, the runtime will raise a warning instead of type hint violation. * The `get_type_structure<reify T>()` function, given a reified type, returns the type structure representing the type. * The `get_classname<reify T>()` function, given a reified type, returns the name of the class represented by this type, or raises an exception if the type does not represent a class. ## Example Incremental Migration In this part, we'll walk you through how to migrate a non reified function to a reified function. Some of these steps can be skipped depending on the use case. 0) Beginning of time ```Hack class C<T> {} function f(C<int> $x): void {} function demo(): void { f(new C()); // OK } ``` 1) You have managed to write out all the type annotations (either pre-existing or by using `<<__Soft>>` annotation logging) ```Hack error class C<<<__Soft>> reify T> {} function f(C<int> $x): void {} function demo(): void { f(new C<string>()); // Typechecker error: string incompatible with int } ``` 2) You now want to remove `__Soft` and start using the generic. So you move `__Soft` to `__Warn`. ```Hack error class C<<<__Warn>> reify T> {} function f(C<int> $x): void {} function demo(): void { f(new C<string>()); // Runtime warning: string incompatible with int } ``` 3) By using logging, you have added `__Soft` to everywhere it's used and now it will be safe to remove `__Warn`. ```Hack error class C<<<__Warn>> reify T> {} function f(C< <<__Soft>> int> $x): void {} function demo(): void { f(new C<string>()); // Runtime warning: string incompatible with int } ``` 4) `__Warn` goes away ```Hack error class C<reify T> {} function f(C< <<__Soft>> int> $x): void {} function demo(): void { f(new C<string>()); // Runtime warning: string incompatible with int } ``` 5) Fix the use site ```Hack class C<reify T> {} function f(C<string> $x): void {} function demo(): void { f(new C<string>()); // OK } ```
Markdown
hhvm/hphp/hack/manual/hack/15-asynchronous-operations/01-introduction.md
Asynchronous operations allow cooperative multi-tasking. Code that utilizes the async infrastructure can hide I/O latency and data fetching. So, if we have code that has operations that involve some sort of waiting (e.g., network access or database queries), async minimizes the downtime our program has to be stalled because of it as the program will go do other things, most likely other I/O somewhere else. Async is **not multithreading**---HHVM still executes a program's code in one main request thread&mdash;but other operations (e.g., MySQL queries) can now execute without taking up time in that thread that code could be using for other purposes. ## A Page as A Dependency Tree Imagine we have a page that contains two components: one stores data in MySQL, the other fetches from an API via cURL. Both cache results in Memcached. The dependencies could be modeled like this: ![Dependency Tree](/images/async/async-dependency.png) Code structured like this gets the most benefit from async. ## Synchronous/Blocking IO: Sequential Execution If we do not use asynchronous programming, each step will be executed one-after-the-other: ![Sequential Execution](/images/async/async-sequential.png) ## Asynchronous Execution All code executes in the main request thread, but I/O does not block it, and multiple I/O or other async tasks can execute concurrently. If code is constructed as a dependency tree and uses async I/O, this will lead to various parts of the code transparently interleaving instead of blocking each other: ![Asynchronous](/images/async/async-always-busy.png) Importantly, the order in which code executes is not guaranteed; for example, if the cURL request for Component A is slow, execution of the same code could look more like this: ![Asynchronous with slow cURL](/images/async/async-slow-curl.png) The reordering of different task instructions in this way allow us to hide I/O [latency](https://en.wikipedia.org/wiki/Latency_\(engineering\)). So, while one task is currently sitting at an I/O instruction (e.g., waiting for data), another task's instruction, with hopefully less latency, can execute in the meantime. ## Limitations The two most important limitations are: - All code executes in the main request thread - Blocking APIs (e.g., `mysql_query()` and `sleep()`) do not get automatically converted to async functions; this would be unsafe as it could change the execution order of unrelated code that might not be designed for that possibility. For example, given the following code: ```Hack use namespace HH\Lib\Vec; async function do_cpu_work(): Awaitable<void> { print("Start CPU work\n"); $a = 0; $b = 1; $list = vec[$a, $b]; for ($i = 0; $i < 1000; ++$i) { $c = $a + $b; $list[] = $c; $a = $b; $b = $c; } print("End CPU work\n"); } async function do_sleep(): Awaitable<void> { print("Start sleep\n"); \sleep(1); print("End sleep\n"); } async function run(): Awaitable<void> { print("Start of main()\n"); await Vec\from_async(vec[do_cpu_work(), do_sleep()]); print("End of main()\n"); } <<__EntryPoint>> function main(): void { \HH\Asio\join(run()); } ``` New users often think of async as multithreading, so expect `do_cpu_work()` and `do_sleep()` to execute in parallel; however, this will not happen because there are no operations that can be moved to the background: - `do_cpu_work()` only contains code with no builtins, so executes in, and blocks, the main request thread - While `do_sleep()` does call a builtin, it is not an async builtin; so, it also must block the main request thread ![multithreaded model vs async model](/images/async/limitations.png) ## Async In Practice: cURL A naive way to make two cURL requests without async could look like this: ```Hack function curl_A(): mixed { $ch = \curl_init(); \curl_setopt($ch, \CURLOPT_URL, "http://example.com/"); \curl_setopt($ch, \CURLOPT_RETURNTRANSFER, 1); return \curl_exec($ch); } function curl_B(): mixed { $ch = \curl_init(); \curl_setopt($ch, \CURLOPT_URL, "http://example.net/"); \curl_setopt($ch, \CURLOPT_RETURNTRANSFER, 1); return \curl_exec($ch); } <<__EntryPoint>> function main(): void { $start = \microtime(true); $a = curl_A(); $b = curl_B(); $end = \microtime(true); echo "Total time taken: ".\strval($end - $start)." seconds\n"; } ``` In the example above, the call to `curl_exec` in `curl_A` is blocking any other processing. Thus, even though `curl_B` is an independent call from `curl_A`, it has to sit around waiting for `curl_A` to finish before beginning its execution: ![No Async](/images/async/curl-synchronous.png) Fortunately, HHVM provides an async version of `curl_exec`: ```Hack use namespace HH\Lib\Vec; async function curl_A(): Awaitable<string> { $x = await \HH\Asio\curl_exec("http://example.com/"); return $x; } async function curl_B(): Awaitable<string> { $y = await \HH\Asio\curl_exec("http://example.net/"); return $y; } async function async_curl(): Awaitable<void> { $start = \microtime(true); list($a, $b) = await Vec\from_async(vec[curl_A(), curl_B()]); $end = \microtime(true); echo "Total time taken: ".\strval($end - $start)." seconds\n"; } <<__EntryPoint>> function main(): void { \HH\Asio\join(async_curl()); } ``` The async version allows the scheduler to run other code while waiting for a response from cURL. The most likely behavior is that as we're also awaiting a call to `curl_B`, the scheduler will choose to call it, which in turn starts another async call to `curl_exec`. As HTTP requests are generally slow, the main thread will then be idle until one of the requests completes: ![Async](/images/async/curl-async.png) This execution order is the most likely, but not guaranteed; for example, if the `curl_B` request is much faster than the `curl_A` HTTP request, `curl_B` may complete before `curl_A`. The amount that async speeds up this example can vary greatly (e.g., depending on network conditions and DNS caching), but can be significant.
Markdown
hhvm/hphp/hack/manual/hack/15-asynchronous-operations/07-awaitables.md
```yamlmeta { "namespace": "HH\\Asio" } ``` An *awaitable* is the key construct in `async` code. An awaitable is a first-class object that represents a possibly asynchronous operation that may or may not have completed. We `await` the awaitable until the operation has completed. An `Awaitable` represents a particular execution; this means that awaiting the same awaitable twice **will not** execute the code twice. For example, while the result of both `await`s below is `42`, the `print()` call (and the `return`) only happen once: ```Hack $x = async { print("Hello, world\n"); return 42; }; \var_dump(await $x); \var_dump(await $x); ``` This can be surprising when the result depends on the call stack; [exceptions](exceptions) are the most common case of this. ## `Awaitable` Awaitables are represented by the interface called `Awaitable`. While there are several classes that implement `Awaitable`, there is no need to concern ourselves with their implementation details. `Awaitable` is the only interface we need. The type returned from an async function is `Awaitable<T>`, where `T` is the final result type (e.g., `int`) of the awaited value. ```Hack async function foo(): Awaitable<int> { throw new Exception('unimplemented'); } async function demo(): Awaitable<void> { $x = foo(); // $x will be an Awaitable<int> $x = await foo(); // $x will be an int } ``` ```Hack async function f(): Awaitable<int> { return 2; } // We call f() and get back an Awaitable<int> // Once the function is finished executing and we await the awaitable (or in // this case, explicitly join since this call is not in an async function) to get // the explicit result of the function call, we will get back 2. <<__EntryPoint>> function join_main(): void { var_dump(\HH\Asio\join(f())); } ``` All `async` functions must return an `Awaitable<T>`. Calling an `async` function will therefore yield an object implementing the `Awaitable` interface, and we must `await` or `join` it to obtain an end result from the operation. When we `await`, we are pausing the current task until the operation associated with the `Awaitable` handle is complete, leaving other tasks free to continue executing. `join` is similar; however it blocks all other operations from completing until the `Awaitable` has returned. ## Awaiting In most cases, we will prefer to `await` an `Awaitable`, so that other tasks can execute while our blocking operation completes. Note however, that only `async` functions can yield control to other asyncs, so `await` may therefore only be used in an `async` function. For other locations, such as a `main` block, we will need to use `join`, as will be shown below. ### Batching Awaitables Many times, we will `await` on one `Awaitable`, get the result, and move on. For example: ```Hack async function foo(): Awaitable<int> { return 3; } <<__EntryPoint>> async function single_awaitable_main(): Awaitable<void> { $aw = foo(); // awaitable of type Awaitable<int> $result = await $aw; // an int after $aw completes var_dump($result); } ``` We will normally see something like `await f();` which combines the retrieval of the awaitable with the waiting and retrieving of the result of that awaitable. The example above separates it out for illustration purposes. At other times, we will gather a bunch of awaitables and `await` them all before moving on. Here we are using one of the library helper-functions in order to batch a bunch of awaitables together to then `await` upon: * `HH\Lib\Vec\from_async`: vec of awaitables with consecutive integer keys * `HH\Lib\Dict\from_async`: dict of awaitables with integer or string keys ```Hack async function quads(float $n): Awaitable<float> { return $n * 4.0; } <<__EntryPoint>> async function quads_m(): Awaitable<void> { $awaitables = dict['five' => quads(5.0), 'nine' => quads(9.0)]; $results = await Dict\from_async($awaitables); \var_dump($results['five']); // float(20) \var_dump($results['nine']); // float(36) } ``` ## Join Sometimes we want to get a result out of an awaitable when the function we are in is *not* `async`. For this there is `HH\Asio\join`, which takes an `Awaitable` and blocks until it resolves to a result. This means that invocations of async functions from the top-level scope cannot be awaited, and must be joined. ```Hack async function get_raw(string $url): Awaitable<string> { return await \HH\Asio\curl_exec($url); } <<__EntryPoint>> function join_main(): void { $result = \HH\Asio\join(get_raw("http://www.example.com")); \var_dump(\substr($result, 0, 10)); } ``` We should **not** call `join` inside an `async` function. This would defeat the purpose of `async`, as the awaitable and any dependencies will run to completion synchronously, stopping any other awaitables from running.
Markdown
hhvm/hphp/hack/manual/hack/15-asynchronous-operations/10-exceptions.md
In general, an async operation has the following pattern: * Call an `async` function * Get an awaitable back * `await` the awaitable to get a result If an exception is thrown within an `async` function body, the function does not technically throw - it returns an `Awaitable` that throws when resolved. This means that if an `Awaitable` is resolved multiple times, the same exception object instance will be thrown every time; as it is the same object every time, its data will be unchanged, **including backtraces**. ```Hack async function exception_thrower(): Awaitable<void> { throw new \Exception("Return exception handle"); } async function basic_exception(): Awaitable<void> { // the handle does not throw, but result will be an Exception objection. // Remember, this is the same as: // $handle = exception_thrower(); // await $handle; await exception_thrower(); } <<__EntryPoint>> function main(): void { HH\Asio\join(basic_exception()); } ``` The use of `from_async` ignores any successful awaitable results and just throw an exception of one of the awaitable results, if one of the results was an exception. ```Hack async function exception_thrower(): Awaitable<void> { throw new \Exception("Return exception handle"); } async function non_exception_thrower(): Awaitable<int> { return 2; } async function multiple_waithandle_exception(): Awaitable<void> { $handles = vec[exception_thrower(), non_exception_thrower()]; // You will get a fatal error here with the exception thrown $results = await Vec\from_async($handles); // This won't happen var_dump($results); } <<__EntryPoint>> function main(): void { HH\Asio\join(multiple_waithandle_exception()); } ``` To get around this, and get the successful results as well, we can use the [utility function](utility-functions.md) [`HH\Asio\wrap`](/hack/reference/function/HH.Asio.wrap/). It takes an awaitable and returns the expected result or the exception if one was thrown. The exception it gives back is of the type [`ResultOrExceptionWrapper`](/hack/reference/interface/HH.Asio.ResultOrExceptionWrapper/). ```Hack no-extract namespace HH\Asio { interface ResultOrExceptionWrapper<T> { public function isSucceeded(): bool; public function isFailed(): bool; public function getResult(): T; public function getException(): Exception; } } ``` Taking the example above and using the wrapping mechanism, this is what the code looks like: ```Hack async function exception_thrower(): Awaitable<void> { throw new Exception(); } async function non_exception_thrower(): Awaitable<int> { return 2; } async function wrapping_exceptions(): Awaitable<void> { $handles = vec[ HH\Asio\wrap(exception_thrower()), HH\Asio\wrap(non_exception_thrower()), ]; // Since we wrapped, the results will contain both the exception and the // integer result $results = await Vec\from_async($handles); var_dump($results); } <<__EntryPoint>> function main(): void { HH\Asio\join(wrapping_exceptions()); } ``` ## Memoized Async Exceptions Because [`__Memoize`](../attributes/predefined-attributes#__memoize) caches the awaitable itself, **if an async function is memoized and throws, you will get the same exception backtrace on every failed call**. For example, both times an exception is caught here, `foo` is in the backtrace, but `bar` is not, as the call to `foo` led to the creation of the memoized awaitable: ```Hack <<__Memoize>> async function throw_something(): Awaitable<int> { throw new Exception(); } async function foo(): Awaitable<void> { await throw_something(); } async function bar(): Awaitable<void> { await throw_something(); } <<__EntryPoint>> async function main(): Awaitable<void> { try { await foo(); } catch (Exception $e) { var_dump($e->getTrace()[2] as shape('function' => string, ...)['function']); } try { await bar(); } catch (Exception $e) { var_dump($e->getTrace()[2] as shape('function' => string, ...)['function']); } } ```
Markdown
hhvm/hphp/hack/manual/hack/15-asynchronous-operations/13-async-blocks.md
Inside a lengthy async function, it's generally a good idea to group together data fetches that are independent of the rest of the function. This reduces unneeded waiting for I/O. To express this grouping inline, we would usually have to use a helper function; however, an async block allows for the immediate execution of a grouping of code, possibly within zero-argument, async lambdas. ## Syntax The syntax for an async block is: ``` async { // grouped together calls, usually await. < statements > } ``` ## Usage Async blocks have two main use-cases. Remember, this is essentially syntactic sugar to make life easier. - Inline simple async statements that would before have required a function call to execute. - Replace the call required by an async lambda to return an actual `Awaitable<T>`. ```Hack async function get_int_async(): Awaitable<int> { return 4; } async function get_float_async(): Awaitable<float> { return 1.2; } async function get_string_async(): Awaitable<string> { return "Hello"; } async function call_async<Tv>((function(): Awaitable<Tv>) $gen): Awaitable<Tv> { return await $gen(); } async function use_async_lambda(): Awaitable<void> { // To use an async lambda with no arguments, you would need to have a helper // function to return an actual Awaitable for you. $x = await call_async( async () ==> { $y = await get_float_async(); $z = await get_int_async(); return \round($y) + $z; }, ); \var_dump($x); } async function use_async_block(): Awaitable<void> { // With an async block, no helper function is needed. It is all built-in to the // async block itself. $x = await async { $y = await get_float_async(); $z = await get_int_async(); return \round($y) + $z; }; \var_dump($x); } async function call_async_function(): Awaitable<void> { // Normally we have to call a simple async function and get its value, even // if it takes no arguments, etc. $x = await get_string_async(); \var_dump($x); } async function use_async_block_2(): Awaitable<void> { // Here we can inline our function right in the async block $x = await async { return "Hello"; }; \var_dump($x); } <<__EntryPoint>> function main(): void { \HH\Asio\join(use_async_lambda()); \HH\Asio\join(use_async_block()); \HH\Asio\join(call_async_function()); \HH\Asio\join(use_async_block_2()); } ``` ## Limitations The typechecker does not allow the use of an async block immediately on the right-hand side of the `==>` in a lambda-creation expression. In async named-functions, `async` immediately precedes `function`, which, in turn, immediately precedes the parameters. In async lambdas, `async` also immediately precedes the parameters. So: ```Hack no-extract $x = async () ==> { ... } // good $x = () ==> async { ... } // bad ``` Basically, this is just a safety guard to reduce the likelihood of unintended behavior.
Markdown
hhvm/hphp/hack/manual/hack/15-asynchronous-operations/14-concurrent.md
`concurrent` concurrently awaits all `await`s within a `concurrent` block and it works with [`await`-as-an-expression](await-as-an-expression.md) as well! Note: [concurrent doesn't mean multithreading](some-basics#limitations) ## Syntax ```Hack no-extract concurrent { $x = await x_async(); await void_async(); $sum = await y_async() + await z_async()(); } $y = $x + $sum; ``` ## Order-of-execution Each of the statements in a `concurrent` block should be thought of as running concurrently. This means there shouldn't be any dependencies between the statements in a `concurrent` block. Similar to `await`-as-an-expression, `concurrent` blocks don't provide a guaranteed order-of-execution between expressions being evaluated for any statement in the `concurrent` block. We guarantee that modifications to locals will happen after all other expressions resolve and will happen in the order in which they would happen outside a `concurrent` block. For this example, we provide no guarantee on the execution order of the calls to `x()`, `y_async()` and `z_async()`. The assignments into `$result` are guaranteed to be well ordered however. ```Hack no-extract $result = vec[]; concurrent { $result[] = x() + await y_async(); $result[] = await z_async(); } ``` ## Exceptions If any statement in a `concurrent` block throws, there are no guarantees about which (if any) awaited values were assigned or which exception will be propagated if more than one of them threw. For example if you have: ```Hack no-extract $x = 0; try { concurrent { $x = await async { return 1; }; await async { throw new Exception('foo'); }; await async { throw new Exception('bar'); }; } } catch (Exception $e) { var_dump($x, $e->getMessage()); } ``` Then it is explicitly undefined whether `var_dump` will see `$x === 0` or `$x === 1` and whether the message will be 'foo' or 'bar'. If you need granular exception handling, consider using nested try-catch blocks inside the concurrent block: ```Hack no-extract concurrent { $x = await async { try { ... return <success path>; } catch (...) { return <fallback>; } }; $y = await async { // same here }; } ```
Markdown
hhvm/hphp/hack/manual/hack/15-asynchronous-operations/15-await-as-an-expression.md
To strike a balance between flexibility, latency, and performance, we require that the `await`s only appear in **unconditionally consumed expression positions**. This means that from the closest statement, the result of the `await` must be used under all non-throwing cases. This is important because all `await`s for a statement will run together, we don't want to over-run code if its result might not be utilized. All `await`s within the same statement will execute concurrently. ## Examples ```Hack no-extract $sum = await x_async() + // yes! await y_async(); // yes! $tuple = tuple( await foo_async(), // yes! 42, ); $result = foo( await bar_async(), // yes! await baz_async(), // yes! ); if (await x_async()) { // yes! // Conditional but separate statement await y_async(); // yes! } $x = await x_async() && // yes! // Conditional expression await y_async(); // no! $y = await x_async() // yes! ? await y_async() // no! : await z_async(); // no! $x = await async { // yes! await x_async(); // yes! } ``` ## Order-of-execution Similar to other aspects of `await`, we do not guarantee an order of execution of the expressions within a statement that contains `await`, but you should assume it could be significantly different than if the `await` wasn't present. **If you want stronger guarantees over order-of-execution, separate `await`s into their own statements.** In this example, you should make no assumptions about the order in which `a_async()`, `b()`, `c_async()` or `d()` are executed, but you can assume that both `await`'ed functions (`a_async()` and `c_async()`) will be concurrently awaited. ```Hack no-extract $x = foo( await a_async(), b(), await c_async(), d(), ); ``` ## Limitations To further help protect against depending on order-of-execution, we've banned assignment or updating variables as-an-expression for statements that contain an `await`. ```Hack no-extract // Yes! $x = await x_async(); // No, assignment as an expression await foo_async($x = 42); // No, we even disallow separate assignment (await bar_async()) + ($x = 42); // Yes! $x = f(inout $y, await x_async()); // Yes, embedded call w/ inout is considered an expression await bar_async(baz(inout $x)); ``` Hack doesn't currently support nested `await`s. ```Hack error // Syntax error. $y = await foo_async(await bar_async()); // Must be written as this instead. $x = await bar_async(); $y = await foo_async($x); ```
Markdown
hhvm/hphp/hack/manual/hack/15-asynchronous-operations/16-utility-functions.md
Async can be used effectively with the basic, built in infrastructure in HHVM, along with some HSL functions. This basic infrastructure includes: * [`async`](../asynchronous-operations/introduction.md), [`await`](../asynchronous-operations/awaitables), [`Awaitable`](../asynchronous-operations/awaitables) * `HH\Lib\Vec\from_async()`, `HH\Lib\Dict\from_async()` However, there are cases when we want to convert some collection of values to awaitables or we want to filter some awaitables out of a collection of awaitables. These types of scenarios come up when we are creating multiple awaitables to await in parallel. Some of the functions that help with this are: Name | Returns | Description -----|---------|------------ `HH\Lib\Vec\filter_async<Tv>` | `Awaitable<vec<Tv>>` | Returns a new vec containing only the values for which the given async predicate returns `true`. `HH\Lib\Vec\from_async<Tv>` | `Awaitable<vec<Tv>>` | Returns a new vec with each value awaited in parallel. `HH\Lib\Vec\map_async<Tv1, Tv2>` | `Awaitable<vec<Tv2>>` | Returns a new vec where each value is the result of calling the given async function on the original value. `HH\Lib\Dict\filter_async<Tk as arraykey, Tv>` | `Awaitable<dict<Tk,Tv>>` | Returns a new dict containing only the values for which the given async predicate returns `true`. `HH\Lib\Dict\filter_with_key_async<Tk as arraykey, Tv>` | `Awaitable<dict<Tk,Tv>>` | Like `filter_async`, but lets you utilize the keys of your dict too. `HH\Lib\Dict\from_async<Tk, Tv1>` | `Awaitable<dict<Tk,Tv2>>` | Returns a new dict where each value is the result of calling the given async function on the original value. `HH\Lib\Dict\from_keys_async<Tk as arraykey, Tv>` | `Awaitable<dict<Tk,Tv>>` | Returns a new dict where each value is the result of calling the given async function on the corresponding key. `HH\Lib\Dict\map_async<Tk as arraykey, Tv1, Tv2>` | `Awaitable<dict<Tk,Tv2>>` | Returns a new dict where each value is the result of calling the given async function on the original value. `HH\Lib\Keyset\filter_async<Tv as arraykey>` | `Awaitable<keyset<Tv>>` | Returns a new keyset containing only the values for which the given async predicate returns `true`. `HH\Lib\Keyset\from_async<Tv as arraykey>` | `Awaitable<keyset<Tv>>` | Returns a new keyset containing the awaited result of the given Awaitables. `HH\Lib\Keyset\map_async<Tv, Tk as arraykey>` | `Awaitable<keyset<Tk>>` | Returns a new keyset where the value is the result of calling the given async function on the original values in the given traversable. ## Other Convenience Functions There are three convenience-functions tailored for use with async. They are: Name | Returns | Description -----|---------|------------ `HH\Asio\usleep(int)` | `Awaitable<void>` | Wait a given length of time before an async function does more work. `HH\Asio\later()` | `Awaitable<void>` | Reschedule the work of an async function until some undetermined point in the future. `HH\Asio\wrap(Awaitable<Tv>)` | `Awaitable<ResultOrExceptionWrapper<Tv>>` | Wrap an `Awaitable` into an `Awaitable` of `ResultOrExceptionWrapper`.
Markdown
hhvm/hphp/hack/manual/hack/15-asynchronous-operations/19-extensions.md
Async in and of itself is a highly useful construct that can provide possible time-saving through its cooperative multitasking infrastructure. Async is especially useful with database access and caching, web resource access, and dealing with streams. ## MySQL The async MySQL extension provides a Hack API to query MySQL and similar databases. All relevant methods return an `Awaitable`, which gives your code control over how it spends the time until the result is ready. The [full API](../reference/class/AsyncMysqlConnection/) contains all of the classes and methods available for accessing MySQL via async; we will only cover a few of the more common scenarios here. The primary class for connecting to a MySQL database is [`AsyncMysqlConnectionPool`](../reference/class/AsyncMysqlClient/) and its primary method is the `async` [`connect`](../reference/class/AsyncMysqlClient/connect/). The primary class for querying a database is [`AsyncMysqlConnection`](../reference/class/AsyncMysqlConnection/) with the three main query methods: `AsyncMysqlConnection::query`, `AsyncMysqlConnection::queryf`, and `AsyncMysqlConnection::queryAsync` all of which are `async`. The naming conventions for async methods have not been applied consistently. There is also a method which turns a raw string into an SQL escaped string `AsyncMysqlConnection::escapeString`. This method should only be used in combination with `AsyncMysqlConnection::query`. ## Choosing a query method ### `AsyncMysqlConnection::queryAsync` This method is the go-to for safe SQL queries. It handles escaping user input automatically and the `%Q` placeholder can be used to insert query fragments into other query fragments. For example: - selecting a post by ID ```SQL SELECT title, body FROM posts WHERE id %=d ``` - Advanced search, which may allow the user to specify a handful of parameters ```SQL SELECT %LC FROM %T WHERE %Q ``` - Inserting _n_ rows in one big INSERT INTO statement ```SQL INSERT INTO %T (%LC) VALUES (%Q) ``` For a list of all placeholders supported by `queryAsync`, see `HH\Lib\SQL\QueryFormatString`. Most placeholders are documented with examples here `AsyncMysqlConnection::queryf`. The types for the `%Lx` placeholders is not a Hack Collection when using queryAsync, but a Hack array instead. The documentation for `%Q` is flat out wrong for using `queryAsync` and should be ignored. ### `AsyncMysqlConnection::query` This method is **dangerous** when used wrong. It accepts a _raw string_ and passes it to the database without scanning for dangerous characters or doing any automatic escaping. If your query contains ANY unescaped input, you are putting your database at risk. Using this method is preferred for one use case: When you can type out the query outright, without string interpolation or string concatenation. You can pass in a _hardcoded_ query. This can be preferred over `queryAsync` and `queryf`, since you can write your SQL string literals without having to write a `%s` placeholder. Which makes it easier to change the query later without the risk of messing up which parameter goes with which `%s`. This method can also be used to create queries by doing string manipulation. If you are doing this, you, the developer, must take responsibility for sanitizing the data. Escape everything that needs to be escaped and make triple sure there is not a sneaky way to get raw user data into the concatenated string at any point. As said, this method is dangerous and this is why. ### `AsyncMysqlConnection::queryf` Is an older API which does what `queryAsync` does, but with more restrictions. It uses Hack Collections instead of Hack arrays for its `%Lx` arguments. There is no way to create fragments of queries for safe query building. It is also not possible to build a query without having an `\AsyncMysqlConnection`. New code should use `queryAsync` instead. ## Getting results The primary class for retrieving results from a query is an abstract class called `AsyncMysqlResult`, which itself has two concrete subclasses called [`AsyncMysqlQueryResult`](../reference/class/AsyncMysqlQueryResult/) and [`AsyncMysqlErrorResult`](../reference/class/AsyncMysqlErrorResult/). The main methods on these classes are [`vectorRows`](../reference/class/AsyncMysqlQueryResult/vectorRows/) | [`vectorRowsTyped`](../reference/class/AsyncMysqlQueryResult/vectorRowsTyped/) and [`mapRows`](../reference/class/AsyncMysqlQueryResult/mapRows/) | [`mapRowsTyped`](../reference/class/AsyncMysqlQueryResult/mapRowsTyped/), which are *non-async*. ### When to use the `____Typed` variant over its untyped counterpart. The typed functions will help you by turning database integers into Hack `int`s and _some, but not all_ fractional numbers into Hack `float`s. This is almost always preferred, except for cases where the result set includes unsigned 64-bit integers (UNSIGNED BIGINT). These numbers may be larger than the largest representable signed 64-bit integer and can therefore not be used in a Hack program. The runtime currently returns the largest signed 64-bit integer for all values which exceed the maximum signed 64-bit integer. The untyped function will return all fields as either a Hack `string` or a Hack `null`. So an integer `404` in the database would come back as `"404"`. Here is a simple example that shows how to get a user name from a database using this extension: ```Hack no-extract async function get_connection(): Awaitable<AsyncMysqlConnection> { // Get a connection pool with default options $pool = new AsyncMysqlConnectionPool(darray[]); // Change credentials to something that works in order to test this code return await $pool->connect( CI::$host, CI::$port, CI::$db, CI::$user, CI::$passwd, ); } async function fetch_user_name( AsyncMysqlConnection $conn, int $user_id, ): Awaitable<?string> { // Your table and column may differ, of course $result = await $conn->queryf( 'SELECT name from test_table WHERE userID = %d', $user_id, ); // There shouldn't be more than one row returned for one user id invariant($result->numRows() === 1, 'one row exactly'); // A vector of vector objects holding the string values of each column // in the query $vector = $result->vectorRows(); return $vector[0][0]; // We had one column in our query } async function get_user_info( AsyncMysqlConnection $conn, string $user, ): Awaitable<Vector<Map<string, ?string>>> { $result = await $conn->queryf( 'SELECT * from test_table WHERE name %=s', $user, ); // A vector of map objects holding the string values of each column // in the query, and the keys being the column names $map = $result->mapRows(); return $map; } <<__EntryPoint>> async function async_mysql_tutorial(): Awaitable<void> { $conn = await get_connection(); if ($conn !== null) { $result = await fetch_user_name($conn, 2); var_dump($result); $info = await get_user_info($conn, 'Fred Emmott'); var_dump($info is vec<_>); var_dump($info[0] is dict<_, _>); } } ``` ### Connection Pools The async MySQL extension does *not* support multiplexing; each concurrent query requires its own connection. However, the extension does support connection pooling. The async MySQL extension provides a mechanism to pool connection objects so we don't have to create a new connection every time we want to make a query. The class is [`AsyncMysqlConnectionPool`](../reference/class/AsyncMysqlConnectionPool/) and one can be created like this: ```hack no-extract function get_pool(): AsyncMysqlConnectionPool { return new AsyncMysqlConnectionPool( darray['pool_connection_limit' => 100], ); // See API for more pool options } async function get_connection(): Awaitable<AsyncMysqlConnection> { $pool = get_pool(); $conn = await $pool->connect( CI::$host, CI::$port, CI::$db, CI::$user, CI::$passwd, ); return $conn; } <<__EntryPoint>> async function run(): Awaitable<void> { $conn = await get_connection(); var_dump($conn); } ``` It is ***highly recommended*** that connection pools are used for MySQL connections; if for some reason we really need one, single asynchronous client, there is an [`AsyncMysqlClient`](../reference/class/AsyncMysqlClient/) class that provides a [`connect`](../reference/class/AsyncMysqlClient/connect/) method. ## MCRouter MCRouter is a memcached protocol-routing library. To help with [memcached](http://php.net/manual/en/book.memcached.php) deployment, it provides features such as connection pooling and prefix-based routing. The async MCRouter extension is basically an async subset of the Memcached extension that is part of HHVM. The primary class is `MCRouter`. There are two ways to create an instance of an MCRouter object. The [`createSimple`](../reference/class/MCRouter/createSimple/) method takes a vector of server addresses where memcached is running. The more configurable [`__construct`](../reference/class/MCRouter/__construct/) method allows for more option tweaking. After getting an object, we can use the `async` versions of the core memcached protocol methods like [`add`](../reference/class/MCRouter/add/), [`get`](../reference/class/MCRouter/get/) and [`del`](../reference/class/MCRouter/del/). Here is a simple example showing how one might get a user name from memcached: ```hack no-extract function get_mcrouter_object(): MCRouter { $servers = Vector {\getenv('HHVM_TEST_MCROUTER')}; $mc = MCRouter::createSimple($servers); return $mc; } async function add_user_name( MCRouter $mcr, int $id, string $value, ): Awaitable<void> { $key = 'name:'.$id; await $mcr->set($key, $value); } async function get_user_name(\MCRouter $mcr, int $user_id): Awaitable<string> { $key = 'name:'.$user_id; try { $res = await HH\Asio\wrap($mcr->get($key)); if ($res->isSucceeded()) { return $res->getResult(); } return ""; } catch (\MCRouterException $ex) { echo $ex->getKey().\PHP_EOL.$ex->getOp(); return ""; } } <<__EntryPoint>> async function run(): Awaitable<void> { $mcr = get_mcrouter_object(); await add_user_name($mcr, 1, 'Joel'); $name = await get_user_name($mcr, 1); var_dump($name); // Should print "Joel" } ``` If an issue occurs when using this protocol, two possible exceptions can be thrown: `MCRouterException` when something goes wrong with a core option, like deleting a key; `MCRouterOptionException` when the provide option list can't be parsed. ## cURL Hack currently provides two async functions for [cURL](http://curl.haxx.se/). ### `curl_multi_await` cURL provides a data transfer library for URLs. The async cURL extension provides two functions, one of which is a wrapper around the other. `curl_multi_await` is the async version of HHVM's `curl_multi_select`. It waits until there is activity on the cURL handle and when it completes, we use `curl_multi_exec` to process the result, just as we would in the non-async situation. ```hack no-extract async function curl_multi_await(resource $mh, float $timeout = 1.0): Awaitable<int>; ``` ### `curl_exec` The function `HH\Asio\curl_exec` is a wrapper around `curl_multi_await`. It is easy to use as we don't necessarily have to worry about resource creation since we can just pass a string URL to it. ```hack no-extract namespace HH\Asio { async function curl_exec(mixed $urlOrHandle): Awaitable<string>; } ``` Here is an example of getting a vector of URL contents, using a lambda expression to cut down on the code verbosity that would come with full closure syntax: ```hack no-extract function get_urls(): vec<string> { return vec[ "http://example.com", "http://example.net", "http://example.org", ]; } async function get_combined_contents( vec<string> $urls, ): Awaitable<vec<string>> { // Use lambda shorthand syntax here instead of full closure syntax $handles = Vec\map_with_key( $urls, ($idx, $url) ==> HH\Asio\curl_exec($url), ); $contents = await Vec\from_async($handles); echo C\count($contents)."\n"; return $contents; } <<__EntryPoint>> function main(): void { HH\Asio\join(get_combined_contents(get_urls())); } ``` ## Streams The async stream extension has one function, [`stream_await`](../reference/function/stream_await/), which is functionally similar to HHVM's [`stream_select`](http://php.net/manual/en/function.stream-select.php). It waits for a stream to enter a state (e.g., `STREAM_AWAIT_READY`), but without the multiplexing functionality of [`stream_select`](http://php.net/manual/en/function.stream-select.php). We can use [HH\Lib\Vec\from_async](../reference/function/HH.Lib.Vec.from_async/) to await multiple stream handles, but the resulting combined awaitable won't be complete until all of the underlying streams have completed. ```Hack no-extract async function stream_await(resource $fp, int $events, float $timeout = 0.0): Awaitable<int>; ``` The following example shows how to use [`stream_await`](../reference/function/stream_await/) to write to resources: ```Hack function get_resources(): vec<resource> { $r1 = fopen('php://stdout', 'w'); $r2 = fopen('php://stdout', 'w'); $r3 = fopen('php://stdout', 'w'); return vec[$r1, $r2, $r3]; } async function write_all(vec<resource> $resources): Awaitable<void> { $write_single_resource = async function(resource $r) { $status = await stream_await($r, STREAM_AWAIT_WRITE, 1.0); if ($status === STREAM_AWAIT_READY) { fwrite($r, str_shuffle('ABCDEF').\PHP_EOL); } }; // You will get 3 shuffled strings, each on a separate line. await Vec\from_async(\array_map($write_single_resource, $resources)); } <<__EntryPoint>> function main(): void { HH\Asio\join(write_all(get_resources())); } ```
Markdown
hhvm/hphp/hack/manual/hack/15-asynchronous-operations/22-generators.md
[Generators](http://php.net/manual/en/language.generators.overview.php) provide a more compact way to write an [iterator](http://php.net/manual/en/language.oop5.iterations.php). Generators work by passing control back and forth between the generator and the calling code. Instead of returning once or requiring something that could be memory-intensive like an array, generators yield values to the calling code as many times as necessary in order to provide the values being iterated over. Generators can be `async` functions; an async generator behaves similarly to a normal generator except that each yielded value is an `Awaitable` that is `await`ed upon. ## Async Iterators To yield values or key/value pairs from async generators, we return [HH\AsyncIterator](/hack/reference/interface/HH.AsyncIterator/) or [HH\AsyncKeyedIterator](/hack/reference/interface/HH.AsyncKeyedIterator/), respectively. Here is an example of using the [async utility function](../asynchronous-operations/utility-functions.md) [`usleep`](/hack/reference/function/HH.Asio.usleep/) to imitate a second-by-second countdown clock. Note that in the `happy_new_year` `foreach` loop we have the syntax `await as`. This is shorthand for calling `await $ait->next()`. ```Hack const int SECOND = 1000000; // microseconds async function countdown(int $from): AsyncIterator<int> { for ($i = $from; $i >= 0; --$i) { await \HH\Asio\usleep(SECOND); // Every second, a value will be yielded back to the caller, happy_new_year() yield $i; } } async function happy_new_year(int $start): Awaitable<void> { // Get the AsyncIterator that enables the countdown $ait = countdown($start); foreach ($ait await as $time) { // we are awaiting the returned awaitable, so this will be an int if ($time > 0) { echo $time."\n"; } else { echo "HAPPY NEW YEAR!!!\n"; } } } <<__EntryPoint>> function run(): void { \HH\Asio\join(happy_new_year(5)); // 5 second countdown } ``` We must use `await as`; otherwise we'll not get the iterated value. Although `await as` is just like calling `await $gen->next()`, we should always use `await as`. Calling the [`AsyncGenerator`](/hack/reference/class/HH.AsyncGenerator/) methods directly is rarely needed. Also note that on async iterators, `await as` or a call to [`next`](/hack/reference/class/HH.AsyncGenerator/next/) actually returns a value (instead of `void` like in a normal iterator). ## Sending and Raising **Calling these methods directly should be rarely needed; `await as` should be the most common way to access values returned by an iterator.** We can send a value to a generator using [`send`](/hack/reference/class/HH.AsyncGenerator/send/) and raise an exception upon a generator using [`raise`](/hack/reference/class/HH.AsyncGenerator/raise/). If we are doing either of these two things, our generator must return `AsyncGenerator`. An `AsyncGenenator` has three type parameters: the key, the value. And the type being passed to [`send`](/hack/reference/class/HH.AsyncGenerator/send/). ```Hack const int HALF_SECOND = 500000; // microseconds async function get_name_string(int $id): Awaitable<string> { // simulate fetch to database where we would actually use $id await \HH\Asio\usleep(HALF_SECOND); return \str_shuffle("ABCDEFG"); } async function generate(): AsyncGenerator<int, string, int> { $id = yield 0 => ''; // initialize $id // $id is a ?int; you can pass null to send() while ($id is nonnull) { $name = await get_name_string($id); $id = yield $id => $name; // key/string pair } } async function associate_ids_to_names(vec<int> $ids): Awaitable<void> { $async_generator = generate(); // You have to call next() before you send. So this is the priming step and // you will get the initialization result from generate() $result = await $async_generator->next(); \var_dump($result); foreach ($ids as $id) { // $result will be an array of ?int and string $result = await $async_generator->send($id); \var_dump($result); } } <<__EntryPoint>> function run(): void { $ids = vec[1, 2, 3, 4]; \HH\Asio\join(associate_ids_to_names($ids)); } ``` Here is how to raise an exception to an async generator. ```Hack const int HALF_SECOND = 500000; // microseconds async function get_name_string(int $id): Awaitable<string> { // simulate fetch to database where we would actually use $id await \HH\Asio\usleep(HALF_SECOND); return \str_shuffle("ABCDEFG"); } async function generate(): AsyncGenerator<int, string, int> { $id = yield 0 => ''; // initialize $id // $id is a ?int; you can pass null to send() while ($id is nonnull) { $name = ""; try { $name = await get_name_string($id); $id = yield $id => $name; // key/string pair } catch (\Exception $ex) { \var_dump($ex->getMessage()); $id = yield 0 => ''; } } } async function associate_ids_to_names(vec<int> $ids): Awaitable<void> { $async_generator = generate(); // You have to call next() before you send. So this is the priming step and // you will get the initialization result from generate() $result = await $async_generator->next(); \var_dump($result); foreach ($ids as $id) { if ($id === 3) { $result = await $async_generator->raise( new \Exception("Id of 3 is bad!"), ); } else { $result = await $async_generator->send($id); } \var_dump($result); } } <<__EntryPoint>> function run(): void { $ids = vec[1, 2, 3, 4]; \HH\Asio\join(associate_ids_to_names($ids)); } ```
Markdown
hhvm/hphp/hack/manual/hack/15-asynchronous-operations/28-guidelines.md
It might be tempting to just sprinkle `async`, `await` and `Awaitable` on all code. And while it is OK to have more `async` functions than not&mdash;in fact, we should generally *not be afraid* to make a function `async` since there is no performance penalty for doing so&mdash;there are some guidelines to follow in order to make the most efficient use of `async`. ## Be Liberal, but Careful, with Async Should code be async or not? It's okay to start with the answer *Yes* and then find a reason to say *No*. For example, a simple "hello world" program can be made async with no performance penalty. And while there likely won't be any gain, there won't be any loss, either; the code is simply ready for any future changes that may require async. These two programs are, for all intents and purposes, equivalent. ```Hack function get_hello(): string { return "Hello"; } <<__EntryPoint>> function run_na_hello(): void { \var_dump(get_hello()); } ``` ```Hack async function get_hello(): Awaitable<string> { return "Hello"; } <<__EntryPoint>> async function run_a_hello(): Awaitable<void> { $x = await get_hello(); \var_dump($x); } ``` Just make sure you are following the rest of the guidelines. Async is great, but you still have to consider things like caching, batching and efficiency. ## Use Async Extensions For the common cases where async would provide maximum benefit, HHVM provides convenient extension libraries to help make writing code much easier. Depending on the use case scenario, we should liberally use: * [MySQL](extensions.md#mysql) for database access and queries. * [cURL](extensions.md#curl) for web page data and transfer. * [McRouter](extensions.md#mcrouter) for memcached-based operations. * [Streams](extensions.md#streams) for stream-based resource operations. ## Do Not Use Async in Loops If you only remember one rule, remember this: **DON'T `await` IN A LOOP** It totally defeats the purpose of async. ```Hack class User { public string $name; protected function __construct(string $name) { $this->name = $name; } public static function get_name(int $id): User { return new User(\str_shuffle("ABCDEFGHIJ").\strval($id)); } } async function load_user(int $id): Awaitable<User> { // Load user from somewhere (e.g., database). // Fake it for now return User::get_name($id); } async function load_users_await_loop(vec<int> $ids): Awaitable<vec<User>> { $result = vec[]; foreach ($ids as $id) { $result[] = await load_user($id); } return $result; } <<__EntryPoint>> function runMe(): void { $ids = vec[1, 2, 5, 99, 332]; $result = \HH\Asio\join(load_users_await_loop($ids)); \var_dump($result[4]->name); } ``` In the above example, the loop is doing two things: 1. Making the loop iterations the limiting factor on how this code is going to run. By the loop, we are guaranteed to get the users sequentially. 2. We are creating false dependencies. Loading one user is not dependent on loading another user. Instead, we will want to use our async-aware mapping function, `Vec\map_async`. ```Hack class User { public string $name; protected function __construct(string $name) { $this->name = $name; } public static function get_name(int $id): User { return new User(\str_shuffle("ABCDEFGHIJ").\strval($id)); } } async function load_user(int $id): Awaitable<User> { // Load user from somewhere (e.g., database). // Fake it for now return User::get_name($id); } async function load_users_no_loop(vec<int> $ids): Awaitable<vec<User>> { return await Vec\map_async( $ids, async $id ==> await load_user($id), ); } <<__EntryPoint>> function runMe(): void { $ids = vec[1, 2, 5, 99, 332]; $result = \HH\Asio\join(load_users_no_loop($ids)); \var_dump($result[4]->name); } ``` ## Considering Data Dependencies Is Important Possibly the most important aspect in learning how to structure async code is understanding data dependency patterns. Here is the general flow of how to make sure async code is data dependency correct: 1. Put each sequence of dependencies with no branching (chain) into its own `async` function. 2. Put each bundle of parallel chains into its own `async` function. 3. Repeat to see if there are further reductions. Let's say we are getting blog posts of an author. This would involve the following steps: 1. Get the post ids for an author. 2. Get the post text for each post id. 3. Get comment count for each post id. 4. Generate final page of information ```Hack class PostData { // using constructor argument promotion public function __construct(public string $text) {} } async function fetch_all_post_ids_for_author( int $author_id, ): Awaitable<vec<int>> { // Query database, etc., but for now, just return made up stuff return vec[4, 53, 99]; } async function fetch_post_data(int $post_id): Awaitable<PostData> { // Query database, etc. but for now, return something random return new PostData(\str_shuffle("ABCDEFGHIJKLMNOPQRSTUVWXYZ")); } async function fetch_comment_count(int $post_id): Awaitable<int> { // Query database, etc., but for now, return something random return \rand(0, 50); } async function fetch_page_data( int $author_id, ): Awaitable<vec<(PostData, int)>> { $all_post_ids = await fetch_all_post_ids_for_author($author_id); // An async closure that will turn a post ID into a tuple of // post data and comment count $post_fetcher = async function(int $post_id): Awaitable<(PostData, int)> { list($post_data, $comment_count) = await Vec\from_async(vec[ fetch_post_data($post_id), fetch_comment_count($post_id), ]); invariant($post_data is PostData, "This is good"); invariant($comment_count is int, "This is good"); return tuple($post_data, $comment_count); }; // Transform the array of post IDs into an vec of results, // using the Vec\map_async function return await Vec\map_async($all_post_ids, $post_fetcher); } async function generate_page(int $author_id): Awaitable<string> { $tuples = await fetch_page_data($author_id); $page = ""; foreach ($tuples as $tuple) { list($post_data, $comment_count) = $tuple; // Normally render the data into HTML, but for now, just create a // normal string $page .= $post_data->text." ".$comment_count.\PHP_EOL; } return $page; } <<__EntryPoint>> function main(): void { print \HH\Asio\join(generate_page(13324)); // just made up a user id } ``` The above example follows our flow: 1. One function for each fetch operation (post ids, post text, comment count). 2. One function for the bundle of data operations (post text and comment count). 3. One top function that coordinates everything. ## Consider Batching Wait handles can be rescheduled. This means that they can be sent back to the queue of the scheduler, waiting until other awaitables have run. Batching can be a good use of rescheduling. For example, say we have high latency lookup of data, but we can send multiple keys for the lookup in a single request. ```Hack async function b_one(string $key): Awaitable<string> { $subkey = await Batcher::lookup($key); return await Batcher::lookup($subkey); } async function b_two(string $key): Awaitable<string> { return await Batcher::lookup($key); } async function batching(): Awaitable<void> { $results = await Vec\from_async(vec[b_one('hello'), b_two('world')]); \printf("%s\n%s\n", $results[0], $results[1]); } <<__EntryPoint>> function main(): void { HH\Asio\join(batching()); } class Batcher { private static vec<string> $pendingKeys = vec[]; private static ?Awaitable<dict<string, string>> $aw = null; public static async function lookup(string $key): Awaitable<string> { // Add this key to the pending batch self::$pendingKeys[] = $key; // If there's no awaitable about to start, create a new one if (self::$aw === null) { self::$aw = self::go(); } // Wait for the batch to complete, and get our result from it $results = await self::$aw; return $results[$key]; } private static async function go(): Awaitable<dict<string, string>> { // Let other awaitables get into this batch await \HH\Asio\later(); // Now this batch has started; clear the shared state $keys = self::$pendingKeys; self::$pendingKeys = vec[]; self::$aw = null; // Do the multi-key roundtrip return await multi_key_lookup($keys); } } async function multi_key_lookup( vec<string> $keys, ): Awaitable<dict<string, string>> { // lookup multiple keys, but, for now, return something random $r = dict[]; foreach ($keys as $key) { $r[$key] = \str_shuffle("ABCDEF"); } return $r; } ``` In the example above, we reduce the number of roundtrips to the server containing the data information to two by batching the first lookup in `b_one` and the lookup in `b_two`. The `Batcher::lookup` method helps enable this reduction. The call to `await HH\Asio\later` in `Batcher::go` allows `Batcher::go` to be deferred until other pending awaitables have run. So, `await Vec\from_async(vec[b_one('hello'), b_two('world')]);` has two pending awaitables. If `b_one` is called first, it calls `Batcher::lookup`, which calls `Batcher::go`, which reschedules via `later`. Then HHVM looks for other pending awaitables. `b_two` is also pending. It calls `Batcher::lookup` and then it gets suspended via `await self::$aw` because `Batcher::$aw` is no longer `null`. Now `Batcher::go)` resumes, fetches, and returns the result. ## Don't Forget to Await an Awaitable What do you think happens here? ```Hack async function speak(): Awaitable<void> { echo "one"; await \HH\Asio\later(); echo "two"; echo "three"; } <<__EntryPoint>> async function forget_await(): Awaitable<void> { $handle = speak(); // This just gets you the handle } ``` The answer is, the behavior is undefined. We might get all three echoes; we might only get the first echo; we might get nothing at all. The only way to guarantee that `speak` runs to completion is to `await` it. `await` is the trigger to the async scheduler that allows HHVM to appropriately suspend and resume `speak`; otherwise, the async scheduler will provide no guarantees with respect to `speak`. ## Minimize Undesired Side Effects In order to minimize any unwanted side effects (e.g., ordering disparities), the creation and awaiting of awaitables should happen as close together as possible. ```Hack async function get_curl_data(string $url): Awaitable<string> { return await \HH\Asio\curl_exec($url); } function possible_side_effects(): int { \sleep(1); echo "Output buffer stuff"; return 4; } async function proximity(): Awaitable<void> { $handle = get_curl_data("http://example.com"); possible_side_effects(); await $handle; // instead you should await get_curl_data("....") here } <<__EntryPoint>> function main(): void { \HH\Asio\join(proximity()); } ``` In the above example, `possible_side_effects` could cause some undesired behavior when we get to the point of awaiting the handle associated with getting the data from the website. Basically, don't depend on the order of output between runs of the same code; i.e., don't write async code where ordering is important. Instead use dependencies via awaitables and `await`. ## Memoization May be Good, But Only Awaitables Given that async is commonly used in operations that are time-consuming, memoizing (i.e., caching) the result of an async call can definitely be worthwhile. The [`<<__Memoize>>`](../attributes/predefined-attributes.md#__memoize) attribute does the right thing, so, use that. However, if to get explicit control of the memoization, *memoize the awaitable* and not the result of awaiting it. ```Hack abstract final class MemoizeResult { private static async function time_consuming(): Awaitable<string> { await \HH\Asio\usleep(5000000); return "This really is not time consuming, but the sleep fakes it."; } private static ?string $result = null; public static async function memoize_result(): Awaitable<string> { if (self::$result === null) { self::$result = await self::time_consuming(); // don't memoize the resulting data } return self::$result; } } <<__EntryPoint>> function runMe(): void { $t1 = \microtime(true); \HH\Asio\join(MemoizeResult::memoize_result()); $t2 = \microtime(true) - $t1; $t3 = \microtime(true); \HH\Asio\join(MemoizeResult::memoize_result()); $t4 = \microtime(true) - $t3; \var_dump($t4 < $t2); // The memoized result will get here a lot faster } ``` On the surface, this seems reasonable. We want to cache the actual data associated with the awaitable. However, this can cause an undesired race condition. Imagine that there are two other async functions awaiting the result of `memoize_result`, call them `A` and `B`. The following sequence of events can happen: 1. `A` gets to run, and `await`s `memoize_result`. 2. `memoize_result` finds that the memoization cache is empty (`$result` is `null`), so it `await`s `time_consuming`. It gets suspended. 3. `B` gets to run, and `await`s `memoize_result`. Note that this is a new awaitable; it's not the same awaitable as in 1. 4. `memoize_result` again finds that the memoization cache is empty, so it awaits `time_consuming` again. Now the time-consuming operation will be done twice. If `time_consuming` has side effects (e.g., a database write), then this could end up being a serious bug. Even if there are no side effects, it's still a bug; the time-consuming operation is being done multiple times when it only needs to be done once. Instead, memoize the awaitable: ```Hack abstract final class MemoizeAwaitable { private static async function time_consuming(): Awaitable<string> { await \HH\Asio\usleep(5000000); return "Not really time consuming but sleep."; // For type-checking purposes } private static ?Awaitable<string> $handle = null; public static function memoize_handle(): Awaitable<string> { if (self::$handle === null) { self::$handle = self::time_consuming(); // memoize the awaitable } return self::$handle; } } <<__EntryPoint>> function runMe(): void { $t1 = \microtime(true); \HH\Asio\join(MemoizeAwaitable::memoize_handle()); $t2 = \microtime(true) - $t1; $t3 = \microtime(true); \HH\Asio\join(MemoizeAwaitable::memoize_handle()); $t4 = \microtime(true) - $t3; \var_dump($t4 < $t2); // The memoized result will get here a lot faster } ``` This simply caches the handle and returns it verbatim; [Async Vs Awaitable](async-vs.-awaitable.md) explains this in more detail. This would also work if it were an async function that awaited the handle after caching. This may seem unintuitive, because the function `await`s every time it's executed, even on the cache-hit path. But that's fine: on every execution except the first, `$handle` is not `null`, so a new call to `time_consuming` will not be started. The result of the one existing instance will be shared. Either approach works, but the non-async caching wrapper can be easier to reason about. ## Use Lambdas Where Possible The use of lambdas can cut down on code verbosity that comes with writing full closure syntax. Lambdas are quite useful in conjunction with the [async utility helpers](utility-functions.md). For example, look how the following three ways to accomplish the same thing can be shortened using lambdas. ```Hack async function fourth_root(num $n): Awaitable<float> { return sqrt(sqrt((float)$n)); } async function normal_call(): Awaitable<vec<float>> { $nums = vec[64, 81]; return await Vec\map_async($nums, fourth_root<>); } async function closure_call(): Awaitable<vec<float>> { $nums = vec[64, 81]; $froots = async function(num $n): Awaitable<float> { return sqrt(sqrt((float)$n)); }; return await Vec\map_async($nums, $froots); } async function lambda_call(): Awaitable<vec<float>> { $nums = vec[64, 81]; return await Vec\map_async($nums, async $num ==> sqrt(sqrt((float)$num))); } async function use_lambdas(): Awaitable<void> { $nc = await normal_call(); $cc = await closure_call(); $lc = await lambda_call(); \var_dump($nc); \var_dump($cc); \var_dump($lc); } <<__EntryPoint>> function main(): void { HH\Asio\join(use_lambdas()); } ``` ## Integrating async and non-async functions If you need to call an async function from a non-async function, the best approach is to refactor so that the caller is also async. Sometimes this might need refactoring an unmanageable number of recursive call sites, so an alternative is available - but best avoided: Imagine we are making a call to an `async` function `join_async` from a non-async scope. If refactoring to an entirely async call stack is not possible, `HH\Asio\join()` can be used to resolve the awaitable: ```Hack async function join_async(): Awaitable<string> { return "Hello"; } // In an async function, you would await an awaitable. // In a non-async function, or the global scope, you can // use `join` to force the the awaitable to run to its completion. <<__EntryPoint>> function main(): void { $s = \HH\Asio\join(join_async()); \var_dump($s); } ``` **THIS IS A COUNTEREXAMPLE**: in real-world code, the entrypoint should be made async instead. `HH\Asio\join()` is not just a blocking form of `await`: no other Hack code in the current request will be executed until the awaitable you pass to `join()` is completed, blocking the entire request until then. ## Remember Async Is NOT Multi-threading Async functions are not running at the same time. They are CPU-sharing via changes in wait state in executing code (i.e., pre-emptive multitasking). Async still lives in the single-threaded world of normal Hack! ## `await` Is Not a General Expression To strike a balance between flexibility, latency, and performance, we require that `await`s only appear in **unconditionally consumed expression positions**. For more details, see [Await As An Expression](await-as-an-expression).
Markdown
hhvm/hphp/hack/manual/hack/15-asynchronous-operations/31-examples.md
Here are some examples representing a slew of possible async scenarios. Obviously, this does not cover all possible situations, but they provide an idea of how and where async can be used effectively. Some of these examples are found spread out through the rest of the async documentation; they are added here again for consolidation purposes. ## Basic This example shows the basic tenets of async, particularly the keywords used: ```Hack // async specifies a function will return an awaitable. Awaitable<string> means // that the awaitable will ultimately return a string when complete async function trivial(): Awaitable<string> { return "Hello"; } <<__EntryPoint>> async function call_trivial(): Awaitable<void> { // These first two lines could be combined into // $result = await trivial(); // but wanted to show the process // get awaitable that you can wait for completion $aw = trivial(); // wait for the operation to complete and get the result $result = await $aw; echo $result; // "Hello" } ``` ## Joining To get the result of an awaitable in a non-async function, use `join`: ```Hack async function join_async(): Awaitable<string> { return "Hello"; } // In an async function, you would await an awaitable. // In a non-async function, or the global scope, you can // use `join` to force the the awaitable to run to its completion. <<__EntryPoint>> function main(): void { $s = \HH\Asio\join(join_async()); \var_dump($s); } ``` ## Async Closures and Lambdas Closure and lambda expressions can involve async functions: ```Hack <<__EntryPoint>> async function closure_async(): Awaitable<void> { // closure $hello = async function(): Awaitable<string> { return 'Hello'; }; // lambda $bye = async ($str) ==> $str; // The call style to either closure or lambda is the same $rh = await $hello(); $rb = await $bye("bye"); echo $rh." ".$rb.\PHP_EOL; } ``` ## Data Fetching This shows a way to organize async functions such that we have a nice clean data dependency graph: ```Hack class PostData { // using constructor argument promotion public function __construct(public string $text) {} } async function fetch_all_post_ids_for_author( int $author_id, ): Awaitable<vec<int>> { // Query database, etc., but for now, just return made up stuff return vec[4, 53, 99]; } async function fetch_post_data(int $post_id): Awaitable<PostData> { // Query database, etc. but for now, return something random return new PostData(\str_shuffle("ABCDEFGHIJKLMNOPQRSTUVWXYZ")); } async function fetch_comment_count(int $post_id): Awaitable<int> { // Query database, etc., but for now, return something random return \rand(0, 50); } async function fetch_page_data( int $author_id, ): Awaitable<vec<(PostData, int)>> { $all_post_ids = await fetch_all_post_ids_for_author($author_id); // An async closure that will turn a post ID into a tuple of // post data and comment count $post_fetcher = async function(int $post_id): Awaitable<(PostData, int)> { concurrent { $post_data = await fetch_post_data($post_id); $comment_count = await fetch_comment_count($post_id); } return tuple($post_data, $comment_count); // alternatively: $_return = tuple( await fetch_post_data($post_id), await fetch_comment_count($post_id), ); }; // Transform the array of post IDs into a vec of results, // using the Vec\map_async function return await Vec\map_async($all_post_ids, $post_fetcher); } async function generate_page(int $author_id): Awaitable<string> { $tuples = await fetch_page_data($author_id); $page = ""; foreach ($tuples as $tuple) { list($post_data, $comment_count) = $tuple; // Normally render the data into HTML, but for now, just create a // normal string $page .= $post_data->text." ".$comment_count.\PHP_EOL; } return $page; } <<__EntryPoint>> function main(): void { print \HH\Asio\join(generate_page(13324)); // just made up a user id } ``` ## Batching Use rescheduling (via `HH\Asio\later`) to batch up operations to send multiple keys in a single request over a high latency network (for example purposes, the network isn't high latency, but just returns something random): ```Hack async function b_one(string $key): Awaitable<string> { $subkey = await Batcher::lookup($key); return await Batcher::lookup($subkey); } async function b_two(string $key): Awaitable<string> { return await Batcher::lookup($key); } async function batching(): Awaitable<void> { $results = await Vec\from_async(vec[b_one('hello'), b_two('world')]); \printf("%s\n%s\n", $results[0], $results[1]); } <<__EntryPoint>> function main(): void { \HH\Asio\join(batching()); } class Batcher { private static vec<string> $pendingKeys = vec[]; private static ?Awaitable<dict<string, string>> $aw = null; public static async function lookup(string $key): Awaitable<string> { // Add this key to the pending batch self::$pendingKeys[] = $key; // If there's no awaitable about to start, create a new one if (self::$aw === null) { self::$aw = self::go(); } // Wait for the batch to complete, and get our result from it $results = await self::$aw; return $results[$key]; } private static async function go(): Awaitable<dict<string, string>> { // Let other awaitables get into this batch await \HH\Asio\later(); // Now this batch has started; clear the shared state $keys = self::$pendingKeys; self::$pendingKeys = vec[]; self::$aw = null; // Do the multi-key roundtrip return await multi_key_lookup($keys); } } async function multi_key_lookup( vec<string> $keys, ): Awaitable<dict<string, string>> { // lookup multiple keys, but, for now, return something random $r = dict[]; foreach ($keys as $key) { $r[$key] = \str_shuffle("ABCDEF"); } return $r; } ``` ## Polling We can use rescheduling in a polling loop to allow other awaitables to run. A polling loop may be needed where a service does not have an async function to add to the scheduler: ```Hack // Of course, this is all made up :) class Polling { private int $count = 0; public function isReady(): bool { $this->count++; if ($this->count > 10) { return true; } return false; } public function getResult(): int { return 23; } } async function do_polling(Polling $p): Awaitable<int> { echo "do polling 1".\PHP_EOL; // No async function in Polling, so loop until we are ready, but let // other awaitables go via later() while (!$p->isReady()) { await \HH\Asio\later(); } echo "\ndo polling 2".\PHP_EOL; return $p->getResult(); } async function no_polling(): Awaitable<string> { echo '.'; return \str_shuffle("ABCDEFGH"); } async function polling_example(): Awaitable<void> { $handles = vec[do_polling(new Polling())]; // To make this semi-realistic, call no_polling a bunch of times to show // that do_polling is waiting. for ($i = 0; $i < 50; $i++) { $handles[] = no_polling(); } $results = await Vec\from_async($handles); } <<__EntryPoint>> function main(): void { \HH\Asio\join(polling_example()); } ```
Markdown
hhvm/hphp/hack/manual/hack/16-readonly/01-introduction.md
`readonly` is a keyword used to create immutable references to [Objects](/hack/classes/introduction) and their properties. ### How does it work? Expressions in Hack can be annotated with the `readonly` keyword. When an object or reference is readonly, there are two main constraints on it: * **Readonlyness:** Object properties cannot be modified (i.e. mutated). * **Deepness:** All nested properties of a readonly value are readonly. ### Readonlyness Object properties of `readonly` values cannot be modified (i.e. mutated). ```Hack error class Bar { public function __construct( public Foo $foo, ){} } class Foo { public function __construct( public int $prop, ) {} } function test(readonly Foo $x) : void { $x->prop = 4; // error, $x is readonly, its properties cannot be modified } ``` ### Deepness All nested properties of `readonly` objects are readonly. ``` Hack error function test(readonly Bar $x) : void { $foo = $x->foo; $foo->prop = 3; // error, $foo is readonly } ``` ### How is `readonly` different from contexts and capabilities that control property mutation (such as `write_props`)? [Contexts](/hack/contexts-and-capabilities/available-contexts-and-capabilities) such as `write_props` affect an entire function (and all of its callees), whereas readonly affects specific values / expressions. ### Topics covered in this section * [Syntax](syntax.md): Basic syntax for readonly keyword * [Subtyping](subtyping.md): Rules and semantics for interacting with readonly and mutable values * [Explicit Readonly Keywords](explicit-readonly-keywords.md): Positions where the readonly keyword is explicitly required * [Containers and Collections](containers-and-collections.md): Interactions between collections of readonly values * [Advanced Features and Semantics](advanced-semantics.md): More complex features and interactions
Markdown
hhvm/hphp/hack/manual/hack/16-readonly/02-syntax.md
The `readonly` keyword can be applied to various positions in Hack. ## Parameters and return values Parameters and return values of any callable (e.g. a function or method) can be marked `readonly`. ```Hack class Bar { public function __construct( public Foo $foo, ){} } class Foo { public function __construct( public int $prop, ) {} } function getFoo(readonly Bar $x): readonly Foo { return $x->foo; } ``` A readonly *parameter* signals that the function/method will not modify that parameter when called. A readonly *return type* signals that the function returns a readonly reference to an object that cannot be modified. ## Static and regular properties Static and regular properties marked as `readonly` cannot be modified. ```Hack class Bar {} class Foo { private static readonly ?Bar $static_bar = null; public function __construct( private readonly Bar $bar, ){} } ``` A readonly property represents a property that holds a readonly reference (specifically, that the nested object within the property cannot be modified). ## Lambdas and function type signatures `readonly` is allowed on inner parameters and return types on function typehints. ```Hack class Bar {} function call( (function(readonly Bar) : readonly Bar) $f, readonly Bar $arg, ) : readonly Bar { return readonly $f($arg); } ``` ## Expressions `readonly` can appear on expressions to convert mutable values to readonly. ```Hack class Foo {} function foo(): void { $x = new Foo(); $y = readonly $x; } ``` ## Functions / Methods `readonly` can appear as a modifier on instance methods, signaling that `$this` is readonly (i.e, that the method promises not to modify the instance). ``` Hack error class C { public function __construct(public int $prop) {} public readonly function foo() : void { $this->prop = 4; // error, $this is readonly. } } ``` Note that readonly objects can only call readonly methods, since they promise not to modify the object. ``` Hack error class Data {} class Box { public function __construct(public Data $data) {} public readonly function getData(): readonly Data { return $this->data; } public function setData(Data $d) : void { $this->data = $d; } } function readonly_method_example(readonly Box $b): void { $y = readonly $b->getData(); // ok, $y is readonly $b->setData(new Data()); // error, $b is readonly, it can only call readonly methods } ``` ## Closures and function types A function type can be marked readonly: `(readonly function(T1): T)`. Denoting a function/closure as readonly adds the restriction that the function/closure captures all values as readonly: ``` Hack error function readonly_closure_example(): void { $x = new Foo(); $f = readonly () ==> { $x->prop = 4; // error, $x is readonly here! }; } ``` One way to make sense of this behavior is to think of closures as an object whose properties are the values it captures, which implement a special invocation function that executes the closure. A readonly closure is then defined as a closure whose invocation function is annotated with readonly. Readonly closures affect Hack’s type system; readonly closures are subtypes of their mutable counterparts. That is, a `(readonly function(T1):T2)` is a strict subtype of a `(function(T1): T2)`.
Markdown
hhvm/hphp/hack/manual/hack/16-readonly/03-subtyping.md
From a typing perspective, one can think of a readonly object as a [supertype](/hack/types/supertypes-and-subtypes) of its mutable counterpart. For example, readonly values cannot be passed to a function that takes mutable values. ```Hack error class Foo { public int $prop = 0; } function takes_mutable(Foo $x): void { $x->prop = 4; } function test(): void { $z = readonly new Foo(); takes_mutable($z); // error, takes_mutable's first parameter // is mutable, but $z is readonly } ``` Similarly, functions cannot return readonly values unless they are annotated to return readonly. ```Hack error class Foo {} function returns_mutable(readonly Foo $x): Foo { return $x; // error, $x is readonly } function returns_readonly(readonly Foo $x): readonly Foo { return $x; // correct } ``` Note that non-readonly (i.e. mutable) values *can* be passed to a function that takes a readonly parameter: ```Hack class Foo {} // promises not to modify $x function takes_readonly(readonly Foo $x): void { } function test(): void { $z = new Foo(); takes_readonly($z); // ok } ``` Similarly, class properties cannot be set to readonly values unless they are declared as readonly properties. ```Hack error class Bar {} class Foo { public function __construct( public readonly Bar $ro_prop, public Bar $mut_prop ){} } function test( Foo $x, readonly Bar $bar, ) : void { $x->mut_prop = $bar; // error, $bar is readonly but the prop is mutable $x->ro_prop = $bar; // ok } ```
Markdown
hhvm/hphp/hack/manual/hack/16-readonly/04-explicit-readonly-keywords.md
There are a few places where an explicit readonly keyword is required when using readonly values. ## Calling a readonly function Calling a function or method that returns readonly requires wrapping the result in a readonly expression. ```Hack class Foo {} function returns_readonly(): readonly Foo { return readonly new Foo(); } function test(): void { $x = readonly returns_readonly(); // this is required to call returns_readonly() } ``` ## Accessing readonly properties Accessing a readonly property (i.e. a property annotated readonly at the declaration, not accessing a property off of a readonly object) requires readonly annotation. ```Hack class Bar {} class Foo { public function __construct( public readonly Bar $bar, ) {} } function test(Foo $f): void { $bar = readonly $f->bar; // this is required } ``` ## Interactions with [Coeffects](https://docs.hhvm.com/hack/contexts-and-capabilities/available-contexts-and-capabilities) If your function has the `ReadGlobals` capability but not the `AccessGlobals` capability (i.e. is marked `read_globals` or `leak_safe`), it can only access class static variables if they are wrapped in a readonly expression: ```Hack <<file:__EnableUnstableFeatures("readonly")>> class Bar {} class Foo { public static readonly ?Bar $bar = null; } function read_static()[read_globals]: void { $y = readonly Foo::$bar; // keyword required } function read_static2()[leak_safe]: void { $y = readonly Foo::$bar; // keyword required } ```
Markdown
hhvm/hphp/hack/manual/hack/16-readonly/05-containers-and-collections.md
## Basics Readonly values cannot be written to normal container types (such as`vec`, `Vector`, or `dict`): ```Hack error class Foo {} function container_example(readonly Foo $x) : void { $container = vec[]; $container[] = $x; // error, $x is readonly } ``` To use readonly values within a container, you can either declare the values in an array literal, or declare an array type (i.e. `vec` or `dict`) as readonly and append to it. Note that the entire container literal is readonly if any of its contents are readonly. ```Hack class Foo {} function container_example2(readonly Foo $x) : void { $container = readonly vec[]; // container is now a readonly vec $container_literal = vec[new Foo(), readonly new Foo()]; // $container_literal is readonly } ``` Foreaching over a readonly container results in readonly values: ```Hack error class Foo { public function __construct(public int $prop) {} } function container_foreach(readonly vec<Foo> $vec): void { foreach($vec as $elem) { $elem->prop = 3; // error, $elem is readonly } } ``` ### Readonly and Collection types Readonly has only limited support with object collection types like `Vector`, `Map` and `Pair`. Specifically, you can declare readonly collection literals of readonly values to create a readonly collection type (i.e a `readonly Vector<Foo>`), but since collection types themselves are mutable objects, you cannot append to or modify a readonly collection. ```Hack error class Foo {} function collection_example(): void { $v = Vector { new Foo(), readonly new Foo() }; // $v is readonly since at least one of its contents is readonly $v[] = new Foo(); // error, $v is readonly and not a value type, so it cannot be appended } ```
Markdown
hhvm/hphp/hack/manual/hack/16-readonly/06-advanced-semantics.md
This page lists some more complicated interactions and nuances with readonly. ## `readonly (function (): T)` versus `(readonly function(): T)`: references vs. objects A `(readonly function(): T)` may look very similar to a `readonly (function(): T)`, but they are actually different. The first denotes a readonly closure object, which at definition time, captured readonly values. The second denotes a readonly **reference** to a regular, mutable closure object: ```Hack function readonly_closures_example2<T>( (function (): T) $regular_f, (readonly function(): T) $ro_f, ) : void { $ro_regular_f = readonly $regular_f; // readonly (function(): T) $ro_f; // (readonly function(): T) $ro_ro_f = readonly $ro_f; // readonly (readonly function(): T) } ``` Since calling a mutable closure object can modify itself (and its captured values), a readonly reference to a regular closure **cannot** be called. ```Hack error function readonly_closure_call<T>( (function (): T) $regular_f, (readonly function(): T) $ro_f, ) : void { $ro_regular_f = readonly $regular_f; // readonly (function(): T) $ro_regular_f(); // error, $ro_regular_f is a readonly reference to a regular function } ``` But a readonly closure object can have readonly references and call them, since they cannot modify the original closure object on call: ```Hack error function readonly_closure_call2<T>( (function (): T) $regular_f, (readonly function(): T) $ro_f, ) : void { $ro_regular_f = readonly $regular_f; // readonly (function(): T) $ro_regular_f(); // error, $ro_regular_f is a readonly reference to a regular function $ro_ro_f = readonly $ro_f; // readonly (readonly function(): T) $ro_ro_f(); // safe } ``` ## Converting to non-readonly Sometimes you may encounter a readonly value that isn’t an object (e.g.. a readonly int, due to the deepness property of readonly). In those cases, instead of returning a readonly int, you’ll want a way to tell Hack that the value you have is actually a value type. You can use the function `HH\Readonly\as_mut()` to convert any primitive type from readonly to mutable. Use `HH\Readonly\as_mut()` strictly for primitive types and value-type collections of primitive types (i.e. a vec of int). ```Hack class Foo { public function __construct( public int $prop, ) {} public readonly function get() : int { $result = $this->prop; // here, $result is readonly, but its also an int. return \HH\Readonly\as_mut($this->prop); // convert to a non-readonly value } } ```
Markdown
hhvm/hphp/hack/manual/hack/17-modules/01-introduction.md
Modules are an experimental feature for organizing code and separating your internal and external APIs. Modules are collections of Hack files that share an identity or utility. ## Module definitions You can define a new module with the `new module` keywords. ```hack file:foomodule.hack //// module.hack new module foo {} ``` Modules do not share a namespace with other symbols. Module names can contain periods `.` to help delineate between directories or logical units. Periods in module names do not currently have any semantic meaning. ```hack new module foo {} new module foo.bar {} new module foo.bar.test {} ``` ## Module membership Any Hack file can be placed in a defined module by writing `module <module name>` at the top of the file. ```hack no-extract module foo; class Foo { // ... } ``` ## Module level visibility: `internal` By placing your code in modules, you can use a new visibility keyword: `internal`. An `internal` symbol can only be accessed from within the module. ```hack file:foomodule.hack //// foo_class.hack module foo; public class Foo {} internal class FooInternal { public function foo(): void {} internal function bar(): void {} } internal function foo_fun(): void {} ``` An internal symbol cannot be accessed outside of the module it's defined in. ```hack no-extract module bar; public function bar_test(): void { $x = new FooInternal(); // error! FooInternal is internal to module foo. } ```
Markdown
hhvm/hphp/hack/manual/hack/17-modules/02-defining-modules.md
## Defining modules You can define a module with the `new module` syntax. A module, just like any other toplevel entity (classes, functions, etc), can have at most one definition. ```hack new module foo {} ``` Module names live in their own namespace, and do not conflict with classes, functions, etc. Module names are **not** affected by namespaces. ```Hack no-extract namespace Bar; module foo; function foo(): void {} ``` Currently, module bodies are empty. This will change in future versions of Hack as we build more support for modules and organizing their relationships. # Module membership A module can be thought of as a logical structure of code organized into a list of files. To add a file to a module, use the `module foo;` syntax at the top of the file. ```Hack no-extract // This file is now a member of module foo module foo; class MyFoo { // ... } ``` A file can have at most one module membership statement, and the statement must be before any symbol in the file (File attributes and namespace declarations can appear before module membership statements, as they are not referenceable symbols). For clarity, module definitions (i.e. `new module`) cannot be placed within any module. ```hack error module foo; // ok module bar; // not okay: duplicate module membership statement ``` ```hack error module bar; // not okay: module definitions must live outside of files already in a module new module foo {} ```
Markdown
hhvm/hphp/hack/manual/hack/17-modules/03-using-internal.md
## Internal and module level visibility One goal of using modules is to separate a code unit's public and private APIs. If a file is part of a module, its toplevel functions, classes, interfaces, traits, enums, and typedefs can be marked `internal`. An internal toplevel symbol cannot be referenced outside of its module. If a symbol is not internal, it is `public`, and it's part of the public API of the module. You can optionally use the `public` keyword on toplevel symbols to denote them as public. ```hack no-extract module foo; internal class FooInternal {} internal trait TFoo {} internal interface IFoo {} internal newtype TInternal = FooInternal; internal function foo_internal(): void {} ``` ```hack no-extract module bar; // error: FooInternal is internal, it cannot be referenced outside of its module public function foo(): FooInternal {} ``` Methods and properties within classes also gain a new visibility `internal`, which means that they can only be accessed or called within the module. ```hack no-extract module foo; public class FooPublic { internal function foo(): void { echo "foo!\n"; } internal int $prop = 5; public function bar(): void { echo "bar!\n"; } } ``` An internal method or property can be called anywhere from within a module. `internal` replaces the visibility keyword of the method or propertiy (i.e. `protected`, `public` or `private`). Note that **method and property visibilities do not have to match the visibility of the class itself**: an internal class can have public methods, and a public class can have internal methods. You can think of the visibility on a toplevel symbol to represent where a symbol is allowed to be referenced, whereas the visibility of a method or property to represent where that individual member can be accessed. If you try calling an internal method or accessing a property from outside of the module, you'll get a runtime error. ```hack no-extract module bar; <<__EntryPoint>> function test(): void { $x = new FooPublic(); // ok since Foo is a public class $x->bar(); // prints "bar!" $x->foo(); // error, foo is an internal method being called from outside the module. $x->prop = 5; // error, $x::prop is an internal property being accessed outside of the module. } ``` You'll also get an error if you reference an internal symbol in any code outside of the module it's defined in (i.e., in typehints, constructor classnames, is/as statements): ```hack no-extract module bar; <<__EntryPoint>> function test(IFoo $x): void { //^^^^ error, IFoo is internal to module foo $a = new FooInternal(); // error $b = FooInternal::class; // error $c = $x as FooInternal; // error $d = foo_internal<>; // error } ``` We will go over the inheritance and override rules in a different section. ## Referencing internal symbols in your public API Public symbols within your module generally cannot reference internal symbols directly. ```hack no-extract module foo; internal class Secret { internal function mySecret(): int { return 42; } } public function foo(): Secret { // error, public API users wouldn't know what a Secret is return new Secret(); } ``` In order to expose Secret to outside users, you can use a public interface. ```hack no-extract module foo; public interface PublicFoo { public function myPublic(): int; } internal class Secret implements PublicFoo { public function myPublic(): int { return $this->mySecret(); } internal function mySecret(): int { return 42; } } public function foo(): PublicFoo { // return new Secret(); } ``` At runtime, if code from another module calls `foo`, it will receive a Secret object. However, statically, any function that calls foo must respect the defined PublicFoo interface. ```hack no-extract module bar; <<__EntryPoint>> public function test(): void { $x = foo(); // $x has type Secret at runtime $x->myPublic(); // returns 42 $x->mySecret(); // typechecker error, $x is type Public, it does not have a method called mySecret(). } ```
Markdown
hhvm/hphp/hack/manual/hack/17-modules/04-inheritance.md
## Inheriting methods and properties In general, override rules for internal class members are consistent with that of private and protected: you can only override a class member with a visibility that's at least as visible as the previous. ```hack no-extract module foo; class Foo { internal function foo(): void {} public function bar(): void {} internal function baz(): void {} } class Bar extends Foo { <<__Override>> public function foo(): void {} // ok <<__Override>> internal function bar(): void {} // error, overriding a public method with a lower visibility <<__Override>> private function baz(): void {} // ok } ``` Note that `internal` and `protected` do not encompass each other in terms of visibility. Therefore, you can never override an internal member with a protected one, or vice versa. The same rule applies when implementing an interface: ```hack no-extract interface IFoo { public function bar(): void; internal function baz(): void; } class Foo implements IFoo { // You must implement a public function in an interface with another public one public function bar(): void {} // You **can** implement an internal function in an interface with a public one public function baz(): void {} } ``` ## Inheriting toplevel symbols Unlike with methods and properties, within the same module, an internal class can override a public one, and vice versa. ```hack no-extract public class Bar {} internal class Foo extends Bar {} public class Baz extends Foo {} ``` You can think of this behavior as freely choosing which symbols in your module to export to your public API. Since the visibility of a toplevel entity only affects how it is statically referenced, no inheritance rules need to be applied when overriding them. You cannot, however, extend an internal class, implement an internal interface, or use an internal trait from a different module. ```hack //// newmodule.hack new module foo {} //// foo.hack module foo; internal interface IFoo { //... } class Foo implements IFoo {} // ok ``` ```hack no-extract module bar; class Bar implements IFoo {} // error, IFoo is internal to module foo ```
Markdown
hhvm/hphp/hack/manual/hack/17-modules/05-traits.md
Traits have special behavior in Hack when used with modules. ## Marking traits internal An internal trait can only be used within the module it's defined. Internal traits can have public, protected, or internal methods. ```hack //// newmodule.hack new module foo {} //// foo.hack module foo; internal trait TFoo { public function foo(): void {} internal function bar(): void {} } ``` ```hack no-extract module bar; public class Bar { use TFoo; // error, TFoo is internal } ``` ## Public traits Hack supports two different module semantics for public traits. By default, since public traits by nature can have their implementations copied to any class in any other module, public traits cannot access any internal symbols or implementations from the module they are defined in. You can think of public traits as not belonging to any specific module, even if they are defined within one. ```hack no-extract module foo; internal class Foo {} // Assume TFoo is defined as before public trait TBar { use TFoo; // error, TBar is a public trait, it cannot access internal symbols in module foo public function foo(): mixed { return new Foo(); // error, TBar is a public trait, it cannot access internal symbols in module foo } } ``` As experimental feature, the programmer can however declare a public trait to belong to the module where the trait was itself defined, by adding the `<<__ModuleLevelTrait>>` attribute to the trait definition. By doing so the methods of the trait can access the internal symbols and implementations of the module they are defined in. For instance the following code is accepted: ```hack no-extract /// file a.php <<file: __EnableUnstableFeatures('module_level_traits')>> module A; internal function foo(): void { echo "I am foo in A\n"; } <<__ModuleLevelTrait>> public trait T { public function getFoo(): void { foo(); // both getFoo and foo belong to module A } } /// file b.php module B; class C { use T; } <<__EntryPoint>> function bar(): void { (new C())->getFoo(); // prints "I am foo in A" } ``` Module level traits are especially useful in conjunction with the `<<__Sealed(...)>>` attribute to export selectively internal module functionalities, mimicking C++ friends modules. Public traits cannot have internal methods or properties, as they may be used by classes outside of any module. ```hack no-extract public trait TBar { internal function foo(): void {} // error, public traits cannot have internal methods or properties } ```
Markdown
hhvm/hphp/hack/manual/hack/17-modules/06-type-aliases.md
Type aliases have special rules when it comes to internal types depending on which kind of type alias is used. ## Internal type aliases A type alias declared with `type` can be marked internal. Just as with classes, this means that the type can only be referenced from within the module. ```hack //// newmodule.hack new module foo {} //// foo.hack module foo; internal class Foo {} internal type FooInternal = Foo; internal newtype FooOpaque = FooInternal; internal newtype FooOpaque2 as Foo = Foo; ``` Internal newtypes can also be constrained by other internal types, since they can only be used from within the module. ## Public Opaque type aliases Since public opaque type aliases hide their implementations from users outside of the current file, you can implement them with internal types. The opaque type alias acts as an empty interface for the internal type. You cannot, however, constrain them with an internal type, since a public user would not know what type it's being constrained by. ```hack no-extract newtype FooOpaque = FooInternal; // ok newtype FooErr as FooInternal = FooInternal; // error, FooInternal is an internal type, cannot be used as constraint ``` ## Public transparent type aliases Transparent type aliases leak their implementation, so they cannot be implemented by internal types. ```no-extract type FooOpaque = FooInternal; // error, cannot use internal type FooInternal in transparent type FooOpaque. ``` ## Module-level type aliases We also introduce a new type alias known as a **module-level** type alias. You can create one using the syntax `module newtype TFoo as ... = ...`. A module-level type alias is opaque outside of the module it's defined in, and transparent inside (rather than just being opaque outside of the file it's defined in). Since they hide their implementations from outside the module, you can use internal types from within a module to implement them. They still cannot be constrained by internal types. ```hack no-extract module newtype FooModule = FooInternal; // ok module newtype FooModuleErr as FooInternal = FooInternal; // error, FooInternal is an internal type, cannot be used as a constraint ``` Since the purpose of module newtypes is to create an interface surrounding a module boundary, you cannot mark module newtypes themselves internal. ```hack error internal module newtype FooModuleErr2 = int; // Parse error ```
Markdown
hhvm/hphp/hack/manual/hack/17-modules/07-closures-and-function-pointers.md
Within a module, you can create a pointer to an internal function and pass it anywhere for use. Pointers to internal functions can only be created from within a module, but can be called and acccessed from anywhere. ```hack //// newmodule.hack new module foo {} //// foo.hack module foo; internal function f() : void { echo "Internal f\n"; } public function getF(): (function():void) { return f<>; } ``` ```hack no-extract module bar; public function test(): void { $f = getF(); $f(); // prints "Internal f"; } ``` Similarly, a closure can access internal symbols from the module it's defined in, but can be called from any location in code. ```hack //// newmodule.hack new module foo {} //// foo.hack module foo; internal function f() : void { echo "Internal f\n"; } public function getF(): (function():void) { return () ==> { f(); }; // ok } ``` ```hack no-extract module bar; public function test(): void { $f = getF(); $f(); // prints "Internal f"; } ``` However, calling a function via string invocation must respect module boundaries. That is, if you try to call a function from outside of the current module using a string invocation, the runtime will throw an error. (The typechecker already bans this type of dynamic behavior). ```hack no-extract module bar; public function test(): void { $f = "f"; $f(); // runtime error, f is internal to module foo } ```
Markdown
hhvm/hphp/hack/manual/hack/17-modules/08-reflection-and-migration.md
## Reflection You can reflect on the module of a class or function using its corresponding methods. ```Hack no-extract ReflectionClass::getModule(); ReflectionFunctionAbstract::getModule(); ``` You can check if a class, method or property is internal with the `isInternalToModule()` function. ```hack no-extract ReflectionClass::isInternalToModule(); ReflectionFunctionAbstract::isInternalToModule(); ``` ## Migration and <<__SoftInternal>> When migrating existing code to use internal, you can use the <<__SoftInternal>> attribute to help detect dynamic usages of the code outside of the module. Internal symbols with <<__SoftInternal>> will raise a warning in HHVM instead of an exception. ```hack //// newmodule.hack new module foo {} //// foo.hack module foo; class Cls { <<__SoftInternal>> internal function foo_soft(): void { echo "Hello from foo_soft\n"; } } ``` Calling Cls::foo_soft() from outside the code: ```hack no-extract module bar; <<__EntryPoint>> function test(): void { Cls::foo_soft(); } ``` will result in the following output from HHVM: ``` Warning: Accessing soft internal method Cls::foo_soft in module foo from module bar is not allowed in test.php on line 4 Hello from foo_soft ```
Markdown
hhvm/hphp/hack/manual/hack/20-attributes/01-introduction.md
Attributes attach metadata to Hack definitions. Hack provides built-in attributes that can change runtime or typechecker behavior. ```Hack <<__Memoize>> function add_one(int $x): int { return $x + 1; } ``` You can attach multiple attributes to a definition, and attributes can have arguments. ``` Hack <<__ConsistentConstruct>> class OtherClass { <<__Memoize, __Deprecated("Use FooClass methods instead")>> public function addOne(int $x): int { return $x + 1; } } ``` ## Defining an attribute You can define your own attribute by implementing an attribute interface in the HH namespace. ```Hack file:contributors.hack class Contributors implements HH\ClassAttribute { public function __construct(private string $author, private ?keyset<string> $maintainers = null) {} public function getAuthor(): string { return $this->author; } public function getMaintainers(): keyset<string> { return $this->maintainers ?? keyset[$this->author]; } } <<Contributors("John Doe", keyset["ORM Team", "Core Library Team"])>> class MyClass {} <<Contributors("You")>> class YourClass {} ``` Other common attribute interfaces are `HH\FunctionAttribute`, `HH\MethodAttribute` and `HH\PropertyAttribute`, but see [the Hack interface reference](/hack/reference/interface/) for the full list. ## Accessing attribute arguments You need to use reflection to access attribute arguments. Given the `MyClass` example defined above: ```Hack file:contributors.hack $rc = new ReflectionClass('MyClass'); $my_class_contributors = $rc->getAttributeClass(Contributors::class); $my_class_contributors?->getAuthor(); // "John Doe" $my_class_contributors?->getMaintainers(); // keyset["ORM Team", "Core Library Team"] ```
Markdown
hhvm/hphp/hack/manual/hack/20-attributes/07-predefined-attributes.md
The following attributes are defined: * [__AcceptDisposable](#__acceptdisposable) * [__ConsistentConstruct](#__consistentconstruct) * [__Deprecated](#__deprecated) * [__Docs](#__docs) * [__DynamicallyCallable](#__dynamicallycallable) * [__DynamicallyConstructible](#__dynamicallyconstructible) * [__EnableMethodTraitDiamond](#__enablemethodtraitdiamond) * [__Enforceable](#__enforceable) * [__EntryPoint](#__entrypoint) * [__Explicit](#__explicit) * [__LateInit](#__lateinit) * [__LSB](#__lsb) * [__Memoize](#__memoize) * [__MemoizeLSB](#__memoizelsb) * [__MockClass](#__mockclass) * [__ModuleLevelTrait](#__moduleleveltrait) * [__Newable](#__newable) * [__Override](#__override) * [__PHPStdLib](#__phpstdlib) * [__ReturnDisposable](#__returndisposable) * [__Sealed](#__sealed) * [__Soft](#__soft) ## __AcceptDisposable This attribute can be applied to a function parameter that has a type that implements interface `IDisposable` or `IAsyncDisposable`. See [object disposal](../classes/object-disposal.md) for an example of its use. ## __ConsistentConstruct When a method is overridden in a derived class, it must have exactly the same number, type, and order of parameters as that in the base class. However, that is not usually the case for constructors. Having a family of constructors with different signatures can cause a problem, however, especially when using `new static`. This attribute can be applied to classes; it has no attribute values. Consider the following example: ```Hack <<__ConsistentConstruct>> class Base { public function __construct() {} public static function make(): this { return new static(); } } class Derived extends Base { public function __construct() { parent::__construct(); } } function demo(): void { $v2 = Derived::make(); } ``` When `make` is called on a `Derived` object, `new static` results in `Derived`'s constructor being called knowing only the parameter list of `Base`'s constructor. As such, `Derived`'s constructor must either have the exact same signature as `Base`'s constructor, or the same plus an ellipsis indicating a trailing variable-argument list. ## __Deprecated If you mark a function with `__Deprecated`, the Hack typechecker will find all static invocations of that function and mark them as errors so that you can find those invocations and fix them as needed. For runtime invocations, any function marked with `__Deprecated` will still be called successfully, but with runtime logging so that you can find and fix those dynamic invocations later. Consider the following example: ```Hack <<__Deprecated("This function has been replaced by do_that", 7)>> function do_this(): void { /* ... */ } ``` The presence of this attribute on a function has no effect, unless that function is actually called, in which case, for each call to that function, HHVM raises a notice containing the text from the first attribute value. The optional `int`-typed second attribute value (in this case, 7) indicates a *sampling rate*. Every 1/sampling-rate calls (as in, 1/7) to that function will raise a notice at runtime. If omitted, the default sampling rate is 1 (i.e. all calls raise notices). To disable runtime notices, use a sampling rate of 0. ## __Docs Associates a documentation URL with a type. ```Hack file:base.hack <<__Docs("http://www.example.com/my_framework")>> class MyFrameworkBaseClass {} ``` The IDE will include this URL when hovering over the `MyFrameworkBaseClass` type name. ```Hack file:base.hack class MyClass extends MyFrameworkBaseClass {} ``` Docs URLs are also inherited. Hovering over the `MyClass` type name will also show the docs URL. ## __DynamicallyCallable Allows a function or method to be called dynamically, based on a string of its name. HHVM will warn on error (depending on configuration) on dynamic calls to functions or methods without this attribute. ## __DynamicallyConstructible Allows this class to be instantiated dynamically, based on a string of its name. HHVM will warn on error (depending on configuration) on dynamic instantiations of classes without this attribute. ## __EnableMethodTraitDiamond This attribute can be applied to a class or trait to enable resolution of traits used along multiple paths. See [using a trait](../traits-and-interfaces/using-a-trait.md) for an example of its use. ## __Enforceable A type is _enforceable_ if it can be used in `is` and `as` expressions. Examples of non-enforceable types are function types and erased (non-reified) generics. The `__Enforceable` attribute is used to annotate abstract type constants so they can only be instantiated with enforceable types, and thus used in `is` and `as` expressions. The attribute restricts deriving type constants to values that are valid for a type test. ```Hack error abstract class A { abstract const type Tnoenf; <<__Enforceable>> abstract const type Tenf; public function f(mixed $m): void { $m as this::Tenf; // OK $m as this::Tnoenf; // Hack error } } class B1 extends A { const type Tnoenf = (function (): void); // ok const type Tenf = (function (): void); // Hack error, function types cannot be used in type tests } class B2 extends A { const type Tnoenf = (function (): void); // ok const type Tenf = int; // ok } ``` Similarly, the `__Enforceable` attribute can also be used to annotate reified generics, enabling the generic to be used in a type test expression. ## __Explicit Requires callers to explicitly specify the value for a generic type. Normally Hack allows generics to be inferred at the call site. ```Hack error function values_are_equal<<<__Explicit>> T>(T $x, T $y): bool { return $x === $y; } function example_usage(int $x, int $y, string $s): void { values_are_equal<int>($x, $y); // Without <<__Explicit>>, this code would be fine, even though // it always returns false. values_are_equal($x, $s); } ``` ## __EntryPoint A Hack program begins execution at a top-level function referred to as the *entry-point function*. A top-level function can be designated as such using this attribute, which has no attribute values. For example: ```Hack <<__EntryPoint>> function main(): void { printf("Hello, World!\n"); } ``` Note: An entry-point function will *not* be automatically executed if the file containing such a function is included via require or the autoloader. ## __LateInit Hack normally requires properties to be initialized, either with an initial value on the property definition or inside the constructor. `__LateInit` disables this check. ```Hack class Foo {} class Bar { <<__LateInit>> private Foo $f; public function trustMeThisIsCalledEarly(): void { $this->f = new Foo(); } } ``` **This is intended for testing**, where it's common to have a setup function that initializes values. Accessing a property that is not initialized produces a runtime error. `__LateInit` can also be used with static properties. ```Hack class Foo {} class Bar { <<__LateInit>> private static Foo $f; public static function trustMeThisIsCalledEarly(): void { self::$f = new Foo(); } } ``` It may be clearer to write your code using a memoized static method instead of a static property with `__LateInit`. ## __LSB Marks this property as implicitly redeclared on all subclasses. This ensures each subclass has its own value for the property. ## __Memoize The presence of this attribute causes the designated method to automatically cache each value it looks up and returns, so future calls with the same parameters can be retrieved more efficiently. The set of parameters is hashed into a single hash key, so changing the type, number, and/or order of the parameters can change that key. Functions with variadic parameters can not be memoized. This attribute can be applied to functions and static or instance methods; it has no attribute values. Consider the following example: ```Hack no-extract class Item { <<__Memoize>> public static function get_name_from_product_code(int $productCode): string { if (name-in-cache) { return name-from-cache; } else { return Item::get_name_from_storage($productCode); } } private static function get_name_from_storage(int $productCode): string { // get name from alternate store return ...; } } ``` `Item::get_name_from_storage` will only be called if the given product code is not in the cache. The types of the parameters are restricted to the following: `null`, `bool`, `int`, `float`, `string`, any object type that implements `IMemoizeParam`, enum constants, tuples, shapes, and arrays/collections containing any supported element type. The interface type `IMemoizeParam` assists with memoizing objects passed to async functions. You can clear the cache with `HH\clear_static_memoization`. This should only be used **in tests** where: - the component being tested is meant to be immutable/idempotent for the entire request - the test needs to cover multiple initial states, where only one would truly be reachable in a single request NOTE: Putting the `__Memoize` attribute on a static method will cause it to bind to the declaring class. When you do this, any uses of `static::` constructs to retrieve definitions from subclasses can cause unexpected results (they will actuually access the declaring class, similar to equivalent `self::` constructs). Consider using `__MemoizeLSB` instead on static methods. ### Exceptions Thrown exceptions are not memoized, showing by the increasing counter in this example: ```Hack class CountThrows { private int $count = -1; <<__Memoize>> public function doStuff(): void { $this->count += 1; throw new \Exception('Hello '.$this->count); } } <<__EntryPoint>> function main(): void { $x = new CountThrows(); for($i = 0; $i < 2; ++$i) { try { $x->doStuff(); } catch (\Exception $e) { \var_dump($e->getMessage()); } } } ``` ### Awaitables and Exceptions As memoize caches an [Awaitable](../asynchronous-operations/awaitables) itself, this means that **if an async function is memoized and throws, you will get the same exception backtrace on every failed call**. For more information and examples, see [Memoized Async Exceptions](../asynchronous-operations/exceptions#memoized-async-exceptions). ## __MemoizeLSB This is like [<<__Memoize>>](#__memoize), but the cache has Late Static Binding. Each subclass has its own memoize cache. You can clear the cache with `HH\clear_lsb_memoization`. This should only be used **in tests** where: - the component being tested is meant to be immutable/idempotent for the entire request - the test needs to cover multiple initial states, where only one would truly be reachable in a single request ## __MockClass ```yamlmeta { "fbonly messages": [ "Mock classes are intended for test infrastructure. They should not be added or used directly in Facebook's WWW repository." ] } ``` Mock classes are useful in testing frameworks when you want to test functionality provided by a legitimate, user-accessible class, by creating a new class (many times a child class) to help with the testing. However, what if a class is marked as `final` or a method in a class is marked as `final`? Your mocking framework would generally be out of luck. The `__MockClass` attribute allows you to override the restriction of `final` on a class or method within a class, so that a mock class can exist. ```Hack no-extract final class FinalClass { public static function f(): void { echo __METHOD__, "\n"; } } // Without this attribute HHVM would throw a fatal error since you are trying // to extend a final class. With it, you can run the code as you normally would. // That said, you will still get Hack typechecker errors, since it does not // recognize this attribute as anything intrinsic, but these can be suppressed. /* HH_IGNORE_ERROR [2049] */ <<__MockClass>> /* HH_IGNORE_ERROR [4035] */ final class MockFinalClass extends FinalClass { public static function f(): void { echo __METHOD__, "\n"; // Let's say we were testing the call to the parent class. We wouldn't // be able to do this in HHVM without the __MockClass attribute. parent::f(); } } <<__EntryPoint>> function main(): void { $o = new MockFinalClass(); $o::f(); } ``` Mock classes *cannot* extend types `vec`, `dict`, and `keyset`, or the Hack legacy types `Vector`, `Map`, and `Set`. ## __ModuleLevelTrait Can be used on public traits. The elements of a trait annotated with `<<__ModuleLevelTrait>>` are considered to belong to the module where the trait is defined, and can access other internal symbols of the module. For more information see [Traits and Modules](../modules/traits.md). ## __Newable This attribute is used to annotate reified type parameters to ensure that they are only instantiated with classes on which `new` can be safely called. A common pattern, defining a function that creates instances of a class passed as type parameter, is: ```Hack final class A {} function f<<<__Newable>> reify T as A>(): T { return new T(); } ``` The class `A` must either be final (as in the example) or annotated with `__ConsistentConstruct`. The `__Newable` attribute ensures that the function `f` is only be applied to a _non-abstract_ class, say `C`, while the `as A` constraint guarantees that the interface of the constructor of `C` is uniquely determined by the interface of the constructor of class `A`. The generic type `T` must be reified so that the runtime has access to it, refer to [Generics: Reified Generics](../generics/reified-generics.md) for details. A complete example thus is: ```Hack <<__ConsistentConstruct>> abstract class A { public function __construct(int $x, int $y) {} } class B extends A {} function f<<<__Newable>> reify T as A>(int $x, int $y): T { return new T($x,$y); } <<__EntryPoint>> function main(): void { f<B>(3,4); // success, equivalent to new B(3,4) } ``` Omitting either the `__Newable` attribute for `T`, or the `__ConsistentConstruct` for the abstract class `A` will result in a type-checker error. ## __Override Methods marked with `__Override` must be used with inheritance. For classes, `__Override` ensures that a parent class has a method with the same name. ```Hack class Button { // If we rename 'draw' to 'render' in the parent class, public function draw(): void { /* ... */ } } class CustomButton extends Button { // then the child class would get a type error. <<__Override>> public function draw(): void { /* ... */ } } ``` For traits, `__Override` ensures that trait users have a method that is overridden. ```Hack class Button { public function draw(): void { /* ... */ } } trait MyButtonTrait { <<__Override>> public function draw(): void { /* ... */ } } class ExampleButton extends Button { // If ExampleButton did not have an inherited method // called 'draw', this would be an error. use MyButtonTrait; } ``` It is often clearer to use constraints on traits instead. The above trait could also be written like this. ```Hack class Button { public function draw(): void { /* ... */ } } trait MyButtonTrait { // This makes the relationship with Button explicit. require extends Button; public function draw(): void { /* ... */ } } class ExampleButton extends Button { use MyButtonTrait; } ``` ## __PHPStdLib This attribute tells the type checker to ignore a function or class, so type errors are reported on any code that uses it. This is useful when gradually deprecating PHP features. `__PHPStdLib` only applies on `.hhi` files by default, but can apply everywhere with the option `deregister_php_stdlib`. ## __ReturnDisposable This attribute can be applied to a function that returns a value whose type implements interface `IDisposable` or `IAsyncDisposable`. See [object disposal](../classes/object-disposal.md) for an example of its use. ## __Sealed A class that is *sealed* can be extended directly only by the classes named in the attribute value list. Similarly, an interface that is sealed can be implemented directly only by the classes named in the attribute value list. Classes named in the attribute value list can themselves be extended arbitrarily unless they are final or also sealed. In this way, sealing provides a single-level restraint on inheritance. For example: ```Hack <<__Sealed(X::class, Y::class)>> abstract class A {} class X extends A {} class Y extends A {} <<__Sealed(Z::class)>> interface I {} class Z implements I {} ``` Only classes `X` and `Y` can directly extend class `A`, and only class `Z` can directly implement interface `I`. ## __Soft Disable type enforcement. See [soft types](/hack/types/soft-types).
Markdown
hhvm/hphp/hack/manual/hack/21-XHP/01-setup.md
XHP provides a native XML-like representation of output. After adding the required dependencies, read the [Introduction](/hack/XHP/introduction). ## The XHP-Lib Library While XHP syntax is a part of the Hack language, implementation is in [XHP-Lib](https://github.com/hhvm/xhp-lib/), a library that needs to be installed with [Composer](https://getcomposer.org/). * XHP-Lib includes the base classes and interfaces, and definitions of standard HTML elements. * Support for namespaced XHP classes (elements like `<p>`) is enabled by default since HHVM 4.73. ### XHP-Lib Versions We stongly recommend using XHP-Lib v4, which includes XHP namespace support. XHP-Lib v3 is not officially maintained. **Important:** All of the guides in this section are written with the assumption that XHP-Lib v4 is used, but there are notes pointing out any major differences—look for the **Historical note** sections. <span data-nosnippet class="fbOnly fbIcon">**XHP namespaces are not enabled in Facebook's WWW repository**, so all *Historical note* sections apply.</span> #### XHP-Lib v4 Used when XHP namespace support is enabled. Declares all base classes, interfaces and elements in namespaces (e.g. standard HTML elements are in `Facebook\XHP\HTML`). It is also more strict (e.g. disallows most mutations after an element is rendered) and deprecates some features (e.g. attribute "clobbering" in `XHPHTMLHelpers`). To install, add `facebook/xhp-lib` to your `composer.json` manually, or run `composer require facebook/xhp-lib ^4.0` #### XHP-Lib v3 Used in older HHVM versions or when XHP namespace support is disabled. Declares everything in the root namespace, with the exception of `Facebook\XHP\ChildValidation`. To install, add `facebook/xhp-lib` to your `composer.json` manually, or run `composer require facebook/xhp-lib ^3.0` ### Enable Namespace Support We recommend using HHVM 4.73 or newer, since it's more thoroughly tested and doesn't require any extra configuration, however, XHP namespace support can be enabled in older HHVM versions (since around HHVM 4.46) by adding the following flags to your `.hhconfig`: ``` enable_xhp_class_modifier = true disable_xhp_element_mangling = true ``` And to `hhvm.ini` (or provided via `-d` when executing `hhvm`): ``` hhvm.hack.lang.enable_xhp_class_modifier=true hhvm.hack.lang.disable_xhp_element_mangling=true ``` ### Disable Namespace Support In HHVM 4.73 or newer, XHP namespace support can be disabled by setting these to `false`. ``` hhvm.hack.lang.enable_xhp_class_modifier=false hhvm.hack.lang.disable_xhp_element_mangling=false ``` If these flags are disabled, or if you're using an older version of HHVM: - XHP classes cannot be declared in namespaces (only in the root namespace) - any code that uses XHP classes also cannot be in a namespace, as HHVM previously didn't have any syntax to reference XHP classes across namespaces - note that the above two rules are not consistently enforced by the typechecker or the runtime, but violating them can result in various bugs - it is, however, possible to use namespaced code from inside XHP class declarations Make sure to also use the correct version of XHP-Lib based on whether XHP namespace support is enabled in your HHVM version. ## HHVM Configuration Flags These are not enabled by default in any HHVM version, but we recommend enabling them in any new Hack projects: - `disable_xhp_children_declarations = true` disables the old way of declaring allowed children, which has been deprecated in favor of the `Facebook\XHP\ChildValidation\Validation` trait. See [Children](extending#children) for more information. - `check_xhp_attribute = true` enables the typechecker to check that all required attributes are provided. Otherwise, these would only be errors at runtime.
Markdown
hhvm/hphp/hack/manual/hack/21-XHP/04-introduction.md
XHP provides a native XML-like representation of output (which is usually HTML). This allows UI code to be typechecked, and automatically avoids several common issues such as cross-site scripting (XSS) and double-escaping. It also applies other validation rules, e.g., `<head>` must contain `<title>`. Using traditional interpolation, a simple page could look like this: ```hack no-extract $user_name = 'Fred'; echo "<tt>Hello <strong>$user_name</strong></tt>"; ``` However, with XHP, it looks like this: ```hack no-extract $user_name = 'Fred'; $xhp = <tt>Hello <strong>{$user_name}</strong></tt>; echo await $xhp->toStringAsync(); ``` The first example uses string interpolation to output the HTML, while the second has no quotation marks&mdash;meaning that the syntax is fully understood by Hack&mdash;but this does not mean that all you need to do is remove quotation marks. Other steps needed include: - Use curly braces to include variables - e.g., `"<a>$foo</a>"` becomes `<a>{$foo}</a>`. - As XHP is XML-like, all elements must be closed - e.g., `"<br>"` becomes `<br />`. - Make sure your HTML is properly nested. - Remove all HTML/attribute escaping - e.g., you don't need to call `htmlspecialchars` before including a variable in your XHP output; and if you do, it will be double-escaped. ## Why use XHP? The initial reason for most users is because it is *safe by default*: all variables are automatically escaped in a context-appropriate way (e.g., there are different rules for escaping attribute values vs. text nodes). In addition, XHP is understood by the typechecker, making sure that you don't pass invalid attribute values. A common example of this is `border="3"`, but `border` is an on/off attribute, so a value of 3 doesn't make sense. For users experienced with XHP, the biggest advantage is that it is easy to add custom 'elements' with your own behavior, which can then be used like plain HTML elements. For example, this site defines an `<a_post>` tag that has the same interface as a standard `<a>` tag, but makes a POST request instead of a GET request: ```hack no-extract use namespace Facebook\XHP\Core as x; use type Facebook\XHP\HTML\{XHPHTMLHelpers, a, form}; final xhp class a_post extends x\element { use XHPHTMLHelpers; attribute string href @required; attribute string target; <<__Override>> protected async function renderAsync(): Awaitable<x\node> { $id = $this->getID(); $anchor = <a>{$this->getChildren()}</a>; $form = ( <form id={$id} method="post" action={$this->:href} target={$this->:target} class="postLink"> {$anchor} </form> ); $anchor->setAttribute( 'onclick', 'document.getElementById("'.$id.'").submit(); return false;', ); $anchor->setAttribute('href', '#'); return $form; } } ``` A little CSS is needed so that the `<form>` doesn't create a block element: ``` form.postLink { display: inline; } ``` At this point, the new element can be used like any built-in element: ```hack no-extract use type Facebook\XHP\HTML\a; use type HHVM\UserDocumentation\a_post; <<__EntryPoint>> async function intro_examples_a_a_post(): Awaitable<void> { $get_link = <a href="http://www.example.com">I'm a normal link</a>; $post_link = <a_post href="http://www.example.com">I make a POST REQUEST</a_post>; echo await $get_link->toStringAsync(); echo "\n"; echo await $post_link->toStringAsync(); } ```.expectf <a href="http://www.example.com">I'm a normal link</a> <form id="%s" method="post" action="http://www.example.com" class="postLink"><a onclick="document.getElementById(&quot;%s&quot;).submit(); return false;" href="#">I make a POST REQUEST</a></form> ``` ## Runtime Validation Since XHP objects are first-class and not just strings, a whole slew of validation can occur to ensure that your UI does not have subtle bugs: ```hack no-extract function intro_examples_tag_matching_validation_using_string(): void { echo '<div class="section-header">'; echo '<a href="#use">You should have used <span class="xhp">XHP</naps></a>'; echo '</div>'; } async function intro_examples_tag_matching_validation_using_xhp( ): Awaitable<void> { // Typechecker error // Fatal syntax error at runtime $xhp = <div class="section-header"> <a href="#use">You should have used <span class="xhp">XHP</naps></a> </div>; echo await $xhp->toStringAsync(); } <<__EntryPoint>> async function intro_examples_tag_matching_validation_run(): Awaitable<void> { intro_examples_tag_matching_validation_using_string(); await intro_examples_tag_matching_validation_using_xhp(); } ``` The above code won't typecheck or run because the XHP validator will see that `<span>` and `<naps>` tags are mismatched; however, the following code will typecheck correctly but fail to run, because while the tags are matched, they are not nested correctly (according to the HTML specification), and nesting verification only happens at runtime: ```hack no-extract use namespace Facebook\XHP; use type Facebook\XHP\HTML\{i, ul}; function intro_examples_allowed_tag_validation_using_string(): void { echo '<ul><i>Item 1</i></ul>'; } async function intro_examples_allowed_tag_validation_using_xhp( ): Awaitable<void> { try { $xhp = <ul><i>Item 1</i></ul>; echo await $xhp->toStringAsync(); } catch (XHP\InvalidChildrenException $ex) { // We will get here because an <i> cannot be nested directly below a <ul> \var_dump($ex->getMessage()); } } ``` ```hack no-extract <<__EntryPoint>> async function intro_examples_allowed_tag_validation_run(): Awaitable<void> { intro_examples_allowed_tag_validation_using_string(); echo \PHP_EOL.\PHP_EOL; await intro_examples_allowed_tag_validation_using_xhp(); } ``` ## Security String-based entry and validation are prime candidates for cross-site scripting (XSS). You can get around this by using special functions like [`htmlspecialchars`](http://php.net/manual/en/function.htmlspecialchars.php), but then you have to actually remember to use those functions. XHP automatically escapes reserved HTML characters to HTML entities before output. ```hack no-extract use type Facebook\XHP\HTML\{body, head, html}; function intro_examples_avoid_xss_using_string(string $could_be_bad): void { // Could call htmlspecialchars() here echo '<html><head/><body> '.$could_be_bad.'</body></html>'; } async function intro_examples_avoid_xss_using_xhp( string $could_be_bad, ): Awaitable<void> { // The string $could_be_bad will be escaped to HTML entities like: // <html><head></head><body>&lt;blink&gt;Ugh&lt;/blink&gt;</body></html> $xhp = <html> <head /> <body>{$could_be_bad}</body> </html>; echo await $xhp->toStringAsync(); } async function intro_examples_avoid_xss_run( string $could_be_bad, ): Awaitable<void> { intro_examples_avoid_xss_using_string($could_be_bad); echo \PHP_EOL.\PHP_EOL; await intro_examples_avoid_xss_using_xhp($could_be_bad); } <<__EntryPoint>> async function intro_examples_avoid_xss_main(): Awaitable<void> { await intro_examples_avoid_xss_run('<blink>Ugh</blink>'); } ```
Markdown
hhvm/hphp/hack/manual/hack/21-XHP/07-basic-usage.md
XHP is a syntax to create actual Hack objects, called *XHP objects*. They are meant to be used as a tree, where children can either be other XHP objects or text nodes (or, rarely, other non-XHP objects). ## Creating a Simple XHP Object Instead of using the `new` operator, creating XHP looks very much like XML: ```Hack no-extract $my_xhp_object = <p>Hello, world</p>; ``` `$my_xhp_object` now contains an instance of the `p` class. It is a real object, meaning that `is_object` will return `true` and you can call methods on it. **Historical note:** <span data-nosnippet class="fbOnly fbIcon">(applies in FB WWW repository)</span> Before XHP namespace support (in XHP-Lib v3), XHP classes lived in a separate (but still global) namespace from regular classes, denoted by a `:` prefix in the typechecker and an `xhp_` prefix at runtime. `<p>` would therefore instantiate a class named `:p` in Hack code and `xhp_p` at runtime. It would therefore not conflict with a global non-XHP class named `p`, but would conflict with a class named `xhp_p`. The following example utilizes three XHP classes: `div`, `strong`, `i`. Whitespace is insignificant, so you can create a readable tree structure in your code. ```hack no-extract use type Facebook\XHP\HTML\{div, i, strong}; <<__EntryPoint>> function basic_usage_examples_basic_xhp(): void { \var_dump( <div> My Text <strong>My Bold Text</strong> <i>My Italic Text</i> </div>, ); } ``` The `var_dump` shows that a tree of objects has been created, not an HTML/XML string. An HTML string can be produced by calling `await $xhp_object->toStringAsync()`. ## Namespace Syntax When instantiating an XHP class using the `<ClassName>` syntax, `:` must be used instead of `\` as a namespace separator (this mirrors XML's namespace syntax). These are all equivalent ways to instantiate a `Facebook\XHP\HTML\p` object: ``` use type Facebook\XHP\HTML\p; $xhp = <p>Hello, world</p>; ``` ``` use namespace Facebook\XHP\HTML; $xhp = <HTML:p>Hello, world</HTML:p>; ``` ``` use namespace Facebook\XHP\HTML as h; $xhp = <h:p>Hello, world</h:p>; ``` ``` // exists in the root namespace: $xhp = <Facebook:XHP:HTML:p>Hello, world</Facebook:XHP:HTML:p>; ``` ``` namespace CustomNamespace; // from any namespace: $xhp = <:Facebook:XHP:HTML:p>Hello, world</:Facebook:XHP:HTML:p>; ``` In all other contexts, `\` must be used, for example: ``` if ($obj is HTML\p) { ... } h\p::staticMethod(); $class_name = Facebook\XHP\HTML\p::class; final xhp class my_element extends \Facebook\XHP\Core\element { ... } ``` **Historical note:** <span data-nosnippet class="fbOnly fbIcon">(applies in FB WWW repository)</span> Before XHP namespace support (in XHP-Lib v3), `:` is allowed as part of an XHP class name, but it is *not* a namespace separator. It is simply translated to `__` at runtime (this is called "name mangling"). For example, `<ui:table>` would instantiate a global class named `xhp_ui__table`. In all other contexts, XHP classes must be referenced with the `:` prefix (e.g. `if ($obj is :ui:table) { ... }`). ## Dynamic Content The examples so far have only shown static content, but usually you'll need to include something that's generated at runtime; for this, you can use Hack expressions directly within XHP with braces: ``` <xhp_class>{$some_expression}</xhp_class> ``` This also works for attributes: ``` <xhp_class attribute={$some_expression} /> ``` More complicated expressions are also supported, for example: ```hack no-extract use type Facebook\XHP\HTML\{div, i, strong}; class MyBasicUsageExampleClass { public function getInt(): int { return 4; } } function basic_usage_examples_get_string(): string { return "Hello"; } function basic_usage_examples_get_float(): float { return 1.2; } <<__EntryPoint>> async function basic_usage_examples_embed_hack(): Awaitable<void> { $xhp_float = <i>{basic_usage_examples_get_float()}</i>; $xhp = <div> {(new MyBasicUsageExampleClass())->getInt()} <strong>{basic_usage_examples_get_string()}</strong> {$xhp_float /* this embeds the <i /> element as a child of the <div /> */} </div>; echo await $xhp->toStringAsync(); } ``` ## Attributes Like HTML, XHP supports attributes on an XHP object. An XHP object can have zero or any number of attributes available to it. The XHP class defines what attributes are available to objects of that class: ``` echo <input type="button" name="submit" value="OK" />; ``` Here the `input` class has the attributes `type`, `name` and `value`. Some attributes are required, and XHP will throw an exception when an XHP object is rendered (`toStringAsync()` is called) with any required attributes missing. With `check_xhp_attribute=true` (available since HHVM 4.8) this is also a typechecker error. Use the [`->:` operator](/hack/expressions-and-operators/XHP-attribute-selection) to select an attribute. ## HTML Character References In order to encode a reserved HTML character or a character that is not readily available to you, you can use HTML character references in XHP: ``` <?hh echo <span>&hearts; &#9829; &#x2665;</span>; ``` The above uses HTML character reference encoding to print out the heart symbol using the explicit name, decimal notation, and hex notation.
Markdown
hhvm/hphp/hack/manual/hack/21-XHP/10-interfaces.md
There are two important XHP types, the `\XHPChild` interface (HHVM built-in) and the `\Facebook\XHP\Core\node` base class (declared in XHP-Lib). You will most commonly encounter these in functions' return type annotations. ## `\XHPChild` XHP presents a tree structure, and this interface defines what can be valid child nodes of the tree; it includes: - all subclasses of `\Facebook\XHP\Core\node` and the advanced interfaces described below - strings, integers, floats - arrays of any of the above Despite strings, integers, floats, and arrays not being objects, both the typechecker and HHVM consider them to implement this interface, for parameter/return types and for `is` checks. ## `\Facebook\XHP\Core\node` (`x\node`) The `\Facebook\XHP\Core\node` base class is implemented by all XHP objects, via one of its two subclasses: - `\Facebook\XHP\Core\element` (`x\element`): most common; subclasses implement a `renderAsync()` method that returns another `node`, and XHP-Lib automatically takes care of recursively rendering nested XHP objects - `\Facebook\XHP\Core\primitive` (`x\primitive`): for very low-level nodes that need exact control of how the object is rendered to a string, or when the automatic handling of nested XHP objects is insufficient; subclasses implement a `stringifyAsync()` method that returns a `string` and must manually deal with any children **Historical note:** <span data-nosnippet fbIcon">(applies in FB WWW repository)</span> Before XHP namespace support (in XHP-Lib v3), the names of `node`, `element` and `primitive` are `\XHPRoot`, `:x:element` and `:x:primitive` respectively. The `\Facebook\XHP\Core` namespace is conventionally aliased as `x` (`use Facebook\XHP\Core as x;`), so you might encounter these classes as `x\node`, `x\element` and `x\primitive`, which also mirrors their historical names. ## Advanced Interfaces While XHP's safe-by-default features are usually beneficial, occasionally they need to be bypassed; the most common cases are: - Needing to embed the output from another template system when migrating to XHP. - Needing to embed HTML from another source, for example, Markdown or BBCode renderers. XHP usually gets in the way of this by: - Escaping all variables, including your HTML code. - Enforcing child relationships - and XHP objects can not be marked as allowing HTML string children. The `\Facebook\XHP\UnsafeRenderable` and `\Facebook\XHP\XHPAlwaysValidChild` interfaces allow bypassing these safety mechanisms. **Historical note:** <span data-nosnippet class="fbOnly fbIcon">(applies in FB WWW repository)</span> Before XHP namespace support (in XHP-Lib v3), the names of these interfaces are `\XHPUnsafeRenderable` and `\XHPAlwaysValidChild`. ### `\Facebook\XHP\UnsafeRenderable` If you need to render raw HTML strings, wrap them in a class that implements this interface and provides a `toHTMLStringAsync()` method: ```md.xss-security-hole.inc.hack use namespace Facebook\XHP; /* YOU PROBABLY SHOULDN'T DO THIS * * Even with a scary (and accurate) name, it tends to be over-used. * See below for an alternative. */ class ExamplePotentialXSSSecurityHole implements XHP\UnsafeRenderable { public function __construct(private string $html) { } public async function toHTMLStringAsync(): Awaitable<string> { return $this->html; } } ``` ```md.xss-security-hole.hack no-auto-output use type Facebook\XHP\HTML\div; <<__EntryPoint>> async function start(): Awaitable<void> { $xhp = <div class="markdown"> {new ExamplePotentialXSSSecurityHole( md_render('Markdown goes here'), )} </div>; echo await $xhp->toStringAsync(); } ``` We do not provide an implementation of this interface as a generic implementation tends to be overused; instead, consider making more specific implementations: ```md.markdown-wrapper.inc.hack use namespace Facebook\XHP; final class ExampleMarkdownXHPWrapper implements XHP\UnsafeRenderable { private string $html; public function __construct(string $markdown_source) { $this->html = md_render($markdown_source); } public async function toHTMLStringAsync(): Awaitable<string> { return $this->html; } } ``` ```md.markdown-wrapper.hack no-auto-output use type Facebook\XHP\HTML\div; <<__EntryPoint>> async function run(): Awaitable<void> { $xhp = <div class="markdown"> {new ExampleMarkdownXHPWrapper('Markdown goes here')} </div>; echo await $xhp->toStringAsync(); } ``` ### `\Facebook\XHP\AlwaysValidChild` XHP's child validation can be bypassed by implementing this interface. Most classes that implement this interface are also implementations of `UnsafeRenderable`, as the most common need is when a child is produced by another rendering or template system. This can also be implemented by XHP objects, but this usually indicates that some class in `getChildrenDeclaration()` should be replaced with a more generic interface. `AlwaysValidChild` is intentionally breaking part of XHP's safety, so should be used as sparingly as possible. ## Example ```all-in-one.inc.hack use namespace Facebook\XHP; final class XHPUnsafeExample implements XHP\UnsafeRenderable { public async function toHTMLStringAsync(): Awaitable<string> { /* HH_FIXME[2050] $_GET is not recognized by the typechecker */ return '<script>'.$_GET['I_LOVE_XSS'].'</script>'; } } ``` ```all-in-one.hack use namespace Facebook\XHP\Core as x; use type Facebook\XHP\HTML\{div, li}; <<__EntryPoint>> function all_in_one_xhp_example_main(): void { $inputs = Map { '<div />' => <div />, '<x:frag />' => <x:frag />, '"foo"' => 'foo', '3' => 3, 'true' => true, 'null' => null, 'new stdClass()' => new \stdClass(), 'vec[<li />, <li />, <li />]' => vec[<li />, <li />, <li />], 'XHPUnsafeExample' => new XHPUnsafeExample(), }; $max_label_len = \max($inputs->mapWithKey(($k, $_) ==> \strlen($k))); print Str\repeat(' ', $max_label_len + 1)." | XHPRoot | XHPChild\n"; print Str\repeat('-', $max_label_len + 1)."-|---------|----------\n"; foreach ($inputs as $label => $input) { \printf( " %s | %-7s | %s\n", Str\pad_left($label, $max_label_len, ' '), $input is x\node ? 'yes' : 'no', $input is \XHPChild ? 'yes' : 'no', ); } } ```
Markdown
hhvm/hphp/hack/manual/hack/21-XHP/13-methods.md
Remember, all XHP Objects derive from the [`\Facebook\XHP\Core\node`](/hack/XHP/interfaces) base class, which has some public methods that can be called. Method | Description --------|------------ `toStringAsync(): Awaitable<string>` | Renders the element to a string for output. Mutating methods like `setAttribute` can no longer be called after this. `appendChild(mixed $child): this` | Adds `$child` to the end of the XHP object's array of children. If `$child` is an array, each item in the array will be appended. `getAttribute(string $name): mixed` | Returns the value of the XHP object's attribute named `$name`. If the attribute is not set, `null` is returned, unless the attribute is required, in which case `AttributeRequiredException` is thrown. If the attribute is not declared or does not exist, then `AttributeNotSupportedException` is thrown. If the attribute you are reading is statically known, use `$this->:name` style syntax instead for better typechecker coverage. `getAttributes(): dict<string, mixed>` | Returns the XHP object's array of attributes. `getChildren(): vec<XHPChild>` | Returns the XHP object's children. `getChildrenOfType<T as XHPChild>(): vec<T>` | Returns the XHP object's children of the specified type (usually a class/interface, but can also be `string` or another type). `getFirstChild(): ?XHPChild` | Returns the XHP object's first child or `null` if it has no children. `getFirstChildx(): XHPChild` | Same but throws if the XHP object has no children. `getFirstChildOfType<T as XHPChild>(): ?T` | Returns the first of XHP object's children of the specified type, or `null` if it has no such children. `getFirstChildOfTypex<T as XHPChild>(): T` | Same but throws if the XHP object has no children of the specified type. `getLastChild(): ?XHPChild` | Analogous to `getFirstChild`. `getLastChildx(): XHPChild` | Analogous to `getFirstChildx`. `getLastChildOfType<T as XHPChild>(): ?T` | Analogous to `getFirstChildOfType`. `getLastChildOfType<T as XHPChild>(): T` | Analogous to `getFirstChildOfTypex`. `isAttributeSet(string $name): bool` | Returns whether the attribute with name `$name` is set. `replaceChildren(XHPChild ...$children): this` | Replaces all the children of this XHP Object with the variable number of children passed to this method. `setAttribute(string $name, mixed $val): this` | Sets the value of the XHP object's attribute named `$name`. This does no validation, attributes are only validated when retrieved using `getAttribute` or during rendering. `setAttributes(KeyedTraversable<string, mixed> $attrs): this` | Replaces the XHP object's array of attributes with `$attrs`. ```hack no-extract use namespace Facebook\XHP\Core as x; use type Facebook\XHP\HTML\{li, p, ul}; function build_list(vec<string> $names): x\node { $list = <ul id="names" />; foreach ($names as $name) { $list->appendChild(<li>{$name}</li>); } return $list; } <<__EntryPoint>> async function xhp_object_methods_run(): Awaitable<void> { $names = vec['Sara', 'Fred', 'Josh', 'Scott', 'Paul', 'David', 'Matthew']; foreach (build_list($names)->getChildren() as $child) { $child as x\node; echo 'Child: '.await $child->toStringAsync()."\n"; } echo 'First child: '. await (build_list($names)->getFirstChild() as x\node->toStringAsync())."\n"; echo 'Last child: '. await (build_list($names)->getLastChild() as x\node->toStringAsync())."\n"; foreach (build_list($names)->getAttributes() as $name => $value) { echo 'Attribute '.$name.' = '.$value as string."\n"; } echo 'ID: '.build_list($names)->getAttribute('id') as string."\n"; } ```
Markdown
hhvm/hphp/hack/manual/hack/21-XHP/16-extending.md
XHP comes with classes for all standard HTML tags, but since these are first-class objects, you can create your own XHP classes for rendering items that are not in the standard HTML specification. ## Basics XHP class names must follow the same rules as any other Hack class names: Letters, numbers and `_` are allowed and the name mustn't start with a number. **Historical note:** <span data-nosnippet class="fbOnly fbIcon">(applies in FB WWW repository)</span> Before XHP namespace support (in XHP-Lib v3), XHP class names could also contain `:` (now a namespace separator) and `-` (now disallowed completely). These were translated to `__` and `_` respectively at runtime (this is called "name mangling"). For example, `<ui:big-table>` would instantiate a global class named `xhp_ui__big_table`. A custom XHP class needs to do three things: * use the keywords `xhp class` instead of `class` * extend `x\element` (`\Facebook\XHP\Core\element`) or, rarely, another [base class](/hack/XHP/interfaces) * implement the method `renderAsync` to return an XHP object (`x\node`) or the respective method of the chosen base class ```basic.inc.hack use namespace Facebook\XHP\Core as x; use type Facebook\XHP\HTML\strong; final xhp class introduction extends x\element { protected async function renderAsync(): Awaitable<x\node> { return <strong>Hello!</strong>; } } final xhp class intro_plain_str extends x\primitive { protected async function stringifyAsync(): Awaitable<string> { return 'Hello!'; } } ``` ```basic.hack <<__EntryPoint>> async function extending_examples_basic_run(): Awaitable<void> { $xhp = <introduction />; echo await $xhp->toStringAsync()."\n"; $xhp = <intro_plain_str />; echo await $xhp->toStringAsync()."\n"; } ``` **Historical note:** <span data-nosnippet class="fbOnly fbIcon">(applies in FB WWW repository)</span> Before XHP namespace support (in XHP-Lib v3), use `class :intro_plain_str` instead of `xhp class intro_plain_str` (no `xhp` keyword, but requires a `:` prefix in the class name). ## Attributes ### Syntax Your custom class may have attributes in a similar form to XML attributes, using the `attribute` keyword: ``` attribute <type> <name> [= default value|@required]; ``` Additionally, multiple declarations can be combined: ``` attribute int foo, string bar @required; ``` ### Types XHP attributes support the following types: * `bool`, `int`, `float`, `string`, `array`, `mixed` (with **no coercion**; an `int` is not coerced into `float`, for example. You will get an `XHPInvalidAttributeException` if you try this). * Hack enums * XHP-specific enums inline with the attribute in the form of `enum {item, item...}`. All values must be scalar, so they can be converted to strings. These enums are *not* Hack enums. * Classes or interfaces * Generic types, with type arguments The typechecker will raise errors if attributes are incorrect when instantiating an element (e.g., `<a href={true} />`; because XHP allows attributes to be set in other ways (e.g., `setAttribute`), not all problems can be caught by the typechecker, and an `XHPInvalidAttributeException` will be thrown at runtime instead in those cases. The `->:` operator can be used to retrieve the value of an attribute. ### Required Attributes You can specify an attribute as required with the `@required` declaration after the attribute name. If you try to render the XHP object and have not set the required attribute, then an `XHPAttributeRequiredException` will be thrown. ```required-attributes.inc.hack use namespace Facebook\XHP\Core as x; final xhp class user_info extends x\element { attribute int userid @required; attribute string name = ""; protected async function renderAsync(): Awaitable<x\node> { return <x:frag>User with id {$this->:userid} has name {$this->:name}</x:frag>; } } ``` ```required-attributes.hack use namespace Facebook\XHP; <<__EntryPoint>> async function extending_examples_attributes_run(): Awaitable<void> { /* HH_FIXME[4314] Missing required attribute is also a typechecker error. */ $uinfo = <user_info />; // Can't render :user-info for an echo without setting the required userid // attribute try { echo await $uinfo->toStringAsync(); } catch (XHP\AttributeRequiredException $ex) { \var_dump($ex->getMessage()); } /* HH_FIXME[4314] This is a typechecker error but not a runtime error. */ $uinfo = <user_info />; $uinfo->setAttribute('userid', 1000); $uinfo->setAttribute('name', 'Joel'); echo await $uinfo->toStringAsync(); } ``` ### Nullable Attributes For historical reasons, nullable types are inferred instead of explicitly stated. An attribute is nullable if it is not `@required` and does not have a default value. For example: ``` attribute string iAmNotNullable @required, string iAmNotNullableEither = "foo", string butIAmNullable; ``` ### Inheritance An XHP class can inherit all attributes of another XHP class using the following syntax: ``` // inherit all attributes from the <div> HTML element attribute :Facebook:XHP:HTML:div; ``` This is most useful for XHP elements that wrap another XHP element, usually to extend its functionality. In such cases, it should be combined with *attribute transfer*. ### Attribute Transfer Let's say you have a class that wants to inherit attributes from `<div>`. You could do something like this: ```bad-attribute-transfer.inc.hack use namespace Facebook\XHP\Core as x; use type Facebook\XHP\HTML\div; final xhp class ui_my_box extends x\element { attribute :Facebook:XHP:HTML:div; // inherit attributes from <div> protected async function renderAsync(): Awaitable<x\node> { // returning this will ignore any attribute set on this custom object // They are not transferred automatically when returning the <div> return <div class="my-box">{$this->getChildren()}</div>; } } ``` ```bad-attribute-transfer.hack <<__EntryPoint>> async function extending_examples_bad_attribute_transfer_run( ): Awaitable<void> { $my_box = <ui_my_box title="My box" />; // This will only bring <div class="my-box"></div> ... title= will be // ignored. echo await $my_box->toStringAsync(); } ``` `attribute :Facebook:XHP:HTML:div` causes your class to inherit all `<div>` attributes, however, any attribute set on `<ui_my_good_box>` will be lost because the `<div>` returned from `render` will not automatically get those attributes. This can be addressed by using the `...` operator. ```attribute-transfer.inc.hack use namespace Facebook\XHP\Core as x; use type Facebook\XHP\HTML\{div, XHPAttributeClobbering_DEPRECATED}; final xhp class ui_my_good_box extends x\element { attribute :Facebook:XHP:HTML:div; // inherit attributes from <div> attribute int extra_attr; protected async function renderAsync(): Awaitable<x\node> { // returning this will transfer any attribute set on this custom object return <div id="id1" {...$this} class="class1">{$this->getChildren()}</div>; } } ``` ```attribute-transfer.hack <<__EntryPoint>> async function extending_examples_good_attribute_transfer_run( ): Awaitable<void> { $my_box = <ui_my_good_box id="id2" class="class2" extra_attr={42} />; echo await $my_box->toStringAsync(); } ``` Now, when `<ui_my_good_box>` is rendered, each `<div>` attribute will be transferred over. Observe that `extra_attr`, which doesn't exist on `<div>`, is not transferred. Also note that the position of `{...$this}` matters&mdash;it overrides any duplicate attributes specified earlier, but attributes specified later override it. ## Children You can declare the types that your custom class is allowed to have as children by using the `Facebook\XHP\ChildValidation\Validation` trait and implementing the `getChildrenDeclaration()` method. **Historical note:** <span data-nosnippet class="fbOnly fbIcon">(applies in FB WWW repository)</span> Before XHP namespace support (in XHP-Lib v3), a special `children` keyword with a regex-like syntax could be used instead ([examples](https://github.com/hhvm/xhp-lib/blob/v3.x/tests/ChildRuleTest.php)). However, XHP-Lib v3 also supports `Facebook\XHP\ChildValidation\Validation`, and it is therefore recommended to use it everywhere. If you don't use the child validation trait, then your class can have any children. However, child validation still applies to any XHP objects returned by your `renderAsync()` method that use the trait. If an element is rendered (`toStringAsync()` is called) with children that don't satisfy the rules in its `getChildrenDeclaration()`, an `InvalidChildrenException` is thrown. Note that child validation only happens during rendering, no exception is thrown before that, e.g. when the invalid child is added. ```children.inc.hack // Conventionally aliased to XHPChild, which makes the children declarations // easier to read (more fluid). use namespace Facebook\XHP\{ChildValidation as XHPChild, Core as x}; use type Facebook\XHP\HTML\{body, head, html, li, ul}; xhp class my_br extends x\primitive { use XHPChild\Validation; protected static function getChildrenDeclaration(): XHPChild\Constraint { return XHPChild\empty(); } protected async function stringifyAsync(): Awaitable<string> { return "\n"; } } xhp class my_ul extends x\element { use XHPChild\Validation; protected static function getChildrenDeclaration(): XHPChild\Constraint { return XHPChild\at_least_one_of(XHPChild\of_type<li>()); } protected async function renderAsync(): Awaitable<x\node> { return <ul>{$this->getChildren()}</ul>; } } xhp class my_html extends x\element { use XHPChild\Validation; protected static function getChildrenDeclaration(): XHPChild\Constraint { return XHPChild\sequence( XHPChild\of_type<head>(), XHPChild\of_type<body>(), ); } protected async function renderAsync(): Awaitable<x\node> { return <html>{$this->getChildren()}</html>; } } ``` ```children.hack use namespace Facebook\XHP; use type Facebook\XHP\HTML\{body, head, li, ul}; <<__EntryPoint>> async function extending_examples_children_run(): Awaitable<void> { $my_br = <my_br />; // Even though my-br does not take any children, you can still call the // appendChild method with no consequences. The consequence will come when // you try to render the object by something like an echo. $my_br->appendChild(<ul />); try { echo await $my_br->toStringAsync()."\n"; } catch (XHP\InvalidChildrenException $ex) { \var_dump($ex->getMessage()); } $my_ul = <my_ul />; $my_ul->appendChild(<li />); $my_ul->appendChild(<li />); echo await $my_ul->toStringAsync()."\n"; $my_html = <my_html />; $my_html->appendChild(<head />); $my_html->appendChild(<body />); echo await $my_html->toStringAsync()."\n"; } ``` ### Interfaces (categories) XHP classes are encouraged to implement one or more interfaces (usually empty), conventionally called "categories". Some common ones taken from the HTML specification are declared in the `Facebook\XHP\HTML\Category` namespace. Using such interfaces makes it possible to implement `getChildrenDeclaration()` in other elements without having to manually list all possible child types, some of which may not even exist yet. ```categories.inc.hack use namespace Facebook\XHP\{ ChildValidation as XHPChild, Core as x, HTML\Category, }; xhp class my_text extends x\element implements Category\Phrase { use XHPChild\Validation; protected static function getChildrenDeclaration(): XHPChild\Constraint { return XHPChild\any_of( XHPChild\pcdata(), XHPChild\of_type<Category\Phrase>(), ); } protected async function renderAsync(): Awaitable<x\node> { return <x:frag>{$this->getChildrenOfType<Category\Phrase>()}</x:frag>; } } ``` ```categories.hack use type Facebook\XHP\HTML\em; <<__EntryPoint>> async function extending_examples_categories_run(): Awaitable<void> { $my_text = <my_text />; $my_text->appendChild(<em>"Hello!"</em>); // This is a Category\Phrase echo await $my_text->toStringAsync(); $my_text = <my_text />; $my_text->appendChild("Bye!"); // This is pcdata, not a phrase // Won't print out "Bye!" because render is only returing Phrase children echo await $my_text->toStringAsync(); } ``` **Historical note:** <span data-nosnippet class="fbOnly fbIcon">(applies in FB WWW repository)</span> Before XHP namespace support (in XHP-Lib v3), a special `category` keyword could be used instead of an interface (`category %name1, %name2;`). ## Async XHP and [async](../asynchronous-operations/introduction.md) co-exist well together. As you may have noticed, all rendering methods (`renderAsync`, `stringifyAsync`) are declared to return an `Awaitable` and can therefore be implemented as async functions and use `await`. ```xhp-async.inc.hack use namespace Facebook\XHP\Core as x; final xhp class ui_get_status extends x\element { protected async function renderAsync(): Awaitable<x\node> { $ch = \curl_init('https://metastatus.com/graph-api'); \curl_setopt($ch, \CURLOPT_USERAGENT, 'hhvm/user-documentation example'); $status = await \HH\Asio\curl_exec($ch); return <x:frag>Status is: {$status}</x:frag>; } } ``` ```xhp-async.hack <<__EntryPoint>> async function extending_examples_async_run(): Awaitable<void> { $status = <ui_get_status />; $html = await $status->toStringAsync(); // This can be long, so just show a bit for illustrative purposes $sub_status = \substr($html, 0, 100); \var_dump($sub_status); } ``` **Historical note:** <span data-nosnippet class="fbOnly fbIcon">(applies in FB WWW repository)</span> In XHP-Lib v3, most rendering methods are not async, and therefore a special `\XHPAsync` trait must be used in XHP classes that need to `await` something during rendering. ## HTML Helpers The `Facebook\XHP\HTML\XHPHTMLHelpers` trait implements two behaviors: * Giving each object a unique `id` attribute. * Managing the `class` attribute. **Historical note:** <span data-nosnippet class="fbOnly fbIcon">(applies in FB WWW repository)</span> In XHP-Lib v3, this trait is called `\XHPHelpers`. ### Unique IDs `XHPHTMLHelpers` has a method `getID` that you can call to give your rendered custom XHP object a unique ID that can be referred to in other parts of your code or UI framework (e.g., CSS). ```get-id.inc.hack use namespace Facebook\XHP\Core as x; use type Facebook\XHP\HTML\{span, XHPHTMLHelpers}; xhp class my_id extends x\element { attribute string id; use XHPHTMLHelpers; protected async function renderAsync(): Awaitable<x\node> { return <span id={$this->getID()}>This has a random id</span>; } } ``` ```get-id.hack <<__EntryPoint>> async function extending_examples_get_id_run(): Awaitable<void> { // This will print something like: // <span id="8b95a23bc0">This has a random id</span> $xhp = <my_id />; echo await $xhp->toStringAsync(); } ```.hhvm.expectf <span id="%s">This has a random id</span> ``` ### Class Attribute Management `XHPHTMLHelpers` has two methods to add a class name to the `class` attribute of an XHP object. `addClass` takes a `string` and appends that `string` to the `class` attribute (space-separated); `conditionClass` takes a `bool` and a `string`, and only appends that `string` to the `class` attribute if the `bool` is `true`. This is best illustrated with a standard HTML element, all of which have a `class` attribute and use the `XHPHTMLHelpers` trait, but it works with any XHP class, as long as it uses the trait and declares the `class` attribute directly or through inheritance. ```add-class.hack use type Facebook\XHP\HTML\h1; function get_header(string $section_name): h1 { return (<h1 class="initial-cls">{$section_name}</h1>) ->addClass('added-cls') ->conditionClass($section_name === 'Home', 'home-cls'); } <<__EntryPoint>> async function run(): Awaitable<void> { $xhp = get_header('Home'); echo await $xhp->toStringAsync()."\n"; $xhp = get_header('Contact'); echo await $xhp->toStringAsync()."\n"; } ```
Markdown
hhvm/hphp/hack/manual/hack/21-XHP/19-migration.md
You can incrementally port code to use XHP. Assume your output is currently handled by the following function, which might be called from many places. ```hack no-extract function render_component(string $text, Uri $uri): string { $uri = htmlspecialchars($uri->toString()); $text = htmlspecialchars($text); return "<a href=\"$uri\">$text</a>"; } ``` ## Convert Leaf Functions You can start by simply using XHP in `render_component`: ```hack no-extract async function render_component(string $text, Uri $uri): Awaitable<string> { $link = <a href={$uri->toString()}>{$text}</a>; return await $link->toStringAsync(); // or HH\Asio\join if converting all callers to async is hard } ``` You are converting `render_component` into a safer function without the need for explicit escaping, etc. But you are still passing strings around in the end. ## Use a Class You could make `render_component` into a class: ```hack no-extract namespace ui; class link extends x\element { attribute Uri uri @required; attribute string text @required; protected async function renderAsync(): Awaitable<x\node> { return <a href={$this->:uri->toString()}>{$this->:text}</a>; } } ``` Keep a legacy `render_component` around while you are converting the old code that uses `render_component` to use the class. ```hack no-extract async function render_component(string $text, Uri $uri): Awaitable<string> { return await (<ui:link uri={$uri} text={$text} />)->toStringAsync(); } ```
Markdown
hhvm/hphp/hack/manual/hack/21-XHP/22-guidelines.md
Here are some general guidelines to know and follow when using XHP. In addition to its [basic usage](basic-usage.md), [available methods](methods.md) and [extending XHP with your own objects](extending.md), these are other tips to make the best use of XHP. ## Validation of Attributes and Children The constraints of XHP object children and attributes are done at various times: * Children constraints are validated at render-time (when `toStringAsync` is called). * Attributes provided directly (`<your_class attr="value">`) are validated by the typechecker. * Attribute names set by `setAttribute` are only validated at render-time. ## Use Contexts to Access Higher Level Information If you have a parent object, and you want to give information to some object further down the UI tree (e.g., `<ul>` to `<li>`), you can set a context for those lower objects and the lower objects can retrieve them. You use `setContext` and `getContext` ```context.inc.hack use namespace Facebook\XHP\{ChildValidation as XHPChild, Core as x}; use type Facebook\XHP\HTML\{dd, dl, dt}; final xhp class ui_myparent extends x\element { use XHPChild\Validation; attribute string text @required; protected static function getChildrenDeclaration(): XHPChild\Constraint { return XHPChild\of_type<ui_mychild>(); } protected async function renderAsync(): Awaitable<x\node> { return ( <dl> <dt>Text</dt> <dd>{$this->:text}</dd> <dt>Child</dt> <dd>{$this->getChildren()}</dd> </dl> ); } } final xhp class ui_mychild extends x\element { attribute string text @required; protected async function renderAsync(): Awaitable<x\node> { if ($this->getContext('hint') === 'Yes') { return <x:frag>{$this->:text.'...and more'}</x:frag>; } return <x:frag>{$this->:text}</x:frag>; } } async function guidelines_examples_context_run(string $s): Awaitable<void> { $xhp = ( <ui_myparent text={$s}> <ui_mychild text="Go" /> </ui_myparent> ); $xhp->setContext('hint', $s); echo await $xhp->toStringAsync(); } ``` ```context.hack <<__EntryPoint>> async function startHere(): Awaitable<void> { await guidelines_examples_context_run('No'); echo "\n\n"; await guidelines_examples_context_run('Yes'); } ``` Context is only passed down the tree at render time; this allows you to construct a tree without having to thread through data. In general, you should only call `getContext` in the `render` method of the child. Common uses include: - current user ID - current theme in multi-theme sites - current browser/device type ## Don't Add Public Methods to Your XHP Components XHP objects should only be interacted with by their attributes, contexts, position in the tree, and rendering them. At Facebook, we haven't yet come across any situations where public methods are a better solution than these interfaces. ## Use Inheritance Minimally If you need an XHP object to act like another, but slightly modified, use composition (the would-be subclass can instead return an instance of the original XHP class from its `renderAsync` method). ## Remember No Dollar Signs Attribute declarations look like Hack property declarations: ```Hack no-extract public string $prop; attribute string attr; ``` A key difference is that there is no `$` in front of the attribute name.
Markdown
hhvm/hphp/hack/manual/hack/21-XHP/25-further-resources.md
Besides our documentation, there are some other very useful resources to enhance your experience with XHP. * [XHP Library](https://github.com/facebook/xhp-lib): The class libraries for XHP. * [XHP Announcement](https://www.facebook.com/notes/facebook-engineering/xhp-a-new-way-to-write-php/294003943919): The original XHP announcement from 2010.
Markdown
hhvm/hphp/hack/manual/hack/30-silencing-errors/01-introduction.md
Errors reported by the Hack typechecker can be silenced with `HH_FIXME` and `HH_IGNORE_ERROR` comments. Errors arising from type mismatches on expressions may also be silenced using the `HH\FIXME\UNSAFE_CAST` function. ## Silencing Errors with `HH\FIXME\UNSAFE_CAST` ```no-extract takes_int(HH\FIXME\UNSAFE_CAST<string,int>("foo", "Your explanation here")); ``` To silence an error arising from a type mismatch on a particular expression, add a call to `HH\FIXME\UNSAFE_CAST` with the expression as the first argument, an optional (string literal) comment, and explicit type hints indicating the actual type of the expression and the expected type. The `UNSAFE_CAST` function **has no runtime effect**. However, in contrast to `HH_FIXME` comments, the `UNSAFE_CAST` function _does_ change the type of the expression. ### Silencing Errors per Expression Whilst a single `HH_FIXME` comment will silence all related errors on the proceeding line, the `UNSAFE_CAST` function must be applied to each sub-expression that has a type mismatch. ```Hack file:takes_int.hack function takes_int(int $i): int { return $i + 1; } function takes_float_with_fixme(float $i): float { /* HH_FIXME[4110] calls takes_int with wrong param type AND returns wrong type */ return takes_int($i); } ``` ```Hack file:takes_int.hack function takes_float_with_unsafe_cast(float $i): float { return HH\FIXME\UNSAFE_CAST<int, float>( takes_int(HH\FIXME\UNSAFE_CAST<float, int>($i, 'wrong param type')), 'returns wrong type', ); } ``` ## Silencing Errors with Comments ```Hack file:takes_int.hack /* HH_FIXME[4110] Your explanation here. */ takes_int("foo"); ``` To silence an error, place a comment on the immediately previous line. The comment must use the `/*` syntax. This syntax only affects error reporting. It does not change types, so the typechecker will keep checking the rest of the file as before. This syntax also **has no runtime effect**. The runtime will do its best with badly typed code, but it may produce an error immediately, produce an error later in the program, or coerce values to an unwanted type. The behavior of badly typed code may change between HHVM releases. This will usually be noted in the changelog. ### `HH_FIXME` versus `HH_IGNORE_ERROR` Both `HH_FIXME` and `HH_IGNORE_ERROR` have the same effect: they suppress an error. ```Hack file:takes_int.hack /* HH_FIXME[4110] An example fixme. */ takes_int("foo"); /* HH_IGNORE_ERROR[4110] This is equivalent to the HH_FIXME above. */ takes_int("foo"); ``` You should generally use `HH_FIXME`. `HH_IGNORE_ERROR` is intended to signal to the reader that the type checker is wrong and you are deliberately suppressing the error. This should be very rare. ### Error Codes Every Hack error has an associated error code. These are stable across Hack releases, and new errors always have new error codes. Hack will ignore error suppression comments that have no effect, to help migration to newer Hack versions. Error codes 1000 - 1999 are used for parsing errors. Whilst it is possible to silence these, the runtime usually cannot run this code at all. Error codes 2000 - 3999 are used for naming errors. This includes references to nonexistent names, as well as well-formedness checks that don't require type information. Error codes 4000 - 4999 are used for typing errors. ### Configuring Error Suppression Hack error suppression can be configured in the `.hhconfig` file at the root of a project. In hhvm version [4.62](https://hhvm.com/blog/2020/06/16/hhvm-4.62.html) and above, error suppression works on a whitelist system. Older hhvm versions used a blacklisting system instead. ### How to whitelist suppression comments in hhvm 4.62 and above By default Hack will not accept a suppression comment, if that specific error code is not mentioned in the `.hhconfig` file. Attempting to suppress an unmentioned error will result in an extra error like this: ``` Typing[4110] You cannot use HH_FIXME or HH_IGNORE_ERROR comments to suppress error 4110 ``` If the file in which this error resides is in **partial** mode, add `4110` to the `allowed_fixme_codes_partial` key in your `.hhconfig`. If the file in which this error resides is in **strict** mode, add `4110` to the `allowed_fixme_codes_strict` key in your `.hhconfig`. As described further in Best Practices, suppressing errors on declarations is generally a bad idea. However, some errors can only be suppressed at a declaration. When suppressing an error at a declaration, you'll get an error like this. ``` Typing[4047] You cannot use HH_FIXME or HH_IGNORE_ERROR comments to suppress error 4047 in declarations ``` In such cases, you'll have to add `4047` to the `allowed_decl_fixme_codes` key, as well as to the `allowed_fixme_codes_xxx` key. An important note when using an external package. If a package uses a suppression comment and mentions this in its `.hhconfig`, this will not automatically update the `.hhconfig` settings for your project. In order to use this package, you'll need to add these codes to your own `.hhconfig`. ### Historic note for hhvm 4.61 and below *If you are writing code on hhvm 4.62 or above, you may skip this section.* Once you have removed all the occurrences of a specific error code, you can ensure that no new errors are added. You can use the `ignored_fixme_codes` option in `.hhconfig` to forbid suppression of a specific error code. ``` ignored_fixme_codes = 1002, 4110 ``` This forbids `/* HH_FIXME[4110] ... */`. `.hhconfig` also supports `disallowed_decl_fixmes`, which forbids error suppression of specific error codes on declarations (types, class properties etc). ``` disallowed_decl_fixmes = 1002, 4110 ``` This forbids `/* HH_FIXME[4110] ... */` outside of function and method bodies. Partial mode files have fewer checks. You can opt-in to specific strict mode checks in partial files by using the error code in `error_codes_treated_strictly` in `.hhconfig`. ``` error_codes_treated_strictly = 1002, 2045, 2055, 2060, 4005 ``` ## Best Practices Great Hack code has no error suppressing comments, and only uses strict mode. Suppressing errors in one place can lead to runtime errors in other places. ``` function takes_int(int $_): void {} function return_ints_lie(): vec<int> { /* HH_FIXME[4110] The type error is here. */ return vec["foo"]; } <<__EntryPoint>> function oh_no(): void { $items = return_ints_lie(); takes_int($items[0]); // But the exception is here! } ``` Good Hack code has no error suppression comments on its declarations. Suppressing errors in declarations can hide a large number of issues elsewhere. ``` function takes_int(int $_): void {} function takes_float(float $_): void {} /* HH_FIXME[4030] Missing a return type. */ function returns_something() { return ""; } function oh_no(): void { // This is wrong. takes_int(returns_something()); // This is wrong too! takes_float(returns_something()); } ``` When you use error suppression, make sure you specify a reason. Try to keep your comments to small expressions, because the comment applies to the entire next line. ``` /* HH_FIXME[4110] Bad: this can apply to both function calls! */ $result = foo(bar("stuff")); /* HH_FIXME[4110] Better: we will spot errors when calling bar. */ $x = foo("stuff"); $result = bar($x); ```
Markdown
hhvm/hphp/hack/manual/hack/30-silencing-errors/05-error-codes.md
This page lists the most common error codes, and suggests how to fix them. You can see the full list of error codes in [error_map.ml](https://github.com/facebook/hhvm/blob/master/hphp/hack/src/errors/error_codes.ml). ## 1002: Top-level code ```Hack no-extract function foo(): void {} /* HH_FIXME[1002] Top-level code isn't checked. */ echo "hello world\n"; ``` **Why it's bad:** Top-level code is not type checked. **Suggestions:** Put your code in a function and use the `__EntryPoint` attribute. ## 2049: Unbound name ```Hack function foo(): void { /* HH_FIXME[4107] No such function (type checking). */ /* HH_FIXME[2049] No such function (global name check). */ nonexistent_function(); } ``` **Why it's bad:** This is usually a sign that a name is incorrect. It may be useful for calling parts of the PHP standard library that the global name check is not aware of. **Suggestions:** Check your spelling. Use safe Hack APIs rather than legacy PHP APIs. ## 2050: Undefined Variable ```Hack function foo(): mixed { /* HH_FIXME[2050] This variable doesn't exist. */ return $no_such_var; } ``` **Why it's bad:** This is usually a sign that a variable name is incorrect. It may be useful for accessing PHP constants (such as `$GLOBALS` or `$_GET`) which the typechecker is unaware of. **Suggestions:** Check your spelling. Use safe Hack APIs rather than legacy PHP APIs. ## 4006: Array append on an inappropriate type ```Hack function foo(mixed $m): void { /* HH_FIXME[4006] $m may not be an array. */ $m[] = 1; } ``` **Why it's bad:** Appending to other types (e.g. `int`) is undefined and may throw an exception or convert the value to an array. **Suggestions:** If the type isn't specific enough, use `as` (e.g. `as vec<_>`) to perform a runtime type check. ## 4032: Missing return type ```Hack /* HH_FIXME[4030] Missing a return type declaration. */ function foo() { return 1; } ``` **Why it's bad:** When the typechecker does not know the return type, it cannot check operations on the value returned. **Suggestions:** Add a return type to your function. If you're unsure of the type, consider using `__Soft`. You may also want to consider a `mixed` or `dynamic` return type. ## 4045: Array without type parameter ```Hack no-extract function foo(array $_): void {} ``` **Why it's bad:** The typechecker knows very little about how the array is structured. **Suggestions:** Use `darray`, `varray` or `varray_or_darray` instead. If you still want to use `array`, specify the type e.g. `array<mixed>`. ## 4051: Accessing a shape with an invalid field name ```Hack function foo(shape(...) $s): void { /* HH_FIXME[4051] Invalid shape field name. */ $value = $s[1.0]; } ``` **Why it's bad:** The runtime may coerce values and access other fields of your shape. The typechecker also does not know what type `$value` has. **Suggestions:** Use a valid shape key: a string (recommended), an integer, or a class constant. ## 4053: Member not found ```Hack class MyClass {} function takes_myclass(MyClass $c): void { /* HH_FIXME[4053] No such method. */ $c->someMethod(); /* HH_FIXME[4053] No such property. */ $x = $c->someProperty; } ``` **Why it's bad:** Accessing a non-existent method will cause a runtime error. Accessing a non-existent property will log a notice and return null. **Suggestions:** Ensure that the object you're accessing actually has the type you're expecting. ## 4057: Missing shape field ```Hack function foo(): shape('x' => int) { /* HH_FIXME[4057] Missing the field `x`. */ return shape(); } ``` **Why it's bad:** Returning a shape that's missing fields will cause errors when code tries to access those fields later. Note that shape fields are not enforced when calling or returning from functions. **Suggestions:** Change your shape type to use optional fields. ## 4063: Nullable container access ```Hack function foo(?vec<int> $items): void { /* HH_FIXME[4063] $items can be null. */ $x = $items[0]; } ``` **Why it's bad:** indexing a `null` returns null, leading to runtime type errors later. **Suggestions:** Check that the value is non-null with `nullthrows` or assert with `$items as nonnull`. ## 4064: Accessing members on a nullable object ```Hack class MyClass { public int $x = 0; public function foo(): void {} } function foo(?MyClass $m): void { /* HH_FIXME[4064] Accessing a property on a nullable object. */ $value = $m->x; /* HH_FIXME[4064] Calling a method on a nullable object. */ $m->foo(); } ``` **Why it's bad:** Accessing a property or a method on `null` will throw an exception. **Suggestions:** Check that the value is non-null with `nullthrows` or assert with `$m as nonnull`. ## 4101: Wrong number of type parameters ```Hack class MyBox<T> { public ?T $x = null; } /* HH_FIXME[4101] Missing a type parameter. */ class TooFewArguments extends MyBox {} /* HH_FIXME[4101] Too many type parameters. */ class TooManyArguments extends MyBox<mixed, mixed> {} ``` **Why it's bad:** If the typechecker doesn't have full information about a class declaration, it cannot fully check code that uses the class. **Suggestions:** Add the necessary type parameters. You can usually use `mixed` or `nothing` as the type parameter on base classes. Note that this is only required for declarations. Hack can infer type parameters inside function and method bodies. ## 4107: Unbound name (type checking) ```Hack function foo(): void { /* HH_FIXME[4107] No such function (type checking). */ /* HH_FIXME[2049] No such function (global name check). */ nonexistent_function(); } ``` **Why it's bad:** This is usually a sign that a name is incorrect. It may be useful for calling parts of the PHP standard library that the type checker is not aware of. **Suggestions:** Check your spelling. Use safe Hack APIs rather than legacy PHP APIs. ## 4108: Undefined shape field ```Hack function foo(shape('x' => int) $s): void { /* HH_FIXME[4108] No such field in this shape. */ $value = $s['not_x']; } ``` **Why it's bad:** Accessing an undefined field may throw an exception or return an unexpected value (for open shapes). **Suggestions:** Ensure that your shape type declaration has the fields you're using. ## 4110: Bad type in expression ```Hack function takes_int(int $_): void {} function foo(): void { /* HH_FIXME[4110] Passing incorrect type to a function. */ takes_int("hello"); /* HH_FIXME[4110] Addition on a value that isn't a num. */ "1" + 3; } ``` **Why it's bad:** Using the wrong type can result in runtime errors (for enforced types), errors later (for unenforced types, such as erased generics) or surprising coercions (e.g. for arithmetic). **Suggestions:** If the type is too broad (e.g. using `mixed`), use `as SpecificType` to assert the specific runtime type. If you're not sure of the type, consider using `<<__Soft>>` type hints on function signatures. If the type is coming from very dynamic code, consider using the `dynamic` type. ## 4166: Unknown field in shape (obsolete) This error code is obsolete. The typechecker now produces error 4110 in these situations. ``` function test(shape('a' => string) $s): shape() { /* HH_FIXME[4166] Extra fields in the shape. */ return $s; } ``` **Why it's bad:** Passing extra fields in a shape can lead to surprising results when converting shapes to arrays. **Suggestions:** Use a field type declaration with optional fields instead. ## 4128: Using deprecated code ```Hack function foo_new(): void {} <<__Deprecated("Use foo_new instead")>> function foo_old(): void {} function bar(): void { /* HH_FIXME[4128] Calling a deprecated function. */ foo_old(); } ``` **Why it's bad:** Using functions or classes that have been marked as deprecated prevents cleanup of old APIs. **Suggestions:** [`__Deprecated`](/hack/attributes/predefined-attributes#__deprecated) takes a message which describes why something is deprecated. Take a look at that message to learn the new API. ## 4165: Accessing optional shape field ```Hack function foo(shape(?'x' => int) $s): void { /* HH_FIXME[4165] This field may not be present. */ $value = $s['x']; } ``` **Why it's bad:** This code will throw an exception if the shape doesn't have this field. **Suggestions:** Use `Shapes::idx` instead, so you can explicitly handle the missing field. ## 4193: Illegal XHP child ```Hack no-extract use type Facebook\XHP\HTML\div; function foo(mixed $m): void { /* HH_FIXME[4110] */ /* HH_FIXME[4193] $m may not be an XHPChild.*/ $my_div = <div>{$m}</div>; } ``` **Why it's bad:** XHP expects child elements to be instance of `XHPChild`. **Suggestions:** Use `as` to assert a narrower type, or convert values to a valid XHP child, such as a string. ## 4276: Truthiness check ``` $x = null; if ($x) { echo "not null"; } $y = '0'; if ($y) { echo "truthy string"; } ``` This error was [moved to a linter](https://github.com/hhvm/hhast), as it was making it harder to convert partial mode files to strict. We still recommend avoiding this code style. **Why it's bad:** Truthiness rules can be surprising. `''` is falsy, but so is `'0'`. **Suggestions:** Use `is null`, `Str\is_empty` or `=== 0` when checking for empty values. ## 4297: Type inference failed ```Hack class MyA { public function doStuff(): void {} } function foo(): void { /* HH_FIXME[4297] Cannot infer the type of $x. */ $f = $x ==> $x->doStuff(); $f(new MyA()); } ``` **Why it's bad:** If the type checker cannot infer the type, it cannot check usage of values with that type. This usually occurs with anonymous functions, but can also occur when working with generic containers like `dict` or `vec`. **Suggestions:** For anonymous functions, add a type annotation. ``` $f = (MyA $x) ==> $x->doStuff(); ``` Alternatively, use a type assertion `($x as MyA)->doStuff()`. When type inference fails on generic containers, add a type annotation on the declaration. ``` $d = dict<string, string>[]; ``` ## 4323: Type constraint violation ```Hack /* HH_FIXME[4323] A dict must have arraykey, int or string keys. */ function foo(dict<mixed, bool> $d): void {} ``` **Why it's bad:** if a type has constraints on how it can be used, and you break those constraints, it may not work as expected. In this example, we define a `dict` with `mixed` keys. We can then insert values that aren't `arraykey` types, leading to surprising value conversions. **Suggestions:** Look carefully at the error message to see what types are supported for the generic you're using. ## 4324: Array access on a type that doesn't support indexing ```Hack function foo(int $m): void { /* HH_FIXME[4324] Indexing a type that isn't indexable. */ $value = $m['foo']; } ``` **Why it's bad:** Indexing values that don't support values can produce surprising behavior. The runtime will log a warning and return null, leading to runtime type errors later. **Suggestions:** Refactor the code to use a Hack array or a `KeyedContainer`. **Note:** In previous versions of HHVM, error `4324` was known as error `4005`.
Markdown
hhvm/hphp/hack/manual/hack/40-contributing/01-introduction.md
This website is itself written in Hack and running on HHVM. You can see the current [HHVM version used on the deployed site](https://github.com/hhvm/user-documentation/blob/main/.deploy/built-site.Dockerfile#L3). ## Prerequisites You'll need HHVM (see [installation instructions](/hhvm/installation/introduction)) installed on your local machine, and the version must have the same major and minor (e.g. `4.123`) as the version specification in the `composer.json` file. You'll also need a checkout of the source code for this site. ``` $ git clone [email protected]:hhvm/user-documentation.git ``` ## Composer Dependencies We use Composer to manage our PHP library dependencies and to autoload classes. Composer is written in PHP, so you need PHP installed. ``` # Ubuntu example, your environment may differ. $ apt-get install php-cli ``` You can now follow the instructions on [the Composer website](https://getcomposer.org/) to install it. Once you've installed `composer.phar`, you can install the website dependencies into `vendor/` and create the autoload map. ``` $ cd user-documentation user-documentation$ php /path/to/composer.phar install ``` ### Updating Dependencies We require that this whole repository has no type errors. ``` $ hh_client No errors! ``` If you are seeing errors in `vendor/`, re-run the composer install command to ensure that all dependencies are up to date. **NOTE**: If you add, delete or rename a class in the primary source tree `src/`, you should run `php composer.phar dump-autoload` in order to make the autoload maps refresh correctly; otherwise you will get class not found exceptions. ## Running A Local Instance Generate `public/` by running the build script. This script will only run the steps related to your changes, so the first run will be slower than later runs. ``` $ hhvm bin/build.php ``` HHVM has a built-in webserver, so it can serve the entire website. ``` $ cd public $ hhvm -m server -p 8080 -c ../hhvm.dev.ini ``` You can now see your local instance by visiting <http://localhost:8080>. When you make changes, you'll need to run `build.php` again. You can leave HHVM serving the site, and it will pick up the changes automatically. ## Running An Old Instance If you want to see old versions of the docs, we provide [regular Docker images of this site](https://hub.docker.com/r/hhvm/user-documentation/tags). This is not suitable for development, but it's useful if you're working with an old HHVM/Hack version. 1. Install [Docker](https://docs.docker.com/engine/installation/). 2. Start a container with `docker run -p 8080:80 -d hhvm/user-documentation`. 3. You can then access a local copy of the documentation at <http://localhost:8080>. ## Running A Production Instance Running a production instance is very similar to a development instance. Configure a webserver and HHVM to serve the `public/` directory. Ensure that all requests that don't match a local file are served by `index.php`.
Markdown
hhvm/hphp/hack/manual/hack/40-contributing/06-writing-content.md
The website has three content sections: * [Hack guides](https://github.com/hhvm/user-documentation/tree/main/guides/hack) describe the Hack language * [HHVM guides](https://github.com/hhvm/user-documentation/tree/main/guides/hhvm) describe how to install, configure and run the HHVM runtime * The API reference is generated from the API definitions, and this site [includes examples](https://github.com/hhvm/user-documentation/tree/main/api-examples) for each API ## File Naming Conventions A guide is a folder with a numeric prefix: ``` $ ls guides/hack/ 01-getting-started/ 02-source-code-fundamentals/ ... ``` These numbers are used to control the ordering of guides on the website, and are not shown in the UI. They do not need to be sequential: there can be gaps. Within each folder, there are markdown files (written in [GitHub flavored markdown](https://github.github.com/gfm/)), a `foo-category.txt` (used for grouping on the home page) and a `foo-summary.txt` (shown as a subheading on the home page). ``` $ ls guides/hack/01-getting-started/ 01-getting-started.md 02-tools.md getting-started-category.txt getting-started-summary.txt ``` Pages use the same numbering system to control their order within a guide. ## Writing Conventions Guides are written in a relatively informal tone, addressing the reader as "you". Assume the reader has some programming knowledge but no familiarity with Hack. Each page should have a clear purpose, starting with a short description of the concept it's describing. Examples should always be provided, preferably under 15 lines. We assume the reader has a relatively recent version of HHVM. References to very old features will be removed, but we provide [Docker images of historical site versions](/hack/contributing/introduction#running-an-old-instance) if needed. It's not necessary to document all the incorrect ways a feature can be used. Content should focus on correct usage, and users can rely on the Hack type checker to tell them when they've done something wrong. ## Links Internal links should be absolute paths without a domain, e.g. `/hack/contributing/introduction`. Image paths should be relative to `public`, e.g. `/images/imagename.png`. When removing or renaming pages, set up a redirect from the old URL. See [`Guides::getGuidePageRedirects`](https://github.com/hhvm/user-documentation/blob/9fd2aaeb60a236072ef99735a9114ec54d96da2c/src/Guides.php#L56). ## Styling We use [Sass](https://sass-lang.com/) to style the website, and the source files are in [sass/](https://github.com/hhvm/user-documentation/tree/main/sass). The CSS files are generated by the build script.
Markdown
hhvm/hphp/hack/manual/hack/40-contributing/10-code-samples.md
All code samples are automatically type checked and executed, to ensure they're correct. ## Basic Usage Code samples require triple backticks, and a file name. ~~~ ```example.hack <<__EntryPoint>> function main(): void { echo "Hello world!\n"; } ``` ~~~ The build script will create a file of this name, type check it, run it, and include the output in the rendered HTML. ## Boilerplate For small examples, the wrapper function can be distracting. You can use standalone statements and they will be automatically wrapped in an `<<__EntryPoint>>` function. We can simplify the previous example to this. ~~~ ```example.hack echo "Hello world!\n"; ``` ~~~ ## Opting Out If you really need to write a code sample that isn't checked or executed, you can omit the file name. The code sample will be included in the docs without any checking. ~~~ ``` // This example is not run at all. // It doesn't even need to be hack code! ``` ~~~ ## Sharing Code By default, each extracted example file has its own namespace based on the file name. This allows multiple examples to define the same class or function. If you want to share code between examples, use a file name prefix followed by `.`. Namespaces are generated based on the first name component, so `foo.x.hack` and `foo.y.hack` will have the same namespace. ~~~ Here's an example class: ```example_class.definition.hack class C {} ``` And its usage: ```example_class.usage.hack $c = new C(); ``` ~~~ Namespaces include the name of the page they're on, e.g. `Hack\UserDocumentation\Fundamentals\Namespaces\Examples\Main`, so you cannot share code between different pages. ## Autoloading HHVM requires an "autoloader" to be explicitly initialized whenever any Hack file references definitions from another Hack file. The build script will insert the necessary initialization code automatically into any `<<__EntryPoint>>` function, so it is OK to rely on definitions from other examples inside any `<<__EntryPoint>>` function or functions called by it, **but not elsewhere**. For example, HHVM can never successfully run a file containing e.g. a class definition that references a parent class or other definition from another file (this is not a limitation specific to the docs site). ~~~ ```example_hierarchy.parent.hack abstract class Parent {} ``` ```example_hierarchy.child.hack // This file will NEVER successfully run in HHVM. final class Child extends Parent {} ``` ~~~ In practice, this is fine because *running* a file containing a class definition is generally not needed. However, it *does* mean that trying to add an `<<__EntryPoint>>` function to `example_hierarchy.child.hack` won't work, because HHVM will fail with an "Undefined class Parent" error before it even reaches it. ~~~ ```example_hierarchy.child.hack // This file will NEVER successfully run in HHVM. final class Child extends Parent {} <<__EntryPoint>> function main(): void { // This EntryPoint function is useless because HHVM will fail above. } ``` ~~~ The workaround is to put any code that depends on definitions from more than one other example into a separate code block. ~~~ ```example_hierarchy.usage.hack $c = new Child(); ``` ~~~ This can also be more convenient because we can rely on the automatic boilerplate addition by the build script, instead of manually writing the `<<__EntryPoint>>` function header. ## Examples with Hack Errors Examples that are expected to fail typechecking should use the `.type-errors` extension: ~~~ ```error_example.hack.type-errors function missing_return_type() {} ``` ~~~ The build script will run the Hack typechecker and include its output in the rendered HTML (instead of HHVM runtime output). ## Supporting Files An example code block may specify additional files to be extracted alongside the example code using the following format: ~~~ ```nondeterministic_example.hack echo "Your lucky number is: ".\mt_rand(0, 99); ```.example.hhvm.out Your lucky number is: 42 ```.expectf Your lucky number is: %d ``` ~~~ Supported extensions are inherited from the [HHVM test runner](https://github.com/facebook/hhvm/blob/master/hphp/test/README.md#file-layout): - `.hhconfig` if the example requires specific *typechecker* flags (e.g. demonstrating a feature that is not yet enabled by default) - `.ini` for *runtime* flags - `.hhvm.expect` if you want to manually specify the expected output, instead of the build script doing it automatically - `.hhvm.expectf` to specify the expected output using printf-style syntax, like in the example above - `.expectregex` to specify the expected output using a regular expression - `.example.hhvm.out` should contain one possible output (this will be included in the rendered HTML instead of the `expectf`/`expectregex` file; it is not needed for regular `expect` files) - `.typechecker.expect`, `.typechecker.expectf`, `.typechecker.expectregex`, `.example.typechecker.out` are the same but for typechecker (Hack) output instead of runtime (HHVM) output; they should only be included if the example code is expected to fail typechecking *and* you don't want the build script to generate them automatically - `.skipif` should contain valid Hack code that will print "skip" if the example should not be run (e.g. a MySQL example that should not run if there isn't a MySQL server running), otherwise print nothing ## Testing Changes We have a test suite to ensure consistency across the changes we make to the guides, API references, and examples. You can run it as follows: ``` $ vendor/bin/hacktest tests/ ``` ## Running the Examples Nearly all of the code examples you see in the guides and API documentation are actual Hack or PHP source files that are embedded at site build time into the content itself. As opposed to embedded the code examples directly within the markdown itself, this provides the flexibility of actually having running examples within this repo. You must have HHVM installed in order to run these examples since most of them are written in Hack (e.g., `<?hh`), and HHVM is the only runtime to currently support Hack. You will find the examples in directories named with the pattern: ``` guides/[hhvm | hack]/##-topic/##-subtopic-examples ``` e.g., ``` $ guides/hack/23-collections/06-constructing-examples ``` ### Standalone You can run any example standalone. For example: ``` # Assuming you are in the user-documentation repo directory $ cd guides/hack/23-collections/10-examples-examples/ $ hhvm lazy.php ``` And you will see output like: ``` object(HH\Vector)#4 (5) { [0]=> int(0) [1]=> int(2) [2]=> int(4) [3]=> int(6) [4]=> int(8) } Time non lazy: 0.10859489440918 object(HH\Vector)#10 (5) { [0]=> int(0) [1]=> int(2) [2]=> int(4) [3]=> int(6) [4]=> int(8) } Time non lazy: 0.0096559524536133 ``` ### Using the HHVM Test Runner Each example is structured to be run with the [HHVM test runner](https://github.com/facebook/hhvm/blob/master/hphp/test/README.md). We use the test runner internally to ensure that any changes made to HHVM do not cause a regression. The examples in the documentation here can be used for that purpose as well. You can run the HHVM test runner on the entire suite of examples, on one directory of examples or just one example itself. *Normally you will use our test suite described [above](#testing-changes) to test any changes you make (because it tests our examples as well). However, sometimes it is actually faster and more explicit to test one example directly with the HHVM test runner.* ``` # Assuming you are in the user-documentation repo root # This runs every example in the test runner. # Won't normally need to do this; just use our test suite instead. # Test with the typechecker $ api-sources/hhvm/hphp/test/run --hhserver-binary-path $(which hh_server) --typechecker guides/hack/05-statements/ # Test with the runtime $ api-sources/hhvm/hphp/test/run --hhvm-binary-path $(which hhvm) guides/hack/05-statements/ ``` Here is the output you should see when you run the test runner. Assume we are running the examples in the collections topic: ``` $ hhvm api-sources/hhvm/hphp/test/run guides/hack/23-collections/ Running 32 tests in 32 threads (0 in serial) All tests passed. | | | )_) )_) )_) )___))___))___)\ )____)____)_____)\ _____|____|____|____\\__ ---------\ SHIP IT /--------- ^^^^^ ^^^^^^^^^^^^^^^^^^^^^ ^^^^ ^^^^ ^^^ ^^ ^^^^ ^^^ Total time for all executed tests as run: 11.57s ``` You can use `--verbose` to see all the tests that are running.
Markdown
hhvm/hphp/hack/manual/hack/40-contributing/12-information-macros.md
This website supports note, tip, caution, and danger macro messages. ## Note Message ```yamlmeta { "note": [ "This change was introduced in [HHVM 4.136](https://hhvm.com/blog/2021/11/19/hhvm-4.136.html)." ] } ``` The `noreturn` type can be upcasted to `dynamic`. ## Tip Message ```yamlmeta { "tip": [ "To start learning Hack, read our [Getting Started](/hack/getting-started/getting-started) documentation!" ] } ``` Hack lets you write code quickly, while also having safety features built in, like static type checking. ## Caution Message ```yamlmeta { "caution": [ "We do not recommend using experimental features until they are formally announced and integrated into the main documentation set." ] } ``` This website maintains documentation on Hack features that are in the *experimental* phase. ## Warning Message ```yamlmeta { "danger": [ "Use this method with caution. **If your query contains *ANY* unescaped input, you are putting your database at risk.**" ] } ``` While inherently dangerous, you can use `AsyncMysqlConnection::query` to query a MySQL database client.
Markdown
hhvm/hphp/hack/manual/hack/40-contributing/15-generated-content.md
## Generating Markdown Occasionally you may want to generate markdown programmatically. For example, the [supported PHP INI settings table](/hhvm/configuration/INI-settings#supported-php-ini-settings) is autogenerated. 1. Define a `BuildStep` for the data you want to generate the markdown from. See [PHPIniSupportInHHVMBuildStep](https://github.com/hhvm/user-documentation/blob/main/src/build/PHPIniSupportInHHVMBuildStep.php) for an example. 2. Define a `BuildStep` that writes markdown to the guides-generated-markdown/ directory, [defined here](https://github.com/hhvm/user-documentation/blob/9fd2aaeb60a236072ef99735a9114ec54d96da2c/src/build/BuildPaths.php#L49). See [PHPIniSupportInHHVMMarkdownBuildStep](https://github.com/hhvm/user-documentation/blob/main/src/build/PHPIniSupportInHHVMMarkdownBuildStep.php) for an example. 3. Add a symlink ([example](https://github.com/hhvm/user-documentation/blob/main/guides/hhvm/04-configuration/guides-generated-markdown)) to the guide folder where you want to include this content. 4. Use `@@` syntax to include the generated file on the relevant page of your guide. ``` @@ guides-generated-markdown/your_generated_file.md @@ ``` 5. Add a test ([example](https://github.com/hhvm/user-documentation/blob/9fd2aaeb60a236072ef99735a9114ec54d96da2c/tests/GuidePagesTest.php#L84)). ## API Example Code Adding a `.md` file to the correct subdirectory in [`api-examples`](https://github.com/hhvm/user-documentation/tree/main/api-examples) will cause the build script to add its content to the respective API page. The `.md` file may contain any combination of explanatory text and any number of code examples following the same rules as above.
Markdown
hhvm/hphp/hack/manual/hack/51-experimental-features/01-introduction.md
The following pages of documentation describe Hack language features in the *experimental* phase. ## About Experimental Features We have documented these features as they may appear in built-ins, including the Hack Standard Library. We _do not_ recommend using any of these features until they are formally announced and integrated into the main documentation set. ## Enabling an Experimental Feature To use an experimental feature, add the `__EnableUnstableFeatures` file attribute to any files containing that feature. ```Hack no-extract <<file:__EnableUnstableFeatures('experimental_feature_name')>> ``` You can also specify multiple features: ```Hack no-extract <<file:__EnableUnstableFeatures('experimental_feature_name', 'other_experimental_feature_name')>> ```
Markdown
hhvm/hphp/hack/manual/hack/55-expression-trees/01-introduction.md
Expression trees are an experimental Hack feature that allow you write domain specific languages (DSLs) with Hack syntax. You can write expressions using normal Hack syntax, and all the normal Hack tools work: syntax highlighting, type checking, and code completion. Unlike normal Hack code, **expression tree code is not executed**. ```hack no-extract $e = MyDsl`foo() + 1`; ``` ## What is executed at runtime? Hack converts an expression tree to a series of method calls on a visitor. ```hack no-extract // You write code like this: $e = MyDsl`1 + 2`; // Hack runs the following "desugared" code: $e = MyDsl::makeTree<MyDslInt>( ($v) ==> $v->visitBinop( $v->visitInt(1), '__plus' $v->visitInt(2)) ); ``` The visitor can also define the types associated with literals and operators. This enables Hack to typecheck the DSL expression, even if `1` doesn't represent a Hack `int`. ```hack no-extract // The type checker will also check that this "virtualized" expression is correct, // even though this virtualized code isn't executed. (MyDsl::intType())->__plus(MyDsl::intType()); ``` ## Why? DSLs without expression trees are verbose and unchecked. ```hack no-extract // No checking or highlighting at all. takes_dsl_string("foo()"); // Verbose, limited type checking, no support for loops or variables in the DSL. takes_dsl_object(new DslFunctionCall("foo")); ``` ## When is this useful? DSLs are useful when you're generating code for scripting languages, such as JavaScript in the browser or stored procedures in a database.
Markdown
hhvm/hphp/hack/manual/hack/55-expression-trees/05-syntax-supported.md
Expression tree DSLs can use most of the expression and statement syntax in Hack. For a full list of supported syntax, see also [expr_tree.hhi](https://github.com/facebook/hhvm/blob/master/hphp/hack/test/hhi/expr_tree.hhi). ## Literals | Example | Visitor Runtime | Typing | |---------|-------------------------------------|-----------------------| | `true` | `$v->visitBool($position, true)` | `MyDsl::boolType()` | | `1` | `$v->visitInt($position, 1)` | `MyDsl::intType()` | | `1.23` | `$v->visitFloat($position, 1.23)` | `MyDsl::floatType()` | | `"foo"` | `$v->visitString($position, "foo")` | `MyDsl::stringType()` | | `null` | `$v->visitString($position)` | `MyDsl::nullType()` | | N/A | N/A | `MyDsl::voidType()` | ## Binary Operators Operator names are based on the appearance of the symbol, as different DSLs may choose different semantics for an operator. | Example | Visitor Runtime | Typing | |-------------|-------------------------------------------------------------------|-------------------------------------------| | `$x + $y` | `$v->visitBinop($position, ..., '__plus', ...)` | `__plus` method on `$x` | | `$x - $y` | `$v->visitBinop($position, ..., '__minus', ...)` | `__minus` method on `$x` | | `$x * $y` | `$v->visitBinop($position, ..., '__star', ...)` | `__star` method on `$x` | | `$x / $y` | `$v->visitBinop($position, ..., '__slash', ...)` | `__slash` method on `$x` | | `$x % $y` | `$v->visitBinop($position, ..., '__percent', ...)` | `__percent` method on `$x` | | `$x && $y` | `$v->visitBinop($position, ..., '__ampamp', ...)` | `__ampamp` method on `$x` | | `$x \|\| $y` | `$v->visitBinop($position, ..., '__barbar', ...)` | `__barbar` method on `$x` | | `$x < $y` | `$v->visitBinop($position, ..., '__lessThan', ...)` | `__lessThan` method on `$x` | | `$x <= $y` | `$v->visitBinop($position, ..., '__lessThanEqual', ...)` | `__lessThanEqual` method on `$x` | | `$x > $y` | `$v->visitBinop($position, ..., '__greaterThan', ...)` | `__greaterThan` method on `$x` | | `$x >= $y` | `$v->visitBinop($position, ..., '__greaterThanEqual', ...)` | `__greaterThanEqual` method on `$x` | | `$x === $y` | `$v->visitBinop($position, ..., '__tripleEquals', ...)` | `__tripleEquals` method on `$x` | | `$x !== $y` | `$v->visitBinop($position, ..., '__notTripleEquals', ...)` | `__notTripleEquals` method on `$x` | | `$x . $y` | `$v->visitBinop($position, ..., '__dot', ...)` | `__dot` method on `$x` | | `$x & $y` | `$v->visitBinop($position, ..., '__amp', ...)` | `__amp` method on `$x` | | `$x \| $y` | `$v->visitBinop($position, ..., '__bar', ...)` | `__bar` method on `$x` | | `$x ^ $y` | `$v->visitBinop($position, ..., '__caret', ...)` | `__caret` method on `$x` | | `$x << $y` | `$v->visitBinop($position, ..., '__lessThanLessThan', ...)` | `__lessThanLessThan` method on `$x` | | `$x >> $y` | `$v->visitBinop($position, ..., '__greaterThanGreaterThan', ...)` | `__greaterThanGreaterThan` method on `$x` | ## Ternary Operators | Example | Visitor Runtime | Typing | |----------------|---------------------------------------------|--------------------------| | `$x ? $y : $z` | `$v->visitTernary($position, ..., ..., ...)` | `$x->__bool() ? $y : $z` | ## Unary Operators | Example | Visitor Runtime | Typing | |---------|------------------------------------------------------------|------------------------------------| | `!$x` | `$v->visitUnop($position, ..., '__exclamationMark')` | `__exclamationMark` method on `$x` | | `-$x` | `$v->visitUnop($position, ..., '__negate')` | `__negate` method on `$x` | | `~$x` | `$v->visitUnop($position, ..., '__tilde')` | `__tilde` method on `$x` | | `$x++` | `$v->visitUnop($position, ..., '__postfixPlusPlus')` | `__postfixPlusPlus` method on `$x` | | `$x--` | `$v->visitUnop($position, ..., '__postfixMinusMinus')` | `__postfixMinusMinus` method on `$x` | ## Local Variables | Example | Visitor Runtime | Typing | |-----------|----------------------------------------|---------------------| | `$x` | `$v->visitLocal($position, '$x')` | Same as normal Hack | You can see here that the visitor runtime does not know the type of `$x`, it just sees a call to `visitLocal` with the variable name as a string `'$x'`. Note that expression trees do not allow free variables. You can only use local variables that have been previously assigned or introduced with a lambda. ## Lambdas | Example | Visitor Runtime | Typing | |-------------------|---------------------------------------------------|---------------------| | `(Foo $x) ==> $y` | `$v->visitLambda($position, vec['$x'], vec[...])` | Same as normal Hack | Note that the visitor runtime does not see the type of `$x`. ## Statements | Example | Visitor Runtime | Typing | |-----------------------------|--------------------------------------------------------------|---------------------------------------| | `$x = $y;` | `$v->visitAssign($position, ..., ...)` | Same as normal Hack | | `return $x;` | `$v->visitReturn($position, ...)` | Same as normal Hack | | `return;` | `$v->visitReturn($position, null)` | Same as normal Hack | | `if (...) {...} else {...}` | `$v->visitIf($position, ..., ..., ...)` | `if (...->__bool()) {...} else {...}` | | `while (...) {...}` | `$v->visitWhile($position, ..., vec[...])` | `while (...->__bool()) {...}` | | `for (...; ...; ...) {...}` | `$v->visitFor($position, vec[...], ..., vec[...], vec[...])` | `for (...; ...->__bool(); ...) {...}` | | `break;` | `$v->visitBreak($position)` | Same as normal Hack | | `continue;` | `$v->visitContinue($position)` | Same as normal Hack | ## Calls | Example | Visitor Runtime | Typing | |-----------------|-------------------------------------------------------------------------------------|-----------------------------------| | `foo(...)` | `$v->visitCall($position, $v->visitGlobalFunction($position, foo<>), vec[...])` | `MyDsl::symbolType(foo<>)()` | | `Foo::bar(...)` | `$v->visitCall($position, $v->visitStaticMethod($position, Foo::bar<>), vec[...])` | `MyDsl::symbolType(Foo::bar<>)()` | Note that the function or method must have a Hack definition, so the typechecker can verify that it's being called with appropriate arguments. ## XHP Literals | Example | Visitor Runtime | Typing | |----------------------|-------------------------------------------------------------|----------------------| | `<foo ...>...</foo>` | `$v->visitXhp($position, :foo::class, dict[...], vec[...])` | `<foo ...>...</foo>` | ## Property Access | Example | Visitor Runtime | Typing | |--------------|--------------------------------------------------|--------------| | `(...)->foo` | `$v->visitPropertyAccess($position, ..., 'foo')` | `(...)->foo` | ## Splicing | Example | Visitor Runtime | Typing | |--------------|--------------------------------------------------|--------------| | `${$x}` | `$v->splice($position, 'key0', $x)` | Extract the inferred type out of the third type argument of `Spliceable` | ## Unsupported Features Expression trees may only contain expressions between the backticks. ```hack error MyDsl`1`; // OK: 1 is an expression MyDsl`while(true) {}`; // Bad: statement MyDsl`() ==> { while true() {} }`; // OK: statements are allowed in lambdas MyDsl`class Foo {}`; // Bad: top-level declaration. ``` ## Expression Tree Blocks There are times when it is desirable to include statements as part of an expression tree. One way to accomplish this is to create a lambda that is immediately invoked. ```hack <<file:__EnableUnstableFeatures('expression_trees')>> function example1(): void { $num = ExampleDsl`1 + 1`; ExampleDsl`() ==> { $n = ${$num}; return $n + $n; }()`; } ``` This can be rewritten using expression tree blocks, eliminating the need to create a lambda and invoke it. ```hack <<file:__EnableUnstableFeatures('expression_trees')>> function example2(): void { $num = ExampleDsl`1 + 1`; ExampleDsl`{ $n = ${$num}; return $n + $n; }`; } ``` Note that expression tree blocks are syntactic sugar. It will be expanded to the longer form for both type checking and the visitor runtime.
Markdown
hhvm/hphp/hack/manual/hack/55-expression-trees/10-splicing.md
Expression trees support "splicing", where you insert one expression tree into another. ```hack <<file:__EnableUnstableFeatures('expression_trees')>> function splicing_example(bool $b): ExprTree<ExampleDsl, mixed, ExampleString> { $name = $b ? ExampleDsl`"world"` : ExampleDsl`"universe"`; return ExampleDsl`"Hello, ".${$name}."!"`; } ``` This allows you to build different expressions based on runtime values. DSL expressions are not evaluated, but the value in the `${...}` is evaluated and inserted into the expression tree. The above example is equivalent to this: ```hack <<file:__EnableUnstableFeatures('expression_trees')>> function splicing_example2(bool $b): ExprTree<ExampleDsl, mixed, ExampleString> { return $b ? ExampleDsl`"Hello, "."world"."!"` : ExampleDsl`"Hello, "."universe"."!"`; } ``` ## Limitations Every DSL expression must be valid in isolation. You cannot use free variables in expression trees, even when splicing. ```hack error $var = ExampleDsl`$x`; // type error: $x is not defined ExampleDsl`($x) ==> { return ${$var}; }`; ``` ## Implementing Splicing A visitor needs to support the `splice` method to allow splicing. The `splice` method is passed the inner expression tree value, along with a unique key that may be used for caching visitor results. ```hack no-extract final class MyDsl { public function splice( ?ExprPos $_pos, string $_key, Spliceable<MyDsl, MyDslAst, mixed> $code, ): MyDslAst { return $code->visit($this); } // ... } ``` For more information, see: [Defining Visitors: Spliceable Types](/hack/expression-trees/defining-dsls#spliceable-types).
Markdown
hhvm/hphp/hack/manual/hack/55-expression-trees/15-defining-dsls.md
Adding a DSL to Hack requires you to define a new visitor. This page will demonstrate defining a DSL supporting integer arithmetic: ```hack no-extract $e = MyDsl`1 + 2`; ``` ## DSLs are opt-in Hack only allows expression tree syntax usage for approved DSLs. These are specified in `.hhconfig`. ``` allowed_expression_tree_visitors = MyDsl, OtherDsl ``` If you just want to test your DSL, you can enable all expression syntax with the `__EnableUnstableFeatures` file attribute. ```hack no-extract <<file:__EnableUnstableFeatures('expression_trees')>> function foo(): void { $e = MyDsl`1 + 2`; } ``` ## Representing DSL Expressions Our DSL needs a data type to represent expressions written by the user. We'll define a simple abstract syntax tree (AST). ```Hack file:mydsl.hack abstract class MyDslAst {} class MyDslAstBinOp extends MyDslAst { public function __construct( public MyDslAst $lhs, public string $operator, public MyDslAst $rhs, ) {} } class MyDslAstInt extends MyDslAst { public function __construct(public int $value) {} } ``` ## A DSL For Integer Literals Hack converts backtick syntax into method calls. ```hack no-extract // The user writes backtick syntax. $e = MyDsl`1`; // The runtime sees a lambda calling methods on MyDSL (simplified) (MyDsl $v) ==> $v->visitInt(null, 1); ``` Our basic visitor looks like this. ```hack no-extract // The runtime will pass file and line position in ExprPos. type ExprPos = shape(...); class MyDsl { // The visitor is passed the literal value, so 1 in our example. public function visitInt(?ExprPos $_pos, int $value): MyDslAst { return new MyDslAstInt($value); } } ``` ## Adding Operators ```hack no-extract // User syntax. $e = MyDsl`1 + 2`; // Runtime (simplified) (MyDsl $v) ==> $v->visitBinop( null, $v->visitInt(null, 1), '__plus', $v->visitInt(null, 2) ); ``` You can see that `$v-visitBinop()` receives the return value of `$v->visitInt()`. This allows the visitor to construct more complex ASTs. **The `visitFoo` methods are always unityped.** They receive ASTs without type information, and return an untyped AST. Typechecking happens separately. We can support binary operators by adding `visitBinop` to our visitor. ```Hack no-extract class MyDsl { public function visitBinop( ?ExprPos $_pos, MyDslAst $lhs, string $operator, MyDslAst $rhs, ): MyDslAst { return new MyDslAstBinOp($lhs, $operator, $rhs); } public function visitInt(?ExprPos $_pos, int $value): MyDslAst { return new MyDslAstInt($value); } } ``` ## The DSL Builder The visitor closure isn't enough. We want to type check the DSL expression, and we might want to do additional work before we execute the closure. ```hack no-extract // The user writes backtick syntax. $e = MyDsl`1`; // Runtime (actual). The first two arguments are extra position information // and function metadata which aren't used in this tutorial. MyDsl::makeTree<MyDslInt>(null, shape(), (MyDsl $v) ==> $v->visitInt(null, 1)) ``` We call `makeTree` on our visitor class, providing the visitor closure and some additional metadata. The type checker also sees the `TInfer` type, which is `MyDslInt` in this example (discussed below). ```Hack file:mydsl.hack class MyDsl { public static function makeTree<<<__Explicit>> TInfer>( ?ExprPos $pos, mixed $_metadata, (function(MyDsl): MyDslAst) $visit_expr, ): MyDslExprTree<TInfer> { return new MyDslExprTree($pos, $visit_expr); } // ... all the visitFoo methods here } ``` ### Positions The builder method `makeTree` takes a nullable position argument as its first argument, as do all of the `visit...` methods on the Visitor class. At runtime, all of the methods will receive a shape value with the following type: ```hack no-extract shape( 'path' => string, 'start_line' => int, 'start_column' => int, 'end_line' => int, 'end_column' => int, ) ``` DSLs can choose to use this information to report errors with positional information about the source code back to the user. ### Metadata The second argument to the `makeTree` method is a shape containing parts of the expression tree that may be useful to have references to without processing the entirety of the `$visit_expr`. The shape has the type: ```hack no-extract shape( 'splices' => dict<string, mixed>, 'functions' => vec<mixed>, 'static_methods' => vec<mixed>, ) $metadata ``` For the `functions` and `static_methods` fields, the vec contains the function pointers to any global functions or static method referenced within the expression tree. The same function pointers are passed to the individual calls of `visitGlobalFunction` and `visitStaticMethod`. The `splices` field contains a dictionary of string keys and the values the splices are evaluated to. The string keys are generated by the runtime and correspond to the string key and value passed to each individual `splice` Visitor method call. ## Spliceable Types Expression tree values implement `Spliceable`, a typed value that can be visited or spliced into another `Spliceable`. Here's the definition for the `Spliceable` interface. ```Hack no-extract /** * Spliceable is this base type for all expression tree visitors. * * A visitor is a class with a visit method. This is extremely generic, so * visitors can choose what they want to construct. * * Typically, you'll use a concrete type rather than this interface. For * example: * * $e = EtDemo`123`; * * This has type `Spliceable<EtDemoVisitor, EtDemoAst, EtDemoInt>`. * * TVisitor: The class with the `visit` method that constructs the value. * TResult: The type we get back when running the visitor. * TInfer: The inferred type of the expression, used only for type checking. */ interface Spliceable<TVisitor, TResult, +TInfer> { public function visit(TVisitor $visitor): TResult; } ``` The `MyDslExprTree` class implements `Spliceable`, and calls the visitor closure ('builder') when `visit` is called. ```Hack file:mydsl.hack class MyDslExprTree<+T> implements Spliceable<MyDsl, MyDslAst, T> { public function __construct( public ?ExprPos $pos, private (function(MyDsl): MyDslAst) $builder, ) {} public function visit(MyDsl $v): MyDslAst { return ($this->builder)($v); } } ``` ### DSL Types ```hack no-extract // Inferred type: MyDslExprTree<MyDslInt> $e = MyDsl`1`; ``` Hack needs to know what types our DSL uses. The visitor specifies the type of literals using `fooType` stub methods. ```hack no-extract class MyDsl { public static function intType(): MyDslInt { // Only used for type checking, so we don't need an implementation here. throw new Exception(); } // ... } ``` For each type in our DSL, we define an associated type. It's usually easier to use interfaces for these types, as they're only used for type checking. ```Hack no-extract interface MyDslNonnull {} interface MyDslInt extends MyDslNonnull { public function __plus(MyDslInt $_): MyDslInt; public function __minus(MyDslInt $_): MyDslInt; } ``` This allows integers to support the `+` and `-` operators in our DSL, and they return DSL integers.
Markdown
hhvm/hphp/hack/manual/hack/55-expression-trees/20-dsl-types.md
For every literal supported in a DSL, the visitor must provide a stub method that shows what type it should have. ```Hack file:types.hack class MyDsl { // Types for literals public static function intType(): MyDslInt { throw new Exception(); } public static function floatType(): MyDslFloat { throw new Exception(); } public static function boolType(): MyDslBool { throw new Exception(); } public static function stringType(): MyDslString { throw new Exception(); } // Visitors can use the normal Hack types if they wish. // This is particularly common for null and void. public static function nullType(): null { throw new Exception(); } public static function voidType(): void { throw new Exception(); } // symbolType is used in function calls. // In this example, MyDsl is using normal Hack // functions but DSLs may choose more specific APIs. public static function symbolType<T>( T $_, ): T { throw new Exception(); } } ``` All types used in the visitor need to define what operators they support. Here's an expanded version of `MyDsl` with types that are very similar to plain Hack. ```Hack file:types.hack interface MyDslNonnull { public function __tripleEquals(?MyDslNonnull $_): MyDslBool; public function __notTripleEquals(?MyDslNonnull $_): MyDslBool; } interface MyDslNum extends MyDslNonnull { // Arithmetic public function __plus(MyDslNum $_): MyDslNum; public function __minus(MyDslNum $_): MyDslNum; public function __star(MyDslNum $_): MyDslNum; public function __slash(MyDslNum $_): MyDslNum; public function __negate(): MyDslNum; // Comparisons public function __lessThan(MyDslNum $_): MyDslBool; public function __lessThanEqual(MyDslNum $_): MyDslBool; public function __greaterThan(MyDslNum $_): MyDslBool; public function __greaterThanEqual(MyDslNum $_): MyDslBool; } interface MyDslInt extends MyDslNum { // Only support modulus on integers in our demo. public function __percent(MyDslInt $_): MyDslInt; // Bitwise operators public function __amp(MyDslInt $_): MyDslInt; public function __bar(MyDslInt $_): MyDslInt; public function __caret(MyDslInt $_): MyDslInt; public function __lessThanLessThan(MyDslInt $_): MyDslInt; public function __greaterThanGreaterThan(MyDslInt $_): MyDslInt; public function __tilde(): MyDslInt; } interface MyDslFloat extends MyDslNum { <<__Override>> public function __plus(MyDslNum $_): MyDslFloat; } interface MyDslString extends MyDslNonnull { public function __dot(MyDslString $_): MyDslString; } interface MyDslBool extends MyDslNonnull { // __bool signifies that we can use MyDslBool in positions that require // a truthy value, such as if statements. public function __bool(): bool; // Infix operators that return another MyDslBool. public function __ampamp(MyDslBool $_): MyDslBool; public function __barbar(MyDslBool $_): MyDslBool; public function __exclamationMark(): MyDslBool; } ```
Markdown
hhvm/hphp/hack/manual/hack/56-memoization-options/01-introduction.md
```yamlmeta { "fbonly messages": [ "There is [an internal wiki](https://www.internalfb.com/intern/wiki/Hack_Foundation/Memoization_options/) with more, Meta-specific guidance." ] } ``` The `__Memoize` and `__MemoizeLSB` attributes in Hack support experimental options that control how the function behaves with respect to an Implicit Context value. ## Introduction The Implicit Context (IC) is an experimental feature. It is a value that can be associated with the execution of code and propagated implicitly from caller to callee in a way that is safe for [concurrently running code](/hack/asynchronous-operations/introduction). In order to prevent the problem of "memoization cache poisoning" where results computed using one IC value are available to callers using a different IC value, we require that memoized functions executed with an IC value are explicit about how they should behave relative to the IC value. Broadly, functions can specify one of two choices: * This function's memoization cache key _should_ incorporate the propagated IC value. * This function's memoization cache key _should not_ incorporate the propagated IC value *AND* this function and its dependencies cannot depend on the propagated IC value. These requirements are enforced at runtime via thrown exceptions and not statically by the typechecker. If static requirements are desired, one can make use of special [contexts and capabilities](/hack/contexts-and-capabilities/introduction) specifically `zoned`. ## Available Options A memoized function may specify its behavior relative to the IC by passing an option to the `__Memoize` (or `__MemoizeLSB`) attribute. ```Hack <<__Memoize(#MakeICInaccessible)>> function get_same_random_int(): int { return HH\Lib\PseudoRandom\int(); } ``` There are two options that are compatible with propagating an IC value — `#KeyedByIC` and `#MakeICInaccessible` — and two options that are not — `#SoftMakeICInaccessible` and `#Uncategorized`. Functions with one of the former pair of options are considered “categorized” while functions with one of the latter pair of options is considered “uncategorized.” See below for the treatment of memoized functions that do not pass an argument to the memoize attribute. * `#KeyedByIC` indicates that the function’s memoization cache should include the IC value in the cache key. * Memoized functions that depend on the IC should use this option. * Memoized functions with the `[zoned]` context must use this option. * A function must have one of the following contexts to use this option: `defaults` (implicitly or explicitly), `zoned`, `zoned_local`, `zoned_shallow` * Note that the cache may also be keyed on metadata necessary for sufficiently complete migration logging and so you should not assume that just because your function isn’t currently being called with a propagated IC value that it is only called once. * `#MakeICInaccessible` indicates that the function’s memoization cache should *not* include the IC value in the cache key and that the function does not access the IC. * Any direct or indirect calls to the builtin function that fetches the IC will result in an exception. * Any direct or indirect calls to an uncategorized memoized function will throw. * A function must have one of the following contexts to use this option: `defaults` (implicitly or explicitly), `leak_safe_shallow`, `leak_safe_local` * `#SoftMakeICInaccessible` is a migration option for functions that are intended to be marked with `#MakeICInaccessible`. * The function’s memoization cache will *not* include the IC value in the cache key. * In circumstances in which using `#MakeICInaccessible` will throw, using `#SoftMakeICInaccessible` instead will result in runtime logs. * Note that functions using this operation are still considered “uncategorized.” * `#Uncategorized` is an option that explicitly indicates that a function has not yet described its intended behavior relative to the IC. * If no option is provided, the function’s memoization cache will not include the IC value, but whether or not it is considered “categorized” or “uncategorized” will depend on the function’s context list. * If the functions’ context already prevents the function from fetching the IC which requires the `[zoned]` context (i.e. the function is as capable as or less capable than `[leak_safe, globals]`) then no option is allowed and the function is considered categorized. * Otherwise, the function is considered uncategorized. >Note that this syntax uses “[enum class labels](/hack/built-in-types/enum-class-label)” as arguments. Currently, only the memoization attributes are allowed to use labels as arguments. ## Related classes and functions ```yamlmeta { "fbonly messages": [ "Meta developers should not use these symbols directly and instead should only use them via Zones APIs." ] } ``` * Executing code with an IC value and accessing the propagated value is done by extending and using methods of the class `HH\ImplicitContext`. * Functions `HH\ImplicitContext\soft_run_with` and `HH\ImplicitContext\soft_run_with_async` are used to execute code in a migratory state ahead of using `HH\ImplicitContext::runWith` or `HH\ImplicitContext::runWithAsync` -- in this migratory state, calls to uncategorized memoized functions produce runtime warnings instead of exceptions.
hhvm/hphp/hack/scripts/.ocamlformat
# -*- conf -*- # The .ml files in this directory are scripts for utop, not normal ocaml syntax. disable = true
Shell Script
hhvm/hphp/hack/scripts/build_and_run.sh
#!/bin/bash # 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. set -e SCRIPT_DIR="$(dirname "$0")" FBCODE_ROOT="$(realpath "${SCRIPT_DIR}/../../../")" HPHP_ROOT="${FBCODE_ROOT}/hphp" HACK_ROOT="${FBCODE_ROOT}/hphp/hack" FB_DUNE_BUILD_DIR="${HACK_ROOT}/facebook/redirect/dune_build" HACK_SUBDIR="$1" TARGET="$2" ARGS=($@) ARGS=(${ARGS[@]:2}) function dune_build() { # OCaml if [ -e "${HACK_ROOT}/${HACK_SUBDIR}/${TARGET}.ml" ]; then ( cd "${HACK_ROOT}" "${DUNE}" build --no-print-directory "${HACK_SUBDIR}/${TARGET}.exe" ) exec "${DUNE_BUILD_DIR}/default/hack/$HACK_SUBDIR/${TARGET}.exe" "${ARGS[@]}" fi # Rust if [ -e "${HACK_ROOT}/${HACK_SUBDIR}/${TARGET}.rs" ]; then export CARGO_TARGET_DIR="${DUNE_BUILD_DIR}/cargo" ( cd "${HACK_ROOT}/${HACK_SUBDIR}" "${CARGO}" build --bin "${TARGET}" ) exec "${CARGO_TARGET_DIR}/debug/${TARGET}" "${ARGS[@]}" fi } cd "${FBCODE_ROOT}" if [ -e "${HACK_ROOT}/facebook/dune.sh" ] && [ -e "${FB_DUNE_BUILD_DIR}" ]; then # FB Dune DUNE="${HACK_ROOT}/facebook/dune.sh" \ CARGO="${HACK_ROOT}/scripts/facebook/cargo.sh" \ DUNE_BUILD_DIR="${FB_DUNE_BUILD_DIR}" dune_build elif [ -e "${FBCODE_ROOT}/third-party/CMakeLists.txt" ]; then # Open Source Dune DUNE="dune" \ CARGO="cargo" \ dune_build elif [ -e "${HPHP_ROOT}/facebook" ]; then # FB Buck exec buck2 run "//hphp/hack/${HACK_SUBDIR}:${TARGET}" -- "${ARGS[@]}" else echo "Couldn't determine build system" exit 1 fi
Shell Script
hhvm/hphp/hack/scripts/concatenate_all.sh
#!/bin/sh # First arg is implicit with buck INSTALL_DIR="${1#--install_dir=}" ROOT="${2#--root=}" OUTPUT_FILE="${3#--output_file=}" if [ "${OUTPUT_FILE#/}" = "${OUTPUT_FILE}" ]; then OUTPUT_FILE="${INSTALL_DIR}/${OUTPUT_FILE}" fi mkdir -p "$(dirname "${OUTPUT_FILE}")" set -e ( find "${ROOT}" -name "*.php" -o -name "*.hack" | while read -r FILE; do echo "///// ${FILE} /////" if grep -qE "^namespace .*;" "$FILE"; then # [?] is a bit strange, but works with both BSD and GNU sed :) sed "/^<[?]hh/d" "$FILE" | \ sed "s/^\(namespace .*\);/\1 {/" echo "}" else sed "/^<[?]hh/d" "$FILE" fi done ) > "${OUTPUT_FILE}"
hhvm/hphp/hack/scripts/dune
(rule (targets get_build_id_gen.c) (deps gen_build_id.ml utils.ml) (action (run ocaml -I scripts -w -3 unix.cma gen_build_id.ml get_build_id_gen.c)))
Shell Script
hhvm/hphp/hack/scripts/fail_on_unclean_repo.sh
#!/bin/bash echo "List of modified files:" CHANGED_FILES="$(hg st)" echo "$CHANGED_FILES" if [[ -z "$CHANGED_FILES" ]] then echo "No files changed!" else echo "ERROR: Files have changed! Please run \"$1\" and amend generated files into diff." exit 1 fi
Shell Script
hhvm/hphp/hack/scripts/generate_full_fidelity.sh
#!/bin/bash set -u # terminate upon read of uninitalized variable set -e # terminate upon non-zero-exit-codes (in case of pipe, only checks at end of pipe) set -o pipefail # in a pipe, the whole pipe runs, but its exit code is that of the first failure trap 'echo "exit code $? at line $LINENO" >&2' ERR set -x # echo every statement in the script FBCODE_ROOT="$(dirname "${BASH_SOURCE[0]}")/../../.." cd "${FBCODE_ROOT}" buck2 run //hphp/hack/src:generate_full_fidelity
Shell Script
hhvm/hphp/hack/scripts/generate_hhis.sh
#!/bin/bash set -e # Shell suggests [ -z foo ] || ... which is invalid syntax # shellcheck disable=SC2166 if [ -z "$1" -o -z "$2" -o -z "$3" -o -z "$4" ]; then echo "Usage: $0 HH_PARSE_EXECUTABLE SOURCE_DIR OUTPUT_DIR STAMP_FILE" exit 1 fi HH_PARSE="$1" SOURCE_DIR="${2%/}" OUTPUT_DIR="${3%/}" STAMP_FILE="$4" if [ -e "$OUTPUT_DIR" ]; then rm -rf "$OUTPUT_DIR" fi FILE_LIST=$(mktemp) find "$SOURCE_DIR" -type f -name '*.hack' -o -name '*.php' | while read -r FILE; do OUTPUT_FILE="$OUTPUT_DIR/${FILE#${SOURCE_DIR}}" OUTPUT_FILE="${OUTPUT_FILE/.php}" OUTPUT_FILE="${OUTPUT_FILE/.hack}" OUTPUT_FILE="${OUTPUT_FILE}.hhi" mkdir -p "$(dirname "$OUTPUT_FILE")" "$HH_PARSE" --generate-hhi "$FILE" > "$OUTPUT_FILE" echo "$OUTPUT_FILE" >> "$FILE_LIST" done mv "$FILE_LIST" "$STAMP_FILE"
OCaml
hhvm/hphp/hack/scripts/gen_build_id.ml
(* * Copyright (c) 2013-present, 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 "utils.ml" (** * Computes some build identifiers based on the current commit. These IDs are * used to ensure that clients and servers are the same version, even between * releases. For example, if you build revision A and start a server, then check * out and build revision B, it's convenient for the server to restart itself * using revision B. * * This fails gracefully when neither hg nor git are installed, or when neither * .hg nor .git exist (e.g. when building from a tarball). This is fine because * you can't move between commits in such a snapshot. *) let () = let out_file = Sys.argv.(1) in let rev = try read_process_output "git" [|"git"; "rev-parse"; "HEAD"|] with Failure _ -> try read_process_output "hg" [|"hg"; "id"; "-i"|] with Failure _ -> "" in let time = try read_process_output "git" [|"git"; "log"; "-1"; "--pretty=tformat:%ct"|] with Failure _ -> try let raw = read_process_output "hg" [|"hg"; "log"; "-r"; "."; "-T"; "{date|hgdate}\\n"|] in String.sub raw 0 (String.index raw ' ') with | Failure _ -> "0" | Not_found -> "0" in let content = Printf.sprintf "const char* const BuildInfo_kRevision = %S;\nconst unsigned long BuildInfo_kRevisionCommitTimeUnix = %sul;\nconst char* const BuildInfo_kBuildMode = %S;\n" rev time "" (* not implemented *) in let do_dump = not (Sys.file_exists out_file) || string_of_file out_file <> content in if do_dump then with_out_channel out_file @@ fun oc -> output_string oc content
OCaml
hhvm/hphp/hack/scripts/gen_index.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. * *) #use "scripts/utils.ml" let get_idx = let idx = ref 100 in fun () -> incr idx; !idx let rec iter rc dir = let files = Sys.readdir dir in let index_file = Filename.concat dir "INDEX" in let index = open_out index_file in Array.iter (fun name -> let idx = get_idx () in let file = Filename.concat dir name in if Sys.is_directory file then begin Printf.fprintf index "%d dir %s\n" idx name; let file, digest = iter rc file in Printf.fprintf rc "%d 256 %s // %s\n" idx file (Digest.to_hex digest) end else if name <> "INDEX" then begin let digest = Digest.file file in Printf.fprintf index "%d file %s\n" idx name; Printf.fprintf rc "%d 257 %s // %s\n" idx file (Digest.to_hex digest); end) files; close_out index; index_file, Digest.file index_file let () = let out_file = Sys.argv.(1) in let dir = Sys.argv.(2) in let temp_file = Filename.temp_file "hhi" ".rc" in let rc = open_out temp_file in let file, digest = iter rc dir in Printf.fprintf rc "100 256 %s // %s\n" file (Digest.to_hex digest); close_out rc; let do_copy = not (Sys.file_exists out_file) || string_of_file out_file <> string_of_file temp_file in if do_copy then begin if (Sys.file_exists out_file) then Sys.remove out_file; Sys.rename temp_file out_file end
Shell Script
hhvm/hphp/hack/scripts/invoke_cargo.sh
#!/bin/bash set -e HACK_SOURCE_ROOT="${HACK_SOURCE_ROOT:-$HACKDIR}" HACK_BUILD_ROOT="${HACK_BUILD_ROOT:-$HACKDIR}" if [ -z "$HACK_SOURCE_ROOT" ]; then echo >&2 "ERROR: must set HACK_SOURCE_ROOT to point to hphp/hack source dir" exit 1 fi if (( "$#" < 2 )); then echo "Usage: CARGO_BIN=path/to/cargo-bin $0 PACKAGE_NAME LIB_NAME" exit 2 fi pkg="$1" lib="$2" shift 2 while :; do case $1 in --target-dir) TARGET_DIR=$2 shift 2 ;; # Run binary --bin) bin=$2 shift 2 ;; # Build executable --exe) exe=$1 shift 1 ;; *) break esac done BUILD_PARAMS=() if [ -z "${HACK_NO_CARGO_VENDOR}" ]; then BUILD_PARAMS+=("--frozen") fi if [ -z "${TARGET_DIR}" ]; then TARGET_DIR="${HACK_BUILD_ROOT}/target" fi if [ -z ${HACKDEBUG+1} ]; then profile=release; profile_flags="--release" else profile=debug; profile_flags= fi BUILD_PARAMS+=(--quiet) BUILD_PARAMS+=(--target-dir "${TARGET_DIR}") BUILD_PARAMS+=(--package "$pkg") BUILD_PARAMS+=("$profile_flags") ( # add CARGO_BIN to PATH so that rustc and other tools can be invoked [[ -n "$CARGO_BIN" ]] && PATH="$CARGO_BIN:$PATH"; # note: --manifest-path doesn't work with custom toolchain, so do cd cd "$HACK_SOURCE_ROOT/src"; if [ -z "$bin" ]; then cargo build "${BUILD_PARAMS[@]}" else cargo run --bin "$bin" -- "$@" fi ) && if [ -z "$exe" ] && [ -z "$bin" ]; then cp "${TARGET_DIR}/$profile/lib$lib.a" "lib${lib}.a" fi
OCaml
hhvm/hphp/hack/scripts/utils.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. * *) let with_pipe f = let (fd_r, fd_w) = Unix.pipe () in try let res = f fd_r fd_w in Unix.close fd_r; Unix.close fd_w; res with exn -> Unix.close fd_r; Unix.close fd_w; raise exn let with_in_channel filename f = let ic = open_in_bin filename in try let res = f ic in close_in ic; res with exn -> close_in ic; raise exn let with_out_channel filename f = let oc = open_out_bin filename in try let res = f oc in close_out oc; res with exn -> close_out oc; raise exn (* Read the first line in stdout or stderr of an external command. *) let read_process_output name args = with_pipe @@ fun in_r _in_w -> with_pipe @@ fun out_r out_w -> let pid = try Unix.create_process name args in_r out_w out_w with | Unix.Unix_error (Unix.ENOENT, _, _) -> raise (Failure (name ^ ": command not found")) in match Unix.waitpid [] pid with | (_, Unix.WEXITED 0) -> input_line (Unix.in_channel_of_descr out_r) | (_, Unix.WEXITED 127) -> raise (Failure (name ^ ": command not found")) | (_, Unix.WEXITED 128) -> raise (Failure (input_line (Unix.in_channel_of_descr out_r))) | (_, Unix.WEXITED code) -> raise (Failure (name ^ ": exited code " ^ string_of_int code)) | (_, Unix.WSIGNALED signal) -> raise (Failure (name ^ ": killed by signal " ^ string_of_int signal)) | (_, Unix.WSTOPPED signal) -> raise (Failure (name ^ ": stopped by signal " ^ string_of_int signal)) let string_of_file filename = with_in_channel filename @@ fun ic -> let s = Bytes.create 32759 in let b = Buffer.create 1000 in let rec iter ic b s = let nread = input ic s 0 32759 in if nread > 0 then ( Buffer.add_subbytes b s 0 nread; iter ic b s ) in iter ic b s; Buffer.contents b
hhvm/hphp/hack/src/.ocp-indent
# -*- conf -*- # Starting the configuration file with a preset ensures you won't fallback to # definitions from "~/.ocp/ocp-indent.conf". # These are `normal`, `apprentice` and `JaneStreet` and set different defaults. normal # # INDENTATION VALUES # # Number of spaces used in all base cases, for example: # let foo = # ^^bar base = 2 # Indent for type definitions: # type t = # ^^int type = 2 # Indent after `let in` (unless followed by another `let`): # let foo = () in # ^^bar in = 0 # Indent after `match/try with` or `function`: # match foo with # ^^| _ -> bar with = 0 # Indent for clauses inside a pattern-match (after the arrow): # match foo with # | _ -> # ^^^^bar # the default is 2, which aligns the pattern and the expression match_clause = 2 # When nesting expressions on the same line, their indentation are in # some cases stacked, so that it remains correct if you close them one # at a line. This may lead to large indents in complex code though, so # this parameter can be used to set a maximum value. Note that it only # affects indentation after function arrows and opening parens at end # of line. # # for example (left: `none`; right: `4`) # let f = g (h (i (fun x -> # let f = g (h (i (fun x -> # x) # x) # ) # ) # ) # ) max_indent = 2 # # INDENTATION TOGGLES # # Whether the `with` parameter should be applied even when in a sub-block. # Can be `always`, `never` or `auto`. # if `always`, there are no exceptions # if `auto`, the `with` parameter is superseded when seen fit (most of the time, # but not after `begin match` for example) # if `never`, `with` is only applied if the match block starts a line. # # For example, the following is not indented if set to `always`: # let f = function # ^^| Foo -> bar strict_with = never # Controls indentation after the `else` keyword. `always` indents after the # `else` keyword normally, like after `then`. # If set to `never', the `else` keyword won't indent when followed by a newline. # `auto` indents after `else` unless in a few "unclosable" cases (`let in`, # `match`...). # # For example, with `strict_else=never`: # if cond then # foo # else # bar; # baz # `never` is discouraged if you may encounter code like this example, # because it hides the scoping error (`baz` is always executed) strict_else = auto # Ocp-indent will normally try to preserve your in-comment indentation, as long # as it respects the left-margin or starts with `(*\n`. Setting this to `true` # forces alignment within comments. strict_comments = false # Toggles preference of column-alignment over line indentation for most # of the common operators and after mid-line opening parentheses. # # for example (left: `false'; right: `true') # let f x = x # let f x = x # + y # + y align_ops = false # Function parameters are normally indented one level from the line containing # the function. This option can be used to have them align relative to the # column of the function body instead. # if set to `always`, always align below the function # if `auto`, only do that when seen fit (mainly, after arrows) # if `never`, no alignment whatsoever # # for example (left: `never`; right: `always or `auto) # match foo with # match foo with # | _ -> some_fun # | _ -> some_fun # ^^parameter # ^^parameter align_params = never # # SYNTAX EXTENSIONS # # You can also add syntax extensions (as per the --syntax command-line option): # syntax = mll
hhvm/hphp/hack/src/Cargo.lock
# This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "aast_parser" version = "0.0.0" dependencies = [ "bitflags 1.3.2", "bumpalo", "core_utils_rust", "decl_mode_parser", "hash", "hh_autoimport_rust", "lowerer", "mode_parser", "namespaces_rust", "naming_special_names_rust", "ocamlrep", "oxidized", "parser_core_types", "positioned_by_ref_parser", "rust_aast_parser_types", "rust_parser_errors", "smart_constructors", "stack_limit", ] [[package]] name = "aast_parser_ffi" version = "0.0.0" dependencies = [ "aast_parser", "ocamlrep", "ocamlrep_ocamlpool", "parser_core_types", ] [[package]] name = "addr2line" version = "0.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a76fd60b23679b7d19bd066031410fb7e458ccc5e958eb5c325888ce4baedc97" dependencies = [ "gimli", ] [[package]] name = "adler" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" [[package]] name = "ahash" version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fcb51a0695d8f838b1ee009b3fbf66bda078cd64590202a864a8f3e8c4315c47" dependencies = [ "getrandom", "once_cell", "version_check", ] [[package]] name = "ahash" version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2c99f64d1e06488f620f932677e24bc6e2897582980441ae90a671415bd7ec2f" dependencies = [ "cfg-if 1.0.0", "once_cell", "version_check", ] [[package]] name = "aho-corasick" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "43f6cb1bf222025340178f382c426f13757b2960e89779dfcb319c32542a5a41" dependencies = [ "memchr", ] [[package]] name = "allocator-api2" version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0942ffc6dcaadf03badf6e6a2d0228460359d5e34b57ccdc720b7382dfbd5ec5" [[package]] name = "analysis" version = "0.0.0" dependencies = [ "ir_core", "itertools 0.10.5", "newtype", "print", ] [[package]] name = "android-tzdata" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e999941b234f3131b00bc13c22d06e8c5ff726d1b6318ac7eb276997bbb4fef0" [[package]] name = "android_system_properties" version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" dependencies = [ "libc", ] [[package]] name = "anstream" version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ca84f3628370c59db74ee214b3263d58f9aadd9b4fe7e711fd87dc452b7f163" dependencies = [ "anstyle", "anstyle-parse", "anstyle-query", "anstyle-wincon", "colorchoice", "is-terminal", "utf8parse", ] [[package]] name = "anstyle" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "41ed9a86bf92ae6580e0a31281f65a1b1d867c0cc68d5346e2ae128dddfa6a7d" [[package]] name = "anstyle-parse" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e765fd216e48e067936442276d1d57399e37bce53c264d6fefbe298080cb57ee" dependencies = [ "utf8parse", ] [[package]] name = "anstyle-query" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5ca11d4be1bab0c8bc8734a9aa7bf4ee8316d462a08c6ac5052f888fef5b494b" dependencies = [ "windows-sys 0.48.0", ] [[package]] name = "anstyle-wincon" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "180abfa45703aebe0093f79badacc01b8fd4ea2e35118747e5811127f926e188" dependencies = [ "anstyle", "windows-sys 0.48.0", ] [[package]] name = "anyhow" version = "1.0.71" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c7d0618f0e0b7e8ff11427422b64564d5fb0be1940354bfe2e0529b18a9d9b8" [[package]] name = "arbitrary" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "237430fd6ed3740afe94eefcc278ae21e050285be882804e0d6e8695f0c94691" [[package]] name = "arc-swap" version = "0.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dabe5a181f83789739c194cbe5a897dde195078fac08568d09221fd6137a7ba8" [[package]] name = "archery" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0a8da9bc4c4053ee067669762bcaeea6e241841295a2b6c948312dad6ef4cc02" dependencies = [ "static_assertions", ] [[package]] name = "arena_collections" version = "0.0.0" dependencies = [ "arena_deserializer", "arena_trait", "bumpalo", "ocamlrep", "quickcheck", "serde", ] [[package]] name = "arena_deserializer" version = "0.0.0" dependencies = [ "bstr 1.6.0", "bumpalo", "ocamlrep_caml_builtins", "serde", ] [[package]] name = "arena_deserializer_tests" version = "0.0.0" dependencies = [ "arena_deserializer", "bincode", "bstr 1.6.0", "bumpalo", "oxidized_by_ref", "relative_path", "serde", "serde_json", ] [[package]] name = "arena_trait" version = "0.0.0" dependencies = [ "bumpalo", ] [[package]] name = "ascii" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbf56136a5198c7b01a49e3afcbef6cf84597273d298f54432926024107b0109" [[package]] name = "assemble" version = "0.0.0" dependencies = [ "anyhow", "assemble_opcode_macro", "bumpalo", "escaper", "ffi", "hash", "hhbc", "hhvm_types_ffi", "log", "naming_special_names_rust", "newtype", "parse_macro", "stack_depth", "strum", ] [[package]] name = "assemble_ir" version = "0.0.0" dependencies = [ "anyhow", "bstr 1.6.0", "bumpalo", "ffi", "hash", "ir_core", "itertools 0.10.5", "log", "naming_special_names_rust", "once_cell", "parse_macro_ir", ] [[package]] name = "assemble_opcode_macro" version = "0.0.0" dependencies = [ "hhbc-gen", "itertools 0.10.5", "proc-macro2", "quote", "syn 1.0.109", ] [[package]] name = "ast_and_decl_parser" version = "0.0.0" dependencies = [ "aast_parser", "bumpalo", "cst_and_decl_parser", "oxidized", "oxidized_by_ref", "parser_core_types", "rust_aast_parser_types", ] [[package]] name = "ast_scope" version = "0.0.0" dependencies = [ "bumpalo", "hhbc", "oxidized", ] [[package]] name = "async-io" version = "1.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fc5b45d93ef0529756f812ca52e44c221b35341892d3dcc34132ac02f3dd2af" dependencies = [ "async-lock", "autocfg", "cfg-if 1.0.0", "concurrent-queue", "futures-lite", "log", "parking", "polling", "rustix", "slab", "socket2", "waker-fn", ] [[package]] name = "async-lock" version = "2.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c8101efe8695a6c17e02911402145357e718ac92d3ff88ae8419e84b1707b685" dependencies = [ "event-listener", "futures-lite", ] [[package]] name = "atomic-polyfill" version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e14bf7b4f565e5e717d7a7a65b2a05c0b8c96e4db636d6f780f03b15108cdd1b" dependencies = [ "critical-section", ] [[package]] name = "atty" version = "0.2.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" dependencies = [ "hermit-abi 0.1.16", "libc", "winapi", ] [[package]] name = "autocfg" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" [[package]] name = "b2i_macros" version = "0.0.0" dependencies = [ "hhbc-gen", "proc-macro2", "quote", "syn 1.0.109", ] [[package]] name = "backtrace" version = "0.3.67" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "233d376d6d185f2a3093e58f283f60f880315b6c60075b01f36b3b85154564ca" dependencies = [ "addr2line", "cc", "cfg-if 1.0.0", "libc", "miniz_oxide 0.6.2", "object", "rustc-demangle", ] [[package]] name = "balanced_partition" version = "0.0.0" dependencies = [ "itertools 0.10.5", "log", "rayon", ] [[package]] name = "bare-metal" version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5deb64efa5bd81e31fcd1938615a6d98c82eafcbcd787162b6f63b91d6bac5b3" dependencies = [ "rustc_version 0.2.3", ] [[package]] name = "bare-metal" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fe8f5a8a398345e52358e18ff07cc17a568fbca5c6f73873d3a62056309603" [[package]] name = "base64" version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b25d992356d2eb0ed82172f5248873db5560c4721f564b13cb5193bda5e668e" dependencies = [ "byteorder", ] [[package]] name = "bc_to_ir" version = "0.0.0" dependencies = [ "b2i_macros", "bstr 1.6.0", "ffi", "hash", "hhbc", "ir", "itertools 0.10.5", "log", "maplit", "newtype", "once_cell", ] [[package]] name = "bench" version = "0.0.0" dependencies = [ "aast_parser", "ast_and_decl_parser", "bumpalo", "clap 4.3.11", "criterion", "cst_and_decl_parser", "direct_decl_parser", "parser_core_types", "relative_path", ] [[package]] name = "bincode" version = "1.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad" dependencies = [ "serde", ] [[package]] name = "bit_field" version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dcb6dd1c2376d2e096796e234a70e17e94cc2d5d54ff8ce42b28cef1d0d359a4" [[package]] name = "bitfield" version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "46afbd2983a5d5a7bd740ccb198caf5b82f45c40c09c0eed36052d91cb92e719" [[package]] name = "bitflags" version = "1.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" version = "2.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "630be753d4e58660abd17930c71b647fe46c27ea6b63cc59e1e3851406972e42" [[package]] name = "bitmaps" version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "031043d04099746d8db04daf1fa424b2bc8bd69d92b25962dcde24da39ab64a2" dependencies = [ "typenum", ] [[package]] name = "block-buffer" version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0bf7fe51849ea569fd452f37822f606a5cabb684dc918707a0193fd4664ff324" dependencies = [ "generic-array", ] [[package]] name = "bstr" version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba3569f383e8f1598449f1a423e72e99569137b47740b1da11ef19af3d5c3223" dependencies = [ "lazy_static", "memchr", "regex-automata 0.1.9", "serde", ] [[package]] name = "bstr" version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6798148dccfbff0fae41c7574d2fa8f1ef3492fba0face179de5d8d447d67b05" dependencies = [ "memchr", "regex-automata 0.3.5", "serde", ] [[package]] name = "bumpalo" version = "3.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "572f695136211188308f16ad2ca5c851a712c464060ae6974944458eb83880ba" [[package]] name = "byte-unit" version = "4.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "95ebf10dda65f19ff0f42ea15572a359ed60d7fc74fdc984d90310937be0014b" dependencies = [ "utf8-width", ] [[package]] name = "bytecode_printer" version = "0.0.0" dependencies = [ "anyhow", "bstr 1.6.0", "escaper", "ffi", "hash", "hhbc", "hhbc_string_utils", "hhvm_hhbc_defs_ffi", "hhvm_types_ffi", "itertools 0.10.5", "oxidized", "print_opcode", "relative_path", "thiserror", "write_bytes", ] [[package]] name = "bytecount" version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2c676a478f63e9fa2dd5368a42f28bba0d6c560b775f38583c8bbaa7fcd67c9c" [[package]] name = "bytemuck" version = "1.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aaa3a8d9a1ca92e282c96a32d6511b695d7d994d1d102ba85d279f9b2756947f" dependencies = [ "bytemuck_derive", ] [[package]] name = "bytemuck_derive" version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5fe233b960f12f8007e3db2d136e3cb1c291bfd7396e384ee76025fc1a3932b4" dependencies = [ "proc-macro2", "quote", "syn 1.0.109", ] [[package]] name = "byteorder" version = "1.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610" [[package]] name = "bytes" version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "89b2fd2a0dcf38d7971e2194b6b6eebab45ae01067456a7fd93d5547a61b70be" [[package]] name = "cactus" version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf034765b7d19a011c6d619e880582bf95e8186b580e6fab56589872dd87dcf5" [[package]] name = "cargo_metadata" version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8de60b887edf6d74370fc8eb177040da4847d971d6234c7b13a6da324ef0caf" dependencies = [ "semver 0.9.0", "serde", "serde_derive", "serde_json", ] [[package]] name = "cast" version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4b9434b9a5aa1450faa3f9cb14ea0e8c53bb5d2b3c1bfd1ab4fc03e9f33fbfb0" dependencies = [ "rustc_version 0.2.3", ] [[package]] name = "cbindgen" version = "0.22.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4d7ac49647ca72e4ecf4a1ca559dbc7fa43e2c5620dbd2cf198e6bf4671de6f2" dependencies = [ "clap 3.2.25", "heck", "indexmap", "log", "proc-macro2", "quote", "serde", "serde_json", "syn 1.0.109", "tempfile", "toml 0.5.11", ] [[package]] name = "cc" version = "1.0.79" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "50d30906286121d95be3d479533b458f87493b30a4b5f79a607db8f5d11aa91f" dependencies = [ "jobserver", ] [[package]] name = "cfg-if" version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "cfgrammar" version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bf74ea341ae8905eac9a234b6a5a845e118c25bbbdecf85ec77431a8b3bfa0be" dependencies = [ "indexmap", "lazy_static", "num-traits", "regex", "serde", "vob", ] [[package]] name = "chrono" version = "0.4.26" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec837a71355b28f6556dbd569b37b3f363091c0bd4b2e735674521b4c5fd9bc5" dependencies = [ "android-tzdata", "iana-time-zone", "js-sys", "num-traits", "serde", "time 0.1.44", "wasm-bindgen", "winapi", ] [[package]] name = "clap" version = "2.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a0610544180c38b88101fecf2dd634b174a62eef6946f84dfc6a7127512b381c" dependencies = [ "bitflags 1.3.2", "textwrap 0.11.0", "unicode-width", ] [[package]] name = "clap" version = "3.2.25" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4ea181bf566f71cb9a5d17a59e1871af638180a18fb0035c92ae62b705207123" dependencies = [ "atty", "bitflags 1.3.2", "clap_derive 3.2.25", "clap_lex 0.2.2", "indexmap", "once_cell", "regex", "strsim", "termcolor", "terminal_size 0.2.6", "textwrap 0.16.0", "unicase", ] [[package]] name = "clap" version = "4.3.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1640e5cc7fb47dbb8338fd471b105e7ed6c3cb2aeb00c2e067127ffd3764a05d" dependencies = [ "clap_builder", "clap_derive 4.3.2", "once_cell", ] [[package]] name = "clap_builder" version = "4.3.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "98c59138d527eeaf9b53f35a77fcc1fad9d883116070c63d5de1c7dc7b00c72b" dependencies = [ "anstream", "anstyle", "clap_lex 0.5.0", "strsim", "terminal_size 0.2.6", "unicase", "unicode-width", ] [[package]] name = "clap_derive" version = "3.2.25" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ae6371b8bdc8b7d3959e9cf7b22d4435ef3e79e138688421ec654acf8c81b008" dependencies = [ "heck", "proc-macro-error", "proc-macro2", "quote", "syn 1.0.109", ] [[package]] name = "clap_derive" version = "4.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8cd2b2a819ad6eec39e8f1d6b53001af1e5469f8c177579cdaeb313115b825f" dependencies = [ "heck", "proc-macro2", "quote", "syn 2.0.27", ] [[package]] name = "clap_lex" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5538cd660450ebeb4234cfecf8f2284b844ffc4c50531e66d584ad5b91293613" dependencies = [ "os_str_bytes", ] [[package]] name = "clap_lex" version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2da6da31387c7e4ef160ffab6d5e7f00c42626fe39aea70a7b0f1773f7dd6c1b" [[package]] name = "closure_convert" version = "0.0.0" dependencies = [ "bumpalo", "env", "error", "global_state", "hack_macros", "hash", "hhbc", "hhbc_string_utils", "itertools 0.10.5", "naming_special_names_rust", "options", "oxidized", "stack_limit", "unique_id_builder", ] [[package]] name = "codespan-reporting" version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3538270d33cc669650c4b093848450d380def10c331d38c768e34cac80576e6e" dependencies = [ "termcolor", "unicode-width", ] [[package]] name = "colorchoice" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "acbf1af155f9b9ef647e42cdc158db4b64a1b61f743629225fde6f3e0be2a7c7" [[package]] name = "compile" version = "0.0.0" dependencies = [ "aast_parser", "anyhow", "bc_to_ir", "bstr 1.6.0", "bumpalo", "bytecode_printer", "clap 4.3.11", "decl_provider", "elab", "emit_unit", "env", "error", "hhbc", "ir", "ir_to_bc", "options", "oxidized", "parser_core_types", "print_expr", "profile_rust", "relative_path", "rewrite_program", "serde", "stack_limit", "thiserror", "types", ] [[package]] name = "compiler_ffi" version = "0.0.0" dependencies = [ "anyhow", "bincode", "bumpalo", "compile", "cxx", "cxx-build", "decl_provider", "direct_decl_parser", "facts", "hash", "hhbc", "itertools 0.10.5", "libc", "options", "parser_core_types", "relative_path", "serde_json", "sha1", "thiserror", ] [[package]] name = "concurrent-queue" version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bd7bef69dc86e3c610e4e7aed41035e2a7ed12e72dd7530f61327a6579a4390b" dependencies = [ "crossbeam-utils 0.8.14", ] [[package]] name = "config_file" version = "0.0.0" dependencies = [ "bstr 1.6.0", "lazy_static", "regex", "serde_json", "sha1", ] [[package]] name = "config_file_ffi" version = "0.0.0" dependencies = [ "config_file", "ocamlrep_custom", "ocamlrep_ocamlpool", ] [[package]] name = "console" version = "0.15.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c050367d967ced717c04b65d8c619d863ef9292ce0c5760028655a2fb298718c" dependencies = [ "encode_unicode", "lazy_static", "libc", "terminal_size 0.1.17", "unicode-width", "winapi", ] [[package]] name = "constant_folder" version = "0.0.0" dependencies = [ "ast_scope", "bumpalo", "env", "ffi", "hhbc", "hhbc_string_utils", "indexmap", "itertools 0.10.5", "naming_special_names_rust", "oxidized", "stack_limit", ] [[package]] name = "convert_case" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e" [[package]] name = "core-foundation-sys" version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5827cebf4670468b8772dd191856768aedcb1b0278a04f989f7766351917b9dc" [[package]] name = "core_utils_rust" version = "0.0.0" dependencies = [ "pretty_assertions", ] [[package]] name = "cortex-m" version = "0.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cd20d4ac4aa86f4f75f239d59e542ef67de87cce2c282818dc6e84155d3ea126" dependencies = [ "bare-metal 0.2.5", "bitfield", "embedded-hal", "volatile-register", ] [[package]] name = "cpufeatures" version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a17b76ff3a4162b0b27f354a0c87015ddad39d35f9c0c36607a3bdd175dde1f1" dependencies = [ "libc", ] [[package]] name = "crc32fast" version = "1.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b540bd8bc810d3885c6ea91e2018302f68baba2129ab3e88f32389ee9370880d" dependencies = [ "cfg-if 1.0.0", ] [[package]] name = "criterion" version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fc755679c12bda8e5523a71e4d654b6bf2e14bd838dfc48cde6559a05caf7d1" dependencies = [ "atty", "cast", "clap 2.34.0", "criterion-plot", "csv", "itertools 0.8.2", "lazy_static", "num-traits", "oorandom", "plotters", "rayon", "regex", "serde", "serde_derive", "serde_json", "tinytemplate", "walkdir", ] [[package]] name = "criterion-plot" version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e022feadec601fba1649cfa83586381a4ad31c6bf3a9ab7d408118b05dd9889d" dependencies = [ "cast", "itertools 0.9.0", ] [[package]] name = "critical-section" version = "0.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "95da181745b56d4bd339530ec393508910c909c784e8962d15d722bacf0bcbcd" dependencies = [ "bare-metal 1.0.0", "cfg-if 1.0.0", "cortex-m", "riscv", ] [[package]] name = "crossbeam" version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2801af0d36612ae591caa9568261fddce32ce6e08a7275ea334a06a4ad021a2c" dependencies = [ "cfg-if 1.0.0", "crossbeam-channel 0.5.8", "crossbeam-deque", "crossbeam-epoch", "crossbeam-queue", "crossbeam-utils 0.8.14", ] [[package]] name = "crossbeam-channel" version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c8ec7fcd21571dc78f96cc96243cab8d8f035247c3efd16c687be154c3fa9efa" dependencies = [ "crossbeam-utils 0.6.6", ] [[package]] name = "crossbeam-channel" version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b153fe7cbef478c567df0f972e02e6d736db11affe43dfc9c56a9374d1adfb87" dependencies = [ "crossbeam-utils 0.7.2", "maybe-uninit", ] [[package]] name = "crossbeam-channel" version = "0.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a33c2bf77f2df06183c3aa30d1e96c0695a313d4f9c453cc3762a6db39f99200" dependencies = [ "cfg-if 1.0.0", "crossbeam-utils 0.8.14", ] [[package]] name = "crossbeam-deque" version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "715e8152b692bba2d374b53d4875445368fdf21a94751410af607a5ac677d1fc" dependencies = [ "cfg-if 1.0.0", "crossbeam-epoch", "crossbeam-utils 0.8.14", ] [[package]] name = "crossbeam-epoch" version = "0.9.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "045ebe27666471bb549370b4b0b3e51b07f56325befa4284db65fc89c02511b1" dependencies = [ "autocfg", "cfg-if 1.0.0", "crossbeam-utils 0.8.14", "memoffset", "once_cell", "scopeguard", ] [[package]] name = "crossbeam-queue" version = "0.3.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d1cfb3ea8a53f37c40dea2c7bedcbd88bdfae54f5e2175d6ecaff1c988353add" dependencies = [ "cfg-if 1.0.0", "crossbeam-utils 0.8.14", ] [[package]] name = "crossbeam-utils" version = "0.6.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04973fa96e96579258a5091af6003abde64af786b860f18622b82e026cca60e6" dependencies = [ "cfg-if 0.1.10", "lazy_static", ] [[package]] name = "crossbeam-utils" version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3c7c73a2d1e9fc0886a08b93e98eb643461230d5f1925e4036204d5f2e261a8" dependencies = [ "autocfg", "cfg-if 0.1.10", "lazy_static", ] [[package]] name = "crossbeam-utils" version = "0.8.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4fb766fa798726286dbbb842f174001dab8abc7b627a1dd86e0b7222a95d929f" dependencies = [ "cfg-if 1.0.0", ] [[package]] name = "crypto-common" version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" dependencies = [ "generic-array", "typenum", ] [[package]] name = "cst_and_decl_parser" version = "0.0.0" dependencies = [ "bumpalo", "direct_decl_parser", "direct_decl_smart_constructors", "oxidized", "oxidized_by_ref", "pair_smart_constructors", "parser", "parser_core_types", "positioned_smart_constructors", ] [[package]] name = "csv" version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "00affe7f6ab566df61b4be3ce8cf16bc2576bca0963ceb0955e45d514bf9a279" dependencies = [ "bstr 0.2.17", "csv-core", "itoa 0.4.8", "ryu", "serde", ] [[package]] name = "csv-core" version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b2466559f260f48ad25fe6317b3c8dac77b5bdb5763ac7d9d6103530663bc90" dependencies = [ "memchr", ] [[package]] name = "custom_error_config_ffi" version = "0.0.0" dependencies = [ "ocamlrep_ocamlpool", "oxidized", ] [[package]] name = "cxx" version = "1.0.100" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e928d50d5858b744d1ea920b790641129c347a770d1530c3a85b77705a5ee031" dependencies = [ "cc", "cxxbridge-flags", "cxxbridge-macro", "link-cplusplus", ] [[package]] name = "cxx-build" version = "1.0.100" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8332ba63f8a8040ca479de693150129067304a3496674477fff6d0c372cc34ae" dependencies = [ "cc", "codespan-reporting", "once_cell", "proc-macro2", "quote", "scratch", "syn 2.0.27", ] [[package]] name = "cxxbridge-flags" version = "1.0.100" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5966a5a87b6e9bb342f5fab7170a93c77096efe199872afffc4b477cfeb86957" [[package]] name = "cxxbridge-macro" version = "1.0.100" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "81b2dab6991c7ab1572fea8cb049db819b1aeea1e2dac74c0869f244d9f21a7c" dependencies = [ "proc-macro2", "quote", "syn 2.0.27", ] [[package]] name = "dashmap" version = "5.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "907076dfda823b0b36d2a1bb5f90c96660a5bbcd7729e10727f07858f22c4edc" dependencies = [ "cfg-if 1.0.0", "hashbrown 0.12.3", "lock_api", "once_cell", "parking_lot_core", "rayon", "serde", ] [[package]] name = "datastore" version = "0.0.0" dependencies = [ "anyhow", "dashmap", "hash", "parking_lot", ] [[package]] name = "decl_enforceability" version = "0.0.0" dependencies = [ "oxidized", "pos", "special_names", "ty", ] [[package]] name = "decl_mode_parser" version = "0.0.0" dependencies = [ "bumpalo", "decl_mode_smart_constructors", "parser", ] [[package]] name = "decl_mode_smart_constructors" version = "0.0.0" dependencies = [ "bumpalo", "ocamlrep", "parser_core_types", "smart_constructors", "syntax_smart_constructors", ] [[package]] name = "decl_parser" version = "0.0.0" dependencies = [ "anyhow", "bumpalo", "direct_decl_parser", "file_provider", "names", "oxidized", "oxidized_by_ref", "pos", "ty", ] [[package]] name = "decl_provider" version = "0.0.0" dependencies = [ "arena_deserializer", "bincode", "bumpalo", "direct_decl_parser", "hash", "oxidized", "oxidized_by_ref", "parser_core_types", "sha1", "thiserror", ] [[package]] name = "decl_provider_rust" version = "0.0.0" dependencies = [ "oxidized_by_ref", ] [[package]] name = "delta_log" version = "0.0.0" dependencies = [ "env_logger 0.10.0", "once_cell", ] [[package]] name = "dep" version = "0.0.0" dependencies = [ "bytemuck", "ocamlrep", "serde", ] [[package]] name = "dep_graph_delta" version = "0.0.0" dependencies = [ "dep", "hash", "serde", ] [[package]] name = "depgraph_compress" version = "0.0.0" dependencies = [ "balanced_partition", "bytemuck", "depgraph_reader", "depgraph_writer", "hash", "log", "newtype", "rayon", "smallvec", "vint64", "zstd", ] [[package]] name = "depgraph_reader" version = "0.0.0" dependencies = [ "bytemuck", "dep", "memmap2", "rayon", "rpds", "static_assertions", "vint64", ] [[package]] name = "depgraph_writer" version = "0.0.0" dependencies = [ "bytemuck", "dep", "log", "newtype", ] [[package]] name = "deps_rust" version = "0.0.0" dependencies = [ "dep_graph_delta", "depgraph_reader", "hash", "ocamlrep", "ocamlrep_custom", "once_cell", "parking_lot", "rpds", ] [[package]] name = "deps_rust_ffi" version = "0.0.0" dependencies = [ "dep", "deps_rust", "hash", "ocamlrep", "ocamlrep_custom", "ocamlrep_ocamlpool", "rpds", "typing_deps_hash", ] [[package]] name = "derive_more" version = "0.99.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4fb810d30a7c1953f91334de7244731fc3f3c10d7fe163338a35b9f640960321" dependencies = [ "convert_case", "proc-macro2", "quote", "rustc_version 0.4.0", "syn 1.0.109", ] [[package]] name = "diff" version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0e25ea47919b1560c4e3b7fe0aaab9becf5b84a10325ddf7db0f0ba5e1026499" [[package]] name = "digest" version = "0.10.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8168378f4e5023e7218c89c891c0fd8ecdb5e5e4f18cb78f38cf245dd021e76f" dependencies = [ "block-buffer", "crypto-common", ] [[package]] name = "direct_decl_parser" version = "0.0.0" dependencies = [ "bumpalo", "direct_decl_smart_constructors", "mode_parser", "oxidized", "oxidized_by_ref", "parser", "parser_core_types", "relative_path", ] [[package]] name = "direct_decl_smart_constructors" version = "0.0.0" dependencies = [ "arena_collections", "bstr 1.6.0", "bumpalo", "escaper", "flatten_smart_constructors", "hash", "hh_autoimport_rust", "namespaces_rust", "naming_special_names_rust", "oxidized", "oxidized_by_ref", "parser_core_types", "smart_constructors", ] [[package]] name = "dirs-next" version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b98cf8ebf19c3d1b223e151f99a4f9f0690dca41414773390fc824184ac833e1" dependencies = [ "cfg-if 1.0.0", "dirs-sys-next", ] [[package]] name = "dirs-sys-next" version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4ebda144c4fe02d1f7ea1a7d9641b6fc6b580adcfa024ae48797ecdeb6825b4d" dependencies = [ "libc", "redox_users", "winapi", ] [[package]] name = "dump-opcodes" version = "0.0.0" dependencies = [ "anyhow", "clap 4.3.11", "emit_opcodes", "hhbc-gen", "quote", ] [[package]] name = "dump_saved_state_depgraph" version = "0.0.0" dependencies = [ "clap 4.3.11", "depgraph_reader", "indicatif", ] [[package]] name = "either" version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "90e5c1c8368803113bf0c9584fc495a58b86dc8a29edbf8fe877d21d9507e797" [[package]] name = "elab" version = "0.0.0" dependencies = [ "bitflags 1.3.2", "bstr 1.6.0", "core_utils_rust", "elaborate_namespaces_visitor", "file_info", "hack_macros", "hash", "itertools 0.10.5", "naming_special_names_rust", "oxidized", "relative_path", "vec1", ] [[package]] name = "elab_ffi" version = "0.0.0" dependencies = [ "elab", "ocamlrep_ocamlpool", "oxidized", "relative_path", ] [[package]] name = "elaborate_namespaces_visitor" version = "0.0.0" dependencies = [ "core_utils_rust", "hash", "lazy_static", "namespaces_rust", "naming_special_names_rust", "oxidized", ] [[package]] name = "embedded-hal" version = "0.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "35949884794ad573cf46071e41c9b60efb0cb311e3ca01f7af807af1debc66ff" dependencies = [ "nb 0.1.3", "void", ] [[package]] name = "emit_opcodes" version = "0.0.0" dependencies = [ "convert_case", "hhbc-gen", "macro_test_util", "opcode_test_data", "proc-macro2", "quote", "syn 1.0.109", ] [[package]] name = "emit_opcodes_macro" version = "0.0.0" dependencies = [ "emit_opcodes", "hhbc-gen", ] [[package]] name = "emit_pos" version = "0.0.0" dependencies = [ "instruction_sequence", "oxidized", ] [[package]] name = "emit_type_hint" version = "0.0.0" dependencies = [ "bumpalo", "error", "ffi", "hhbc", "hhbc_string_utils", "hhvm_types_ffi", "naming_special_names_rust", "oxidized", ] [[package]] name = "emit_unit" version = "0.0.0" dependencies = [ "ast_scope", "bitflags 1.3.2", "bstr 1.6.0", "bumpalo", "constant_folder", "core_utils_rust", "decl_provider", "emit_pos", "emit_type_hint", "env", "error", "ffi", "hack_macros", "hash", "hhbc", "hhbc_string_utils", "hhvm_types_ffi", "indexmap", "instruction_sequence", "itertools 0.10.5", "label_rewriter", "lazy_static", "naming_special_names_rust", "options", "oxidized", "oxidized_by_ref", "print_expr", "regex", "scope", "serde_json", "stack_depth", "stack_limit", "statement_state", ] [[package]] name = "encode_unicode" version = "0.3.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a357d28ed41a50f9c765dbfe56cbc04a64e53e5fc58ba79fbc34c10ef3df831f" [[package]] name = "enum-iterator" version = "1.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7add3873b5dd076766ee79c8e406ad1a472c385476b9e38849f8eec24f1be689" dependencies = [ "enum-iterator-derive", ] [[package]] name = "enum-iterator-derive" version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eecf8589574ce9b895052fa12d69af7a233f99e6107f5cb8dd1044f2a17bfdcb" dependencies = [ "proc-macro2", "quote", "syn 2.0.27", ] [[package]] name = "env" version = "0.0.0" dependencies = [ "ast_scope", "bitflags 1.3.2", "bumpalo", "decl_provider", "ffi", "global_state", "hash", "hhbc", "hhbc_string_utils", "indexmap", "instruction_sequence", "naming_special_names_rust", "options", "oxidized", "print_expr", "relative_path", "statement_state", ] [[package]] name = "env_logger" version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a19187fea3ac7e84da7dacf48de0c45d63c6a76f9490dae389aead16c243fce3" dependencies = [ "log", "regex", ] [[package]] name = "env_logger" version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "85cdab6a89accf66733ad5a1693a4dcced6aeff64602b634530dd73c1f3ee9f0" dependencies = [ "humantime", "is-terminal", "log", "regex", "termcolor", ] [[package]] name = "eq_modulo_pos" version = "0.0.0" dependencies = [ "arena_collections", "bstr 1.6.0", "eq_modulo_pos_derive", "hcons", "indexmap", "ocamlrep_caml_builtins", ] [[package]] name = "eq_modulo_pos_derive" version = "0.0.0" dependencies = [ "proc-macro2", "quote", "synstructure", ] [[package]] name = "erased-serde" version = "0.3.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f94c0e13118e7d7533271f754a168ae8400e6a1cc043f2bfd53cc7290f1a1de3" dependencies = [ "serde", ] [[package]] name = "errno" version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4bcfec3a70f97c962c307b2d2c56e358cf1d00b558d74262b5f929ee8cc7e73a" dependencies = [ "errno-dragonfly", "libc", "windows-sys 0.48.0", ] [[package]] name = "errno-dragonfly" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "14ca354e36190500e1e1fb267c647932382b54053c50b14970856c0b00a35067" dependencies = [ "gcc", "libc", ] [[package]] name = "error" version = "0.0.0" dependencies = [ "hhvm_hhbc_defs_ffi", "oxidized", "thiserror", ] [[package]] name = "error-chain" version = "0.12.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2d2f06b9cac1506ece98fe3231e3cc9c4410ec3d5b1f24ae1c8946f0742cdefc" dependencies = [ "version_check", ] [[package]] name = "escaper" version = "0.0.0" dependencies = [ "bstr 1.6.0", "bumpalo", "pretty_assertions", ] [[package]] name = "event-listener" version = "2.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0" [[package]] name = "facts" version = "0.0.0" dependencies = [ "digest", "hex", "hhbc_string_utils", "naming_special_names_rust", "oxidized_by_ref", "pretty_assertions", "serde", "serde_derive", "serde_json", "sha1", ] [[package]] name = "facts_rust" version = "0.0.0" dependencies = [ "hhbc_string_utils", "oxidized_by_ref", "pretty_assertions", "serde", "serde_derive", "serde_json", ] [[package]] name = "fallible-iterator" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4443176a9f2c162692bd3d352d745ef9413eec5782a80d8fd6f8a1ac692a07f7" [[package]] name = "fallible-streaming-iterator" version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" [[package]] name = "fastrand" version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e51093e27b0797c359783294ca4f0a911c270184cb10f85783b118614a1501be" dependencies = [ "instant", ] [[package]] name = "ffi" version = "0.0.0" dependencies = [ "bstr 1.6.0", "bumpalo", "serde", "write_bytes", ] [[package]] name = "ffi_cbindgen" version = "0.0.0" dependencies = [ "anyhow", "cbindgen", "clap 3.2.25", ] [[package]] name = "file_info" version = "0.0.0" dependencies = [ "arena_deserializer", "arena_trait", "eq_modulo_pos", "naming_types", "no_pos_hash", "ocamlrep", "ocamlrep_caml_builtins", "parser_core_types", "rc_pos", "relative_path", "rusqlite", "serde", "thiserror", "typing_deps_hash", ] [[package]] name = "file_provider" version = "0.0.0" dependencies = [ "anyhow", "bstr 1.6.0", "pos", "tempdir", ] [[package]] name = "files_to_ignore" version = "0.0.0" dependencies = [ "regex", ] [[package]] name = "filetime" version = "0.2.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ed85775dcc68644b5c950ac06a2b23768d3bc9390464151aaf27136998dcf9e" dependencies = [ "cfg-if 0.1.10", "libc", "redox_syscall 0.1.57", "winapi", ] [[package]] name = "find_utils" version = "0.0.0" dependencies = [ "anyhow", "files_to_ignore", "jwalk", "pretty_assertions", "relative_path", ] [[package]] name = "flate2" version = "1.0.26" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3b9429470923de8e8cbd4d2dc513535400b4b3fef0319fb5c4e1f520a7bef743" dependencies = [ "crc32fast", "miniz_oxide 0.7.1", ] [[package]] name = "flatten_smart_constructors" version = "0.0.0" dependencies = [ "parser_core_types", "smart_constructors", ] [[package]] name = "fnv" version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" [[package]] name = "folded_decl_provider" version = "0.0.0" dependencies = [ "anyhow", "datastore", "decl_enforceability", "eq_modulo_pos", "hash", "indexmap", "itertools 0.10.5", "oxidized", "pos", "shallow_decl_provider", "special_names", "thiserror", "ty", ] [[package]] name = "fs2" version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9564fc758e15025b46aa6643b1b77d047d1a56a1aea6e01002ac0c7026876213" dependencies = [ "libc", "winapi", ] [[package]] name = "fuchsia-cprng" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" [[package]] name = "full_fidelity_schema_version_number" version = "0.0.0" [[package]] name = "futures-core" version = "0.3.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4bca583b7e26f571124fe5b7561d49cb2868d79116cfa0eefce955557c6fee8c" [[package]] name = "futures-io" version = "0.3.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4fff74096e71ed47f8e023204cfd0aa1289cd54ae5430a9523be060cdb849964" [[package]] name = "futures-lite" version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7694489acd39452c77daa48516b894c153f192c3578d5a839b62c58099fcbf48" dependencies = [ "fastrand", "futures-core", "futures-io", "memchr", "parking", "pin-project-lite", "waker-fn", ] [[package]] name = "futures-macro" version = "0.3.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "89ca545a94061b6365f2c7355b4b32bd20df3ff95f02da9329b34ccc3bd6ee72" dependencies = [ "proc-macro2", "quote", "syn 2.0.27", ] [[package]] name = "futures-task" version = "0.3.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "76d3d132be6c0e6aa1534069c705a74a5997a356c0dc2f86a47765e5617c5b65" [[package]] name = "futures-util" version = "0.3.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "26b01e40b772d54cf6c6d721c1d1abd0647a0106a12ecaa1c186273392a69533" dependencies = [ "futures-core", "futures-macro", "futures-task", "pin-project-lite", "pin-utils", "slab", ] [[package]] name = "gcc" version = "0.3.55" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f5f3913fa0bfe7ee1fd8248b6b9f42a5af4b9d65ec2dd2c3c26132b950ecfc2" [[package]] name = "gen_hhi_contents_lib" version = "0.0.0" [[package]] name = "generate_hhi_lib" version = "0.0.0" dependencies = [ "anyhow", "parser_core_types", "positioned_parser", "relative_path", ] [[package]] name = "generic-array" version = "0.14.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fd48d33ec7f05fbfa152300fdad764757cbded343c1aa1cff2fbaf4134851803" dependencies = [ "typenum", "version_check", ] [[package]] name = "getopts" version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "14dbbfd5c71d70241ecf9e6f13737f7b5ce823821063188d7e46c41d371eebd5" dependencies = [ "unicode-width", ] [[package]] name = "getrandom" version = "0.2.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c05aeb6a22b8f62540c194aac980f2115af067bfe15a0734d7277a768d396b31" dependencies = [ "cfg-if 1.0.0", "libc", "wasi 0.11.0+wasi-snapshot-preview1", ] [[package]] name = "getset" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24b328c01a4d71d2d8173daa93562a73ab0fe85616876f02500f53d82948c504" dependencies = [ "proc-macro-error", "proc-macro2", "quote", "syn 1.0.109", ] [[package]] name = "gimli" version = "0.27.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ad0a93d233ebf96623465aad4046a8d3aa4da22d4f4beba5388838c8a434bbb4" [[package]] name = "glob" version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b919933a397b79c37e33b77bb2aa3dc8eb6e165ad809e58ff75bc7db2e34574" [[package]] name = "global_state" version = "0.0.0" dependencies = [ "hhbc", "oxidized", "unique_id_builder", ] [[package]] name = "hack_macros" version = "0.0.0" dependencies = [ "hack_macros_impl", "oxidized", ] [[package]] name = "hack_macros_impl" version = "0.0.0" dependencies = [ "aast_parser", "macro_test_util", "once_cell", "oxidized", "parser_core_types", "proc-macro2", "quote", "regex", "relative_path", "rust_parser_errors", "serde", "syn 1.0.109", "thiserror", ] [[package]] name = "hackc" version = "0.0.0" dependencies = [ "aast_parser", "anyhow", "assemble", "bc_to_ir", "bumpalo", "byte-unit", "bytecode_printer", "clap 4.3.11", "compile", "decl_parser", "decl_provider", "direct_decl_parser", "elab", "env_logger 0.10.0", "facts", "ffi", "file_provider", "hackrs_test_utils", "hash", "hdrhistogram", "hhbc", "hhi", "hhvm_config", "hhvm_options", "hhvm_types_ffi", "ir", "ir_to_bc", "itertools 0.10.5", "jwalk", "log", "multifile_rust", "naming_provider", "naming_special_names_rust", "once_cell", "options", "oxidized", "panic-message", "parking_lot", "parser_core_types", "pos", "positioned_by_ref_parser", "positioned_full_trivia_parser", "positioned_parser", "profile_rust", "rayon", "regex", "relative_path", "sem_diff", "serde_json", "shallow_decl_provider", "strum", "tempdir", "textual", "thiserror", "tracing", "ty", ] [[package]] name = "hackrs_provider_backend" version = "0.0.0" dependencies = [ "anyhow", "bstr 1.6.0", "bumpalo", "datastore", "decl_parser", "deps_rust", "file_info", "file_provider", "folded_decl_provider", "hh24_test", "hh24_types", "libc", "maplit", "names", "naming_provider", "ocaml_runtime", "ocamlrep", "ocamlrep_caml_builtins", "ocamlrep_ocamlpool", "oxidized", "oxidized_by_ref", "parking_lot", "pos", "rpds", "rust_provider_backend_api", "serde", "shallow_decl_provider", "shm_store", "shmffi", "ty", ] [[package]] name = "hackrs_test_utils" version = "0.0.0" dependencies = [ "anyhow", "bincode", "datastore", "decl_parser", "folded_decl_provider", "hash", "indicatif", "intern", "lz4", "moka", "naming_provider", "oxidized", "pos", "rayon", "serde", "shallow_decl_provider", "ty", "zstd", ] [[package]] name = "hash" version = "0.0.0" dependencies = [ "dashmap", "indexmap", "rustc-hash", ] [[package]] name = "hash32" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b0c35f58762feb77d74ebe43bdbc3210f09be9fe6742234d573bacc26ed92b67" dependencies = [ "byteorder", ] [[package]] name = "hashbrown" version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" dependencies = [ "ahash 0.7.6", "serde", ] [[package]] name = "hashbrown" version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "43a3c133739dddd0d2990f9a4bdf8eb4b21ef50e4851ca85ab661199821d510e" dependencies = [ "ahash 0.8.3", ] [[package]] name = "hashbrown" version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2c6201b9ff9fd90a5a3bac2e56a830d0caa509576f0e503818ee82c181b3437a" dependencies = [ "ahash 0.8.3", "allocator-api2", ] [[package]] name = "hashlink" version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "312f66718a2d7789ffef4f4b7b213138ed9f1eb3aa1d0d82fc99f88fb3ffd26f" dependencies = [ "hashbrown 0.14.0", ] [[package]] name = "hcons" version = "0.0.0" dependencies = [ "dashmap", "fnv", "ocamlrep", "once_cell", "serde", ] [[package]] name = "hdf" version = "0.0.0" dependencies = [ "cc", "cxx", "cxx-build", "glob", "thiserror", ] [[package]] name = "hdrhistogram" version = "6.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "08d331ebcdbca4acbefe5da8c3299b2e246f198a8294cc5163354e743398b89d" dependencies = [ "base64", "byteorder", "crossbeam-channel 0.3.9", "flate2", "nom", "num-traits", ] [[package]] name = "heapless" version = "0.7.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f6733da246dc2af610133c8be0667170fd68e8ca5630936b520300eee8846f9" dependencies = [ "atomic-polyfill", "hash32", "rustc_version 0.4.0", "spin", "stable_deref_trait", ] [[package]] name = "heck" version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" [[package]] name = "hermit-abi" version = "0.1.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4c30f6d0bc6b00693347368a67d41b58f2fb851215ff1da49e90fe2c5c667151" dependencies = [ "libc", ] [[package]] name = "hermit-abi" version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "443144c8cdadd93ebf52ddb4056d257f5b52c04d3c804e657d19eb73fc33668b" [[package]] name = "hex" version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" [[package]] name = "hh24_test" version = "0.0.0" dependencies = [ "anyhow", "bumpalo", "direct_decl_parser", "hh24_types", "maplit", "names", "oxidized_by_ref", "relative_path", "tempdir", ] [[package]] name = "hh24_types" version = "0.0.0" dependencies = [ "anyhow", "derive_more", "file_info", "hh_hash", "relative_path", "rusqlite", "serde", "serde_json", "thiserror", "typing_deps_hash", ] [[package]] name = "hh_autoimport_rust" version = "0.0.0" dependencies = [ "lazy_static", ] [[package]] name = "hh_codegen" version = "0.0.0" dependencies = [ "anyhow", "clap 4.3.11", "hash", "proc-macro2", "quote", "signed_source", "syn 1.0.109", "synstructure", ] [[package]] name = "hh_config" version = "0.0.0" dependencies = [ "anyhow", "config_file", "oxidized", "serde", "serde_json", "sha1", ] [[package]] name = "hh_fanout_build" version = "0.0.0" dependencies = [ "bytemuck", "dashmap", "dep_graph_delta", "depgraph_compress", "depgraph_reader", "depgraph_writer", "hash", "libc", "log", "memmap2", "newtype", "parking_lot", "rayon", "smallvec", ] [[package]] name = "hh_fanout_build_rust" version = "0.0.0" dependencies = [ "delta_log", "env_logger 0.10.0", "hh_fanout_build", "ocamlrep_ocamlpool", ] [[package]] name = "hh_fanout_dep_graph_is_subgraph_rust" version = "0.0.0" dependencies = [ "depgraph_reader", "env_logger 0.10.0", "log", "ocamlrep_ocamlpool", ] [[package]] name = "hh_fanout_dep_graph_stats_rust" version = "0.0.0" dependencies = [ "depgraph_reader", "env_logger 0.10.0", "json", "log", "ocamlrep_ocamlpool", ] [[package]] name = "hh_fanout_rust_ffi" version = "0.0.0" dependencies = [ "dep", "hh24_types", "ocamlrep_custom", "ocamlrep_ocamlpool", ] [[package]] name = "hh_hash" version = "0.0.0" dependencies = [ "fnv", "no_pos_hash", ] [[package]] name = "hh_slog" version = "0.0.0" dependencies = [ "chrono", "locked_file_drain", "slog", "slog-async", "slog-envlogger", "slog-term", ] [[package]] name = "hhbc" version = "0.0.0" dependencies = [ "bitflags 1.3.2", "bstr 1.6.0", "bumpalo", "emit_opcodes_macro", "ffi", "hash", "hhbc_string_utils", "hhvm_hhbc_defs_ffi", "hhvm_types_ffi", "naming_special_names_rust", "oxidized", "relative_path", "serde", "write_bytes", ] [[package]] name = "hhbc-gen" version = "0.0.0" dependencies = [ "anyhow", "bitflags 1.3.2", "cc", "maplit", "once_cell", ] [[package]] name = "hhbc_string_utils" version = "0.0.0" dependencies = [ "bstr 1.6.0", "escaper", "lazy_static", "libc", "naming_special_names_rust", "ocaml_helper", "pretty_assertions", "regex", ] [[package]] name = "hhi" version = "0.0.0" dependencies = [ "clap 3.2.25", "gen_hhi_contents_lib", "generate_hhi_lib", "walkdir", ] [[package]] name = "hhvm_config" version = "0.0.0" dependencies = [ "anyhow", "hhvm_options", "options", ] [[package]] name = "hhvm_hhbc_defs_ffi" version = "0.0.0" dependencies = [ "cxx", "cxx-build", "serde", ] [[package]] name = "hhvm_options" version = "0.0.0" dependencies = [ "anyhow", "clap 4.3.11", "hdf", "hhvm_runtime_options", ] [[package]] name = "hhvm_runtime_options" version = "0.0.0" dependencies = [ "anyhow", "cxx", "cxx-build", "hdf", "log", ] [[package]] name = "hhvm_types_ffi" version = "0.0.0" dependencies = [ "cxx", "cxx-build", "oxidized", "serde", ] [[package]] name = "html_entities" version = "0.0.0" dependencies = [ "lazy_static", "ocaml_helper", "pretty_assertions", "regex", ] [[package]] name = "humantime" version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4" [[package]] name = "iana-time-zone" version = "0.1.53" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "64c122667b287044802d6ce17ee2ddf13207ed924c712de9a66a5814d5b64765" dependencies = [ "android_system_properties", "core-foundation-sys", "iana-time-zone-haiku", "js-sys", "wasm-bindgen", "winapi", ] [[package]] name = "iana-time-zone-haiku" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0703ae284fc167426161c2e3f1da3ea71d94b21bedbcc9494e92b28e334e3dca" dependencies = [ "cxx", "cxx-build", ] [[package]] name = "im" version = "15.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d0acd33ff0285af998aaf9b57342af478078f53492322fafc47450e09397e0e9" dependencies = [ "bitmaps", "rand_core 0.6.4", "rand_xoshiro", "rayon", "serde", "sized-chunks", "typenum", "version_check", ] [[package]] name = "indexmap" version = "1.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1885e79c1fc4b10f0e172c475f458b7f7b93061064d98c3293e98c5ba0c8b399" dependencies = [ "arbitrary", "autocfg", "hashbrown 0.12.3", "rayon", "serde", ] [[package]] name = "indicatif" version = "0.17.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cef509aa9bc73864d6756f0d34d35504af3cf0844373afe9b8669a5b8005a729" dependencies = [ "console", "number_prefix", "portable-atomic", "rayon", "tokio", "unicode-segmentation", "unicode-width", ] [[package]] name = "instant" version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c" dependencies = [ "cfg-if 1.0.0", ] [[package]] name = "instruction_sequence" version = "0.0.0" dependencies = [ "bumpalo", "emit_opcodes_macro", "ffi", "hhbc", "pretty_assertions", ] [[package]] name = "intern" version = "0.1.0" dependencies = [ "bincode", "fnv", "hashbrown 0.12.3", "indexmap", "once_cell", "parking_lot", "rand 0.8.5", "serde", "serde_bytes", "serde_derive", "serde_json", "smallvec", ] [[package]] name = "io-lifetimes" version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c66c74d2ae7e79a5a8f7ac924adbe38ee42a859c6539ad869eb51f0b52dc220" dependencies = [ "hermit-abi 0.3.2", "libc", "windows-sys 0.48.0", ] [[package]] name = "ir" version = "0.0.0" dependencies = [ "analysis", "assemble_ir", "ir_core", "passes", "print", "testutils", "verify", ] [[package]] name = "ir_core" version = "0.0.0" dependencies = [ "bstr 1.6.0", "ffi", "hash", "hhbc", "hhvm_types_ffi", "indexmap", "macros", "naming_special_names_rust", "newtype", "parking_lot", "smallvec", "static_assertions", "strum", ] [[package]] name = "ir_to_bc" version = "0.0.0" dependencies = [ "bumpalo", "dashmap", "ffi", "hash", "hhbc", "instruction_sequence", "ir", "itertools 0.10.5", "log", "smallvec", "stack_depth", ] [[package]] name = "is-terminal" version = "0.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "adcf93614601c8129ddf72e2d5633df827ba6551541c6d8c59520a371475be1f" dependencies = [ "hermit-abi 0.3.2", "io-lifetimes", "rustix", "windows-sys 0.48.0", ] [[package]] name = "itertools" version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f56a2d0bc861f9165be4eb3442afd3c236d8a98afd426f65d92324ae1091a484" dependencies = [ "either", ] [[package]] name = "itertools" version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "284f18f85651fe11e8a991b2adb42cb078325c996ed026d994719efcfca1d54b" dependencies = [ "either", ] [[package]] name = "itertools" version = "0.10.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473" dependencies = [ "either", ] [[package]] name = "itoa" version = "0.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b71991ff56294aa922b450139ee08b3bfc70982c6b2c7562771375cf73542dd4" [[package]] name = "itoa" version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fad582f4b9e86b6caa621cabeb0963332d92eea04729ab12892c2533951e6440" [[package]] name = "jobserver" version = "0.1.24" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "af25a77299a7f711a01975c35a6a424eb6862092cc2d6c72c4ed6cbc56dfc1fa" dependencies = [ "libc", ] [[package]] name = "js-sys" version = "0.3.59" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "258451ab10b34f8af53416d1fdab72c22e805f0c92a1136d59470ec0b11138b2" dependencies = [ "wasm-bindgen", ] [[package]] name = "json" version = "0.12.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "078e285eafdfb6c4b434e0d31e8cfcb5115b651496faca5749b88fafd4f23bfd" [[package]] name = "jwalk" version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "172752e853a067cbce46427de8470ddf308af7fd8ceaf9b682ef31a5021b6bb9" dependencies = [ "crossbeam", "rayon", ] [[package]] name = "label_rewriter" version = "0.0.0" dependencies = [ "bumpalo", "env", "ffi", "hash", "hhbc", "instruction_sequence", "oxidized", ] [[package]] name = "lazy_static" version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" [[package]] name = "libc" version = "0.2.147" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4668fb0ea861c1df094127ac5f1da3409a82116a4ba74fca2e58ef927159bb3" [[package]] name = "libsqlite3-sys" version = "0.26.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "afc22eff61b133b115c6e8c74e818c628d6d5e7a502afea6f64dee076dd94326" dependencies = [ "pkg-config", "vcpkg", ] [[package]] name = "line_break_map" version = "0.0.0" [[package]] name = "line_break_map_tests" version = "0.0.0" dependencies = [ "line_break_map", "ocamlrep_ocamlpool", ] [[package]] name = "link-cplusplus" version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9d240c6f7e1ba3a28b0249f774e6a9dd0175054b52dfbb61b16eb8505c3785c9" dependencies = [ "cc", ] [[package]] name = "lint_rust" version = "0.0.0" dependencies = [ "arena_deserializer", "arena_trait", "no_pos_hash", "ocamlrep", "oxidized", "rc_pos", "serde", ] [[package]] name = "linux-raw-sys" version = "0.3.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ece97ea872ece730aed82664c424eb4c8291e1ff2480247ccf7409044bc6479f" [[package]] name = "lock_api" version = "0.4.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "435011366fe56583b16cf956f9df0095b405b82d76425bc8981c0e22e60ec4df" dependencies = [ "autocfg", "scopeguard", ] [[package]] name = "locked_file_drain" version = "0.0.0" dependencies = [ "fs2", "serde_json", "slog", "slog-json", "tempfile", ] [[package]] name = "log" version = "0.4.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "518ef76f2f87365916b142844c16d8fefd85039bc5699050210a7778ee1cd1de" dependencies = [ "value-bag", ] [[package]] name = "lowerer" version = "0.0.0" dependencies = [ "bstr 1.6.0", "bumpalo", "escaper", "hash", "html_entities", "itertools 0.10.5", "lazy_static", "lint_rust", "naming_special_names_rust", "ocaml_helper", "oxidized", "parser_core_types", "regex", "relative_path", "rescan_trivia", "stack_limit", "thiserror", ] [[package]] name = "lrgen" version = "0.0.0" dependencies = [ "cfgrammar", "clap 3.2.25", "lrlex", ] [[package]] name = "lrlex" version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "22b832738fbfa58ad036580929e973b3b6bd31c6d6c7f18f6b5ea7b626675c85" dependencies = [ "getopts", "lazy_static", "lrpar", "num-traits", "regex", "serde", "try_from", "vergen", ] [[package]] name = "lrpar" version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2f270b952b07995fe874b10a5ed7dd28c80aa2130e37a7de7ed667d034e0a521" dependencies = [ "bincode", "cactus", "cfgrammar", "filetime", "indexmap", "lazy_static", "lrtable", "num-traits", "packedvec", "regex", "serde", "static_assertions", "vergen", "vob", ] [[package]] name = "lrtable" version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a854115c6a10772ac154261592b082436abc869c812575cadcf9d7ceda8eff0b" dependencies = [ "cfgrammar", "fnv", "num-traits", "serde", "sparsevec", "static_assertions", "vob", ] [[package]] name = "lru" version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "03f1160296536f10c833a82dca22267d5486734230d47bf00bf435885814ba1e" dependencies = [ "hashbrown 0.13.2", ] [[package]] name = "lz4" version = "1.24.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7e9e2dd86df36ce760a60f6ff6ad526f7ba1f14ba0356f8254fb6905e6494df1" dependencies = [ "libc", "lz4-sys", ] [[package]] name = "lz4-sys" version = "1.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "57d27b317e207b10f69f5e75494119e391a96f48861ae870d1da6edac98ca900" dependencies = [ "cc", "libc", ] [[package]] name = "mach" version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b823e83b2affd8f40a9ee8c29dbc56404c1e34cd2710921f2801e2cf29527afa" dependencies = [ "libc", ] [[package]] name = "macro_test_util" version = "0.0.0" dependencies = [ "proc-macro2", ] [[package]] name = "macros" version = "0.0.0" dependencies = [ "proc-macro2", "quote", "syn 1.0.109", ] [[package]] name = "maplit" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3e2e65a1a2e43cfcb47a895c4c8b10d1f4a61097f9f254f183aee60cad9c651d" [[package]] name = "maybe-uninit" version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "60302e4db3a61da70c0cb7991976248362f30319e88850c487b9b95bbf059e00" [[package]] name = "md-5" version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "658646b21e0b72f7866c7038ab086d3d5e1cd6271f060fd37defb241949d0582" dependencies = [ "digest", ] [[package]] name = "measure" version = "0.0.0" dependencies = [ "hash", "ocamlrep", "once_cell", "parking_lot", ] [[package]] name = "measure_ffi" version = "0.0.0" dependencies = [ "measure", "ocamlrep_ocamlpool", ] [[package]] name = "memchr" version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" [[package]] name = "memmap2" version = "0.5.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "83faa42c0a078c393f6b29d5db232d8be22776a891f8f56e5284faee4a20b327" dependencies = [ "libc", ] [[package]] name = "memoffset" version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5aa361d4faea93603064a027415f07bd8e1d5c88c9fbf68bf56a285428fd79ce" dependencies = [ "autocfg", ] [[package]] name = "miniz_oxide" version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b275950c28b37e794e8c55d88aeb5e139d0ce23fdbbeda68f8d7174abdf9e8fa" dependencies = [ "adler", ] [[package]] name = "miniz_oxide" version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7810e0be55b428ada41041c41f32c9f1a42817901b4ccf45fa3d4b6561e74c7" dependencies = [ "adler", ] [[package]] name = "mode_parser" version = "0.0.0" dependencies = [ "bumpalo", "parser_core_types", "positioned_by_ref_parser", ] [[package]] name = "moka" version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b6446f16d504e3d575df79cabb11bfbe9f24b17e9562d964a815db7b28ae3ec" dependencies = [ "async-io", "async-lock", "crossbeam-channel 0.5.8", "crossbeam-epoch", "crossbeam-utils 0.8.14", "futures-util", "num_cpus", "once_cell", "parking_lot", "quanta", "rustc_version 0.4.0", "scheduled-thread-pool", "skeptic", "smallvec", "tagptr", "thiserror", "triomphe", "uuid", ] [[package]] name = "multifile_rust" version = "0.0.0" dependencies = [ "anyhow", "lazy_static", "pretty_assertions", "regex", ] [[package]] name = "names" version = "0.0.0" dependencies = [ "anyhow", "crossbeam", "hh24_types", "oxidized", "oxidized_by_ref", "rand 0.8.5", "relative_path", "rusqlite", "serde", "typing_deps_hash", ] [[package]] name = "namespaces_rust" version = "0.0.0" dependencies = [ "bumpalo", "core_utils_rust", "naming_special_names_rust", "oxidized", "oxidized_by_ref", ] [[package]] name = "naming_attributes_rust" version = "0.0.0" dependencies = [ "oxidized", ] [[package]] name = "naming_provider" version = "0.0.0" dependencies = [ "anyhow", "hh24_types", "names", "oxidized", "parking_lot", "pos", ] [[package]] name = "naming_special_names_rust" version = "0.0.0" dependencies = [ "hash", "lazy_static", "serde", "write_bytes", ] [[package]] name = "naming_table_builder" version = "0.0.0" dependencies = [ "anyhow", "bumpalo", "clap 3.2.25", "direct_decl_parser", "files_to_ignore", "find_utils", "hh_config", "hh_slog", "hhi", "names", "oxidized", "oxidized_by_ref", "rayon", "relative_path", "si_addendum", "slog", "tempdir", ] [[package]] name = "naming_table_builder_ffi" version = "0.0.0" dependencies = [ "anyhow", "naming_table_builder", "ocamlrep_custom", "ocamlrep_ocamlpool", "oxidized", "relative_path", "unwrap_ocaml", ] [[package]] name = "naming_types" version = "0.0.0" dependencies = [ "arena_deserializer", "arena_trait", "eq_modulo_pos", "no_pos_hash", "ocamlrep", "serde", ] [[package]] name = "nb" version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "801d31da0513b6ec5214e9bf433a77966320625a37860f910be265be6e18d06f" dependencies = [ "nb 1.0.0", ] [[package]] name = "nb" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "546c37ac5d9e56f55e73b677106873d9d9f5190605e41a856503623648488cae" [[package]] name = "newtype" version = "0.0.0" dependencies = [ "serde", ] [[package]] name = "nix" version = "0.25.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e322c04a9e3440c327fca7b6c8a63e6890a32fa2ad689db972425f07e0d22abb" dependencies = [ "autocfg", "bitflags 1.3.2", "cfg-if 1.0.0", "libc", "memoffset", "pin-utils", ] [[package]] name = "no_pos_hash" version = "0.0.0" dependencies = [ "arena_collections", "bstr 1.6.0", "fnv", "no_pos_hash_derive", "ocamlrep_caml_builtins", ] [[package]] name = "no_pos_hash_derive" version = "0.0.0" dependencies = [ "proc-macro2", "quote", "syn 1.0.109", "synstructure", ] [[package]] name = "nohash-hasher" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" [[package]] name = "nom" version = "4.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c349f68f25f596b9f44cf0e7c69752a5c633b0550c3ff849518bfba0233774a" dependencies = [ "memchr", ] [[package]] name = "num-traits" version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "578ede34cf02f8924ab9447f50c28075b4d3e5b269972345e7e0372b38c6cdcd" dependencies = [ "autocfg", ] [[package]] name = "num_cpus" version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4161fcb6d602d4d2081af7c3a45852d875a03dd337a6bfdd6e06407b61342a43" dependencies = [ "hermit-abi 0.3.2", "libc", ] [[package]] name = "number_prefix" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "830b246a0e5f20af87141b25c173cd1b609bd7779a4617d6ec582abaf90870f3" [[package]] name = "object" version = "0.30.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ea86265d3d3dcb6a27fc51bd29a4bf387fae9d2986b823079d4986af253eb439" dependencies = [ "memchr", ] [[package]] name = "ocaml_blob" version = "0.0.0" dependencies = [ "libc", "lz4", "ocamlrep", "rand 0.8.5", "shmrs", ] [[package]] name = "ocaml_helper" version = "0.0.0" dependencies = [ "pretty_assertions", ] [[package]] name = "ocaml_runtime" version = "0.0.0" dependencies = [ "ocamlrep", ] [[package]] name = "ocamlrep" version = "0.1.0" dependencies = [ "bstr 1.6.0", "bumpalo", "indexmap", "ocamlrep_derive", "rustc-hash", "serde", ] [[package]] name = "ocamlrep_caml_builtins" version = "0.1.0" dependencies = [ "ocamlrep", "ocamlrep_custom", "serde", ] [[package]] name = "ocamlrep_custom" version = "0.1.0" dependencies = [ "ocamlrep", "ocamlrep_ocamlpool", ] [[package]] name = "ocamlrep_derive" version = "0.1.0" dependencies = [ "proc-macro2", "quote", "syn 1.0.109", "synstructure", ] [[package]] name = "ocamlrep_marshal" version = "0.1.0" dependencies = [ "bitflags 1.3.2", "cc", "ocamlrep", ] [[package]] name = "ocamlrep_marshal_ffi_bindings" version = "0.0.0" dependencies = [ "ocamlrep", "ocamlrep_marshal", "ocamlrep_ocamlpool", ] [[package]] name = "ocamlrep_ocamlpool" version = "0.1.0" dependencies = [ "bumpalo", "cc", "ocamlrep", ] [[package]] name = "once_cell" version = "1.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d" [[package]] name = "oorandom" version = "11.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ab1bc2a289d34bd04a330323ac98a1b4bc82c9d9fcb1e66b63caa84da26b575" [[package]] name = "opcode_test_data" version = "0.0.0" dependencies = [ "hhbc-gen", ] [[package]] name = "operator" version = "0.0.0" dependencies = [ "ocamlrep", "parser_core_types", ] [[package]] name = "options" version = "0.0.0" dependencies = [ "bstr 1.6.0", "hhbc_string_utils", "oxidized", "serde", ] [[package]] name = "os_str_bytes" version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e22443d1643a904602595ba1cd8f7d896afe56d26712531c5ff73a15b2fbf64" [[package]] name = "oxidized" version = "0.0.0" dependencies = [ "anyhow", "arena_deserializer", "arena_trait", "bitflags 1.3.2", "bstr 1.6.0", "bumpalo", "eq_modulo_pos", "file_info", "hash", "hh24_types", "hh_autoimport_rust", "hh_hash", "itertools 0.10.5", "naming_types", "no_pos_hash", "ocamlrep", "parser_core_types", "pretty_assertions", "rc_pos", "relative_path", "rust_to_ocaml_attr", "serde", "serde_json", "thiserror", ] [[package]] name = "oxidized_by_ref" version = "0.0.0" dependencies = [ "arena_collections", "arena_deserializer", "arena_trait", "bitflags 1.3.2", "bstr 1.6.0", "bumpalo", "eq_modulo_pos", "hh24_types", "hh_hash", "no_pos_hash", "ocamlrep", "ocamlrep_caml_builtins", "oxidized", "pretty_assertions", "relative_path", "rust_to_ocaml_attr", "serde", "serde_json", ] [[package]] name = "package" version = "0.0.0" dependencies = [ "anyhow", "hash", "once_cell", "serde", "toml 0.7.3", ] [[package]] name = "package_ffi" version = "0.0.0" dependencies = [ "cxx", "cxx-build", "package", ] [[package]] name = "package_ocaml_ffi" version = "0.0.0" dependencies = [ "ocamlrep", "ocamlrep_ocamlpool", "package", "rc_pos", "relative_path", "toml 0.7.3", ] [[package]] name = "packedvec" version = "1.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bde3c690ec20e4a2b4fb46f0289a451181eb50011a1e2acc8d85e2fde9062a45" dependencies = [ "num-traits", "serde", ] [[package]] name = "pair_smart_constructors" version = "0.0.0" dependencies = [ "parser_core_types", "smart_constructors", ] [[package]] name = "panic-message" version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "384e52fd8fbd4cbe3c317e8216260c21a0f9134de108cea8a4dd4e7e152c472d" [[package]] name = "parking" version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "427c3892f9e783d91cc128285287e70a59e206ca452770ece88a76f7a3eddd72" [[package]] name = "parking_lot" version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f" dependencies = [ "lock_api", "parking_lot_core", ] [[package]] name = "parking_lot_core" version = "0.9.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9069cbb9f99e3a5083476ccb29ceb1de18b9118cafa53e90c9551235de2b9521" dependencies = [ "cfg-if 1.0.0", "libc", "redox_syscall 0.2.10", "smallvec", "windows-sys 0.45.0", ] [[package]] name = "parse_macro" version = "0.0.0" dependencies = [ "proc-macro-error", "proc-macro2", "quote", ] [[package]] name = "parse_macro_ir" version = "0.0.0" dependencies = [ "macro_test_util", "proc-macro-error", "proc-macro2", "quote", ] [[package]] name = "parser" version = "0.0.0" dependencies = [ "heapless", "operator", "parser_core_types", "smart_constructors", "stack_limit", "static_assertions", ] [[package]] name = "parser_core_types" version = "0.0.0" dependencies = [ "bitflags 1.3.2", "bumpalo", "itertools 0.10.5", "line_break_map", "ocaml_helper", "ocamlrep", "relative_path", "serde", ] [[package]] name = "parser_ffi" version = "0.0.0" dependencies = [ "bumpalo", "cxx", "cxx-build", "parser_core_types", "positioned_full_trivia_parser", "relative_path", "serde_json", ] [[package]] name = "passes" version = "0.0.0" dependencies = [ "analysis", "ffi", "hash", "ir_core", "itertools 0.10.5", "log", "newtype", "print", "rand 0.8.5", "testutils", "verify", ] [[package]] name = "pest" version = "2.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f73935e4d55e2abf7f130186537b19e7a4abc886a0252380b59248af473a3fc9" dependencies = [ "thiserror", "ucd-trie", ] [[package]] name = "pin-project-lite" version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e0a7ae3ac2f1173085d398531c705756c94a4c56843785df85a60c1a0afac116" [[package]] name = "pin-utils" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" [[package]] name = "pkg-config" version = "0.3.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "26072860ba924cbfa98ea39c8c19b4dd6a4a25423dbdf219c1eca91aa0cf6964" [[package]] name = "plotters" version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d1685fbe7beba33de0330629da9d955ac75bd54f33d7b79f9a895590124f6bb" dependencies = [ "js-sys", "num-traits", "wasm-bindgen", "web-sys", ] [[package]] name = "polling" version = "2.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2a7bc6b2a29e632e45451c941832803a18cce6781db04de8a04696cdca8bde4" dependencies = [ "cfg-if 0.1.10", "libc", "log", "wepoll-sys", "winapi", ] [[package]] name = "portable-atomic" version = "0.3.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "26f6a7b87c2e435a3241addceeeff740ff8b7e76b74c13bf9acb17fa454ea00b" [[package]] name = "pos" version = "0.0.0" dependencies = [ "arena_trait", "bstr 1.6.0", "bumpalo", "eq_modulo_pos", "hh24_types", "im", "indexmap", "intern", "ocamlrep", "oxidized", "oxidized_by_ref", "relative_path", "serde", "static_assertions", ] [[package]] name = "positioned_by_ref_parser" version = "0.0.0" dependencies = [ "bumpalo", "parser", "positioned_smart_constructors", ] [[package]] name = "positioned_by_ref_parser_ffi" version = "0.0.0" dependencies = [ "ocamlrep", "ocamlrep_ocamlpool", "oxidized", "positioned_by_ref_parser", "rust_parser_ffi", ] [[package]] name = "positioned_full_trivia_parser" version = "0.0.0" dependencies = [ "bumpalo", "full_fidelity_schema_version_number", "parser", "positioned_smart_constructors", "serde", ] [[package]] name = "positioned_parser" version = "0.0.0" dependencies = [ "parser", "positioned_smart_constructors", ] [[package]] name = "positioned_smart_constructors" version = "0.0.0" dependencies = [ "parser_core_types", "smart_constructors", "syntax_smart_constructors", ] [[package]] name = "ppv-lite86" version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c36fa947111f5c62a733b652544dd0016a43ce89619538a8ef92724a6f501a20" [[package]] name = "pretty_assertions" version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "af7cee1a6c8a5b9208b3cb1061f10c0cb689087b3d8ce85fb9d2dd7a29b6ba66" dependencies = [ "diff", "yansi", ] [[package]] name = "print" version = "0.0.0" dependencies = [ "ffi", "ir_core", ] [[package]] name = "print_expr" version = "0.0.0" dependencies = [ "anyhow", "bstr 1.6.0", "bumpalo", "core_utils_rust", "emit_type_hint", "error", "escaper", "hhbc", "hhbc_string_utils", "lazy_static", "naming_special_names_rust", "oxidized", "regex", "thiserror", "write_bytes", ] [[package]] name = "print_opcode" version = "0.0.0" dependencies = [ "print_opcode_impl", "print_opcode_macro", ] [[package]] name = "print_opcode_impl" version = "0.0.0" dependencies = [ "convert_case", "hash", "hhbc-gen", "macro_test_util", "opcode_test_data", "proc-macro2", "quote", "syn 1.0.109", ] [[package]] name = "print_opcode_macro" version = "0.0.0" dependencies = [ "hhbc-gen", "print_opcode_impl", ] [[package]] name = "proc-macro-error" version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" dependencies = [ "proc-macro-error-attr", "proc-macro2", "quote", "syn 1.0.109", "version_check", ] [[package]] name = "proc-macro-error-attr" version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" dependencies = [ "proc-macro2", "quote", "version_check", ] [[package]] name = "proc-macro2" version = "1.0.64" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78803b62cbf1f46fde80d7c0e803111524b9877184cfe7c3033659490ac7a7da" dependencies = [ "unicode-ident", ] [[package]] name = "profile_rust" version = "0.0.0" dependencies = [ "libc", ] [[package]] name = "psm" version = "0.1.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6eca0fa5dd7c4c96e184cec588f0b1db1ee3165e678db21c09793105acb17e6f" dependencies = [ "cc", ] [[package]] name = "pulldown-cmark" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eef52fac62d0ea7b9b4dc7da092aa64ea7ec3d90af6679422d3d7e0e14b6ee15" dependencies = [ "bitflags 1.3.2", ] [[package]] name = "quanta" version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b7e31331286705f455e56cca62e0e717158474ff02b7936c1fa596d983f4ae27" dependencies = [ "crossbeam-utils 0.8.14", "libc", "mach", "once_cell", "raw-cpuid", "wasi 0.10.0+wasi-snapshot-preview1", "web-sys", "winapi", ] [[package]] name = "quickcheck" version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "env_logger 0.8.4", "log", "rand 0.8.5", ] [[package]] name = "quote" version = "1.0.29" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "573015e8ab27661678357f27dc26460738fd2b6c86e46f386fde94cb5d913105" dependencies = [ "proc-macro2", ] [[package]] name = "rand" version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "552840b97013b1a26992c11eac34bdd778e464601a4c2054b5f0bff7c6761293" dependencies = [ "fuchsia-cprng", "libc", "rand_core 0.3.1", "rdrand", "winapi", ] [[package]] name = "rand" version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" dependencies = [ "libc", "rand_chacha", "rand_core 0.6.4", ] [[package]] name = "rand_chacha" version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e12735cf05c9e10bf21534da50a147b924d555dc7a547c42e6bb2d5b6017ae0d" dependencies = [ "ppv-lite86", "rand_core 0.6.4", ] [[package]] name = "rand_core" version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" dependencies = [ "rand_core 0.4.2", ] [[package]] name = "rand_core" version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c33a3c44ca05fa6f1807d8e6743f3824e8509beca625669633be0acbdf509dc" [[package]] name = "rand_core" version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" dependencies = [ "getrandom", ] [[package]] name = "rand_xoshiro" version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6f97cdb2a36ed4183de61b2f824cc45c9f1037f28afe0a322e9fff4c108b5aaa" dependencies = [ "rand_core 0.6.4", ] [[package]] name = "raw-cpuid" version = "10.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6823ea29436221176fe662da99998ad3b4db2c7f31e7b6f5fe43adccd6320bb" dependencies = [ "bitflags 1.3.2", ] [[package]] name = "rayon" version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d2df5196e37bcc87abebc0053e20787d73847bb33134a69841207dd0a47f03b" dependencies = [ "either", "rayon-core", ] [[package]] name = "rayon-core" version = "1.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4b8f95bd6966f5c87776639160a66bd8ab9895d9d4ab01ddba9fc60661aebe8d" dependencies = [ "crossbeam-channel 0.5.8", "crossbeam-deque", "crossbeam-utils 0.8.14", "num_cpus", ] [[package]] name = "rc_pos" version = "0.0.0" dependencies = [ "arena_deserializer", "arena_trait", "eq_modulo_pos", "no_pos_hash", "ocamlrep", "parser_core_types", "pretty_assertions", "relative_path", "serde", "static_assertions", ] [[package]] name = "rdrand" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "678054eb77286b51581ba43620cc911abf02758c91f93f479767aed0f90458b2" dependencies = [ "rand_core 0.3.1", ] [[package]] name = "redox_syscall" version = "0.1.57" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "41cc0f7e4d5d4544e8861606a285bb08d3e70712ccc7d2b84d7c0ccfaf4b05ce" [[package]] name = "redox_syscall" version = "0.2.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8383f39639269cde97d255a32bdb68c047337295414940c68bdd30c2e13203ff" dependencies = [ "bitflags 1.3.2", ] [[package]] name = "redox_syscall" version = "0.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "567664f262709473930a4bf9e51bf2ebf3348f2e748ccc50dea20646858f8f29" dependencies = [ "bitflags 1.3.2", ] [[package]] name = "redox_users" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "528532f3d801c87aec9def2add9ca802fe569e44a544afe633765267840abe64" dependencies = [ "getrandom", "redox_syscall 0.2.10", ] [[package]] name = "regex" version = "1.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5bc4f4d719ae1d92dc7e5ef3865f93af6e28c7af68ebd7a68a367932b88c1e2c" dependencies = [ "aho-corasick", "memchr", "regex-automata 0.3.5", "regex-syntax", ] [[package]] name = "regex-automata" version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ae1ded71d66a4a97f5e961fd0cb25a5f366a42a41570d16a763a69c092c26ae4" dependencies = [ "byteorder", ] [[package]] name = "regex-automata" version = "0.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "26bb2039bb570943fc65037c16640a64fba171d3760138656fdfe62b3bd24239" dependencies = [ "aho-corasick", "memchr", "regex-syntax", ] [[package]] name = "regex-syntax" version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e5ea92a5b6195c6ef2a0295ea818b312502c6fc94dde986c5553242e18fd4ce2" [[package]] name = "relative_path" version = "0.0.0" dependencies = [ "arena_trait", "eq_modulo_pos", "no_pos_hash", "ocamlrep", "pretty_assertions", "serde", ] [[package]] name = "remove_dir_all" version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3acd125665422973a33ac9d3dd2df85edad0f4ae9b00dafb1a05e43a9f5ef8e7" dependencies = [ "winapi", ] [[package]] name = "rescan_trivia" version = "0.0.0" dependencies = [ "parser", "positioned_parser", ] [[package]] name = "rewrite_program" version = "0.0.0" dependencies = [ "closure_convert", "constant_folder", "env", "error", "hack_macros", "hhbc", "oxidized", "relative_path", "rewrite_xml", ] [[package]] name = "rewrite_xml" version = "0.0.0" dependencies = [ "env", "error", "hhbc", "naming_special_names_rust", "oxidized", ] [[package]] name = "riscv" version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6907ccdd7a31012b70faf2af85cd9e5ba97657cc3987c4f13f8e4d2c2a088aba" dependencies = [ "bare-metal 1.0.0", "bit_field", "riscv-target", ] [[package]] name = "riscv-target" version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "88aa938cda42a0cf62a20cfe8d139ff1af20c2e681212b5b34adb5a58333f222" dependencies = [ "lazy_static", "regex", ] [[package]] name = "rpds" version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4ef5140bcb576bfd6d56cd2de709a7d17851ac1f3805e67fe9d99e42a11821f" dependencies = [ "archery", ] [[package]] name = "rusqlite" version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "549b9d036d571d42e6e85d1c1425e2ac83491075078ca9a15be021c56b1641f2" dependencies = [ "bitflags 2.3.3", "fallible-iterator", "fallible-streaming-iterator", "hashlink", "libsqlite3-sys", "smallvec", ] [[package]] name = "rust_aast_parser_types" version = "0.0.0" dependencies = [ "lint_rust", "ocamlrep", "oxidized", "parser_core_types", ] [[package]] name = "rust_batch_index_ffi" version = "0.0.0" dependencies = [ "anyhow", "bumpalo", "direct_decl_parser", "hackrs_provider_backend", "ocamlrep_ocamlpool", "oxidized", "oxidized_by_ref", "rayon", "relative_path", "si_addendum", "unwrap_ocaml", ] [[package]] name = "rust_decl_ffi" version = "0.0.0" dependencies = [ "ast_and_decl_parser", "bumpalo", "direct_decl_parser", "hh_hash", "ocamlrep", "ocamlrep_caml_builtins", "ocamlrep_ocamlpool", "oxidized", "oxidized_by_ref", "parser_core_types", "relative_path", ] [[package]] name = "rust_facts_ffi" version = "0.0.0" dependencies = [ "bumpalo", "direct_decl_parser", "facts_rust", "hhbc_string_utils", "ocamlrep", "ocamlrep_ocamlpool", "relative_path", ] [[package]] name = "rust_parser_errors" version = "0.0.0" dependencies = [ "escaper", "hash", "hh_autoimport_rust", "itertools 0.10.5", "naming_special_names_rust", "oxidized", "parser_core_types", "stack_limit", "strum", ] [[package]] name = "rust_parser_errors_ffi" version = "0.0.0" dependencies = [ "bumpalo", "ocamlrep", "ocamlrep_ocamlpool", "oxidized", "parser_core_types", "rust_parser_errors", ] [[package]] name = "rust_parser_ffi" version = "0.0.0" dependencies = [ "bumpalo", "mode_parser", "ocamlrep", "ocamlrep_ocamlpool", "operator", "oxidized", "parser_core_types", "positioned_by_ref_parser", "to_ocaml_impl", ] [[package]] name = "rust_provider_backend_api" version = "0.0.0" dependencies = [ "file_provider", "folded_decl_provider", "naming_provider", "shallow_decl_provider", "ty", ] [[package]] name = "rust_to_ocaml_attr" version = "0.0.0" [[package]] name = "rustc-demangle" version = "0.1.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7ef03e0a2b150c7a90d01faf6254c9c48a41e95fb2a8c2ac1c6f0d2b9aefc342" [[package]] name = "rustc-hash" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" [[package]] name = "rustc_version" version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a" dependencies = [ "semver 0.9.0", ] [[package]] name = "rustc_version" version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0dfe2087c51c460008730de8b57e6a320782fbfb312e1f4d520e6c6fae155ee" dependencies = [ "semver 0.11.0", ] [[package]] name = "rustc_version" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366" dependencies = [ "semver 1.0.17", ] [[package]] name = "rustix" version = "0.37.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "acf8729d8542766f1b2cf77eb034d52f40d375bb8b615d0b147089946e16613d" dependencies = [ "bitflags 1.3.2", "errno", "io-lifetimes", "libc", "linux-raw-sys", "windows-sys 0.48.0", ] [[package]] name = "rustversion" version = "1.0.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc31bd9b61a32c31f9650d18add92aa83a49ba979c143eefd27fe7177b05bd5f" [[package]] name = "ryu" version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "71d301d4193d031abdd79ff7e3dd721168a9572ef3fe51a1517aba235bd8f86e" [[package]] name = "same-file" version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" dependencies = [ "winapi-util", ] [[package]] name = "scheduled-thread-pool" version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "977a7519bff143a44f842fd07e80ad1329295bd71686457f18e496736f4bf9bf" dependencies = [ "parking_lot", ] [[package]] name = "scope" version = "0.0.0" dependencies = [ "env", "error", "hhbc", "instruction_sequence", ] [[package]] name = "scopeguard" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" [[package]] name = "scratch" version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "764cad9e7e1ca5fe15b552859ff5d96a314e6ed2934f2260168cd5dfa5891409" [[package]] name = "sem_diff" version = "0.0.0" dependencies = [ "anyhow", "ffi", "hash", "hhbc", "hhbc-gen", "itertools 0.10.5", "log", "newtype", ] [[package]] name = "semver" version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403" dependencies = [ "semver-parser 0.7.0", "serde", ] [[package]] name = "semver" version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f301af10236f6df4160f7c3f04eec6dbc70ace82d23326abad5edee88801c6b6" dependencies = [ "semver-parser 0.10.1", ] [[package]] name = "semver" version = "1.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bebd363326d05ec3e2f532ab7660680f3b02130d780c299bca73469d521bc0ed" [[package]] name = "semver-parser" version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" [[package]] name = "semver-parser" version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42ef146c2ad5e5f4b037cd6ce2ebb775401729b19a82040c1beac9d36c7d1428" dependencies = [ "pest", ] [[package]] name = "serde" version = "1.0.176" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "76dc28c9523c5d70816e393136b86d48909cfb27cecaa902d338c19ed47164dc" dependencies = [ "serde_derive", ] [[package]] name = "serde_bytes" version = "0.11.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "16ae07dd2f88a366f15bd0632ba725227018c69a1c8550a927324f8eb8368bb9" dependencies = [ "serde", ] [[package]] name = "serde_derive" version = "1.0.176" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a4e7b8c5dc823e3b90651ff1d3808419cd14e5ad76de04feaf37da114e7a306f" dependencies = [ "proc-macro2", "quote", "syn 2.0.27", ] [[package]] name = "serde_fmt" version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e1d4ddca14104cd60529e8c7f7ba71a2c8acd8f7f5cfcdc2faf97eeb7c3010a4" dependencies = [ "serde", ] [[package]] name = "serde_json" version = "1.0.100" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0f1e14e89be7aa4c4b78bdbdc9eb5bf8517829a600ae8eaa39a6e1d960b5185c" dependencies = [ "itoa 1.0.5", "ryu", "serde", ] [[package]] name = "serde_spanned" version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0efd8caf556a6cebd3b285caf480045fcc1ac04f6bd786b09a6f11af30c4fcf4" dependencies = [ "serde", ] [[package]] name = "sha1" version = "0.10.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f04293dc80c3993519f2d7f6f511707ee7094fe0c6d3406feb330cdb3540eba3" dependencies = [ "cfg-if 1.0.0", "cpufeatures", "digest", ] [[package]] name = "shallow_decl_provider" version = "0.0.0" dependencies = [ "anyhow", "datastore", "decl_parser", "itertools 0.10.5", "naming_provider", "oxidized", "pos", "serde", "thiserror", "ty", ] [[package]] name = "shm_store" version = "0.0.0" dependencies = [ "anyhow", "bincode", "datastore", "hh24_types", "intern", "lru", "lz4", "md-5", "measure", "ocaml_blob", "ocamlrep", "ocamlrep_marshal", "parking_lot", "pos", "serde", "shmffi", "zstd", ] [[package]] name = "shmffi" version = "0.0.0" dependencies = [ "libc", "ocaml_blob", "ocamlrep", "ocamlrep_ocamlpool", "once_cell", "shmrs", ] [[package]] name = "shmrs" version = "0.0.0" dependencies = [ "hashbrown 0.12.3", "libc", "nix", "nohash-hasher", "rand 0.8.5", "static_assertions", ] [[package]] name = "si_addendum" version = "0.0.0" dependencies = [ "core_utils_rust", "oxidized", "oxidized_by_ref", ] [[package]] name = "signed_source" version = "0.0.0" dependencies = [ "bstr 1.6.0", "hex", "md-5", "once_cell", "regex", "thiserror", ] [[package]] name = "sized-chunks" version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "16d69225bde7a69b235da73377861095455d298f2b970996eec25ddbb42b3d1e" dependencies = [ "bitmaps", "typenum", ] [[package]] name = "skeptic" version = "0.13.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a6deb8efaf3ad8fd784139db8bbd51806bfbcee87c7be7578e9c930981fb808" dependencies = [ "bytecount", "cargo_metadata", "error-chain", "glob", "pulldown-cmark", "tempfile", "walkdir", ] [[package]] name = "slab" version = "0.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4614a76b2a8be0058caa9dbbaf66d988527d86d003c11a94fbd335d7661edcef" dependencies = [ "autocfg", ] [[package]] name = "slog" version = "2.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8347046d4ebd943127157b94d63abb990fcf729dc4e9978927fdf4ac3c998d06" dependencies = [ "erased-serde", ] [[package]] name = "slog-async" version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "51b3336ce47ce2f96673499fc07eb85e3472727b9a7a2959964b002c2ce8fbbb" dependencies = [ "crossbeam-channel 0.4.4", "slog", "take_mut", "thread_local", ] [[package]] name = "slog-envlogger" version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "906a1a0bc43fed692df4b82a5e2fbfc3733db8dad8bb514ab27a4f23ad04f5c0" dependencies = [ "log", "regex", "slog", "slog-async", "slog-scope", "slog-stdlog", "slog-term", ] [[package]] name = "slog-json" version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ddc0d2aff1f8f325ef660d9a0eb6e6dcd20b30b3f581a5897f58bf42d061c37a" dependencies = [ "chrono", "serde", "serde_json", "slog", ] [[package]] name = "slog-scope" version = "4.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c44c89dd8b0ae4537d1ae318353eaf7840b4869c536e31c41e963d1ea523ee6" dependencies = [ "arc-swap", "lazy_static", "slog", ] [[package]] name = "slog-stdlog" version = "4.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6706b2ace5bbae7291d3f8d2473e2bfab073ccd7d03670946197aec98471fa3e" dependencies = [ "log", "slog", "slog-scope", ] [[package]] name = "slog-term" version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "95c1e7e5aab61ced6006149ea772770b84a0d16ce0f7885def313e4829946d76" dependencies = [ "atty", "chrono", "slog", "term", "thread_local", ] [[package]] name = "smallvec" version = "1.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a507befe795404456341dfab10cef66ead4c041f62b8b11bbb92bffe5d0953e0" dependencies = [ "serde", ] [[package]] name = "smart_constructors" version = "0.0.0" dependencies = [ "ocamlrep", "parser_core_types", ] [[package]] name = "socket2" version = "0.4.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "64a4a911eed85daf18834cfaa86a79b7d266ff93ff5ba14005426219480ed662" dependencies = [ "libc", "winapi", ] [[package]] name = "sparsevec" version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "928d1ef5df00aec8c5643c2ac37db4dd282763013c0fcc81efbb8e13db8dd8ec" dependencies = [ "num-traits", "packedvec", "serde", "vob", ] [[package]] name = "special_names" version = "0.0.0" dependencies = [ "hash", "naming_special_names_rust", "once_cell", "pos", ] [[package]] name = "spin" version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f6002a767bff9e83f8eeecf883ecb8011875a21ae8da43bffb817a57e78cc09" dependencies = [ "lock_api", ] [[package]] name = "stable_deref_trait" version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" [[package]] name = "stack_depth" version = "0.0.0" dependencies = [ "ffi", "hhbc", "hhbc-gen", "log", "newtype", "thiserror", ] [[package]] name = "stack_limit" version = "0.0.0" dependencies = [ "psm", "stacker", ] [[package]] name = "stacker" version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "90939d5171a4420b3ff5fbc8954d641e7377335454c259dcb80786f3f21dc9b4" dependencies = [ "cc", "cfg-if 1.0.0", "libc", "psm", "winapi", ] [[package]] name = "statement_state" version = "0.0.0" dependencies = [ "instruction_sequence", "oxidized", ] [[package]] name = "static_assertions" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" [[package]] name = "stats_rust" version = "0.0.0" [[package]] name = "strsim" version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" [[package]] name = "strum" version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "063e6045c0e62079840579a7e47a355ae92f60eb74daaf156fb1e84ba164e63f" dependencies = [ "strum_macros", ] [[package]] name = "strum_macros" version = "0.24.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e385be0d24f186b4ce2f9982191e7101bb737312ad61c1f2f984f34bcf85d59" dependencies = [ "heck", "proc-macro2", "quote", "rustversion", "syn 1.0.109", ] [[package]] name = "sval" version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0e6aa16ce8d9e472e21a528a52c875a76a49190f3968f2ec7e9b550ccc28b410" [[package]] name = "sval_buffer" version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "905c4373621186ee9637464b0aaa026389ea9e7f841f2225f160a32ba5d5bac4" dependencies = [ "sval", "sval_ref", ] [[package]] name = "sval_dynamic" version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ad6b4988322c5f22859a6a7649fa1249aa3dd01514caf8ed57d83735f997bb8b" dependencies = [ "sval", ] [[package]] name = "sval_fmt" version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9d3ccd10346f925c2fbd97b75e8573b38e34431bfba04cc531cd23aad0fbabb8" dependencies = [ "itoa 1.0.5", "ryu", "sval", ] [[package]] name = "sval_json" version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6a12e1488defd6344e23243c17ea4a1b185c547968749e8a281373fde0bde2d5" dependencies = [ "itoa 1.0.5", "ryu", "sval", ] [[package]] name = "sval_ref" version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b797fc4b284dd0e45f7ec424479e604ea5be9bb191a1ef4e96c20c7685649938" dependencies = [ "sval", ] [[package]] name = "sval_serde" version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "810fa9a837e67a23e0efa7536250fc4d24043306cc1efd076f1943ba2fc2e62d" dependencies = [ "serde", "sval", "sval_buffer", "sval_fmt", ] [[package]] name = "syn" version = "1.0.109" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "syn" version = "2.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b60f673f44a8255b9c8c657daf66a596d435f2da81a555b06dc644d080ba45e0" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "synstructure" version = "0.12.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "474aaa926faa1603c40b7885a9eaea29b444d1cb2850cb7c0e37bb1a4182f4fa" dependencies = [ "proc-macro2", "quote", "syn 1.0.109", "unicode-xid", ] [[package]] name = "syntax_smart_constructors" version = "0.0.0" dependencies = [ "parser_core_types", "smart_constructors", ] [[package]] name = "tagptr" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b2093cf4c8eb1e67749a6762251bc9cd836b6fc171623bd0a9d324d37af2417" [[package]] name = "take_mut" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f764005d11ee5f36500a149ace24e00e3da98b0158b3e2d53a7495660d3f4d60" [[package]] name = "tempdir" version = "0.3.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "15f2b5fb00ccdf689e0149d1b1b3c03fead81c2b37735d812fa8bddbbf41b6d8" dependencies = [ "rand 0.4.6", "remove_dir_all", ] [[package]] name = "tempfile" version = "3.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9fbec84f381d5795b08656e4912bec604d162bff9291d6189a78f4c8ab87998" dependencies = [ "cfg-if 1.0.0", "fastrand", "redox_syscall 0.3.5", "rustix", "windows-sys 0.45.0", ] [[package]] name = "term" version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c59df8ac95d96ff9bede18eb7300b0fda5e5d8d90960e76f8e14ae765eedbf1f" dependencies = [ "dirs-next", "rustversion", "winapi", ] [[package]] name = "termcolor" version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2dfed899f0eb03f32ee8c6a0aabdb8a7949659e3466561fc0adf54e26d88c5f4" dependencies = [ "winapi-util", ] [[package]] name = "terminal_size" version = "0.1.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "633c1a546cee861a1a6d0dc69ebeca693bf4296661ba7852b9d21d159e0506df" dependencies = [ "libc", "winapi", ] [[package]] name = "terminal_size" version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e6bf6f19e9f8ed8d4048dc22981458ebcf406d67e94cd422e5ecd73d63b3237" dependencies = [ "rustix", "windows-sys 0.48.0", ] [[package]] name = "tests" version = "0.0.0" dependencies = [ "html_entities", "pretty_assertions", ] [[package]] name = "testutils" version = "0.0.0" dependencies = [ "hash", "ir_core", "print", ] [[package]] name = "textual" version = "0.0.0" dependencies = [ "anyhow", "ascii", "escaper", "hash", "ir", "itertools 0.10.5", "log", "naming_special_names_rust", "newtype", "strum", "textual_macros", ] [[package]] name = "textual_macros" version = "0.0.0" dependencies = [ "itertools 0.10.5", "proc-macro-error", "proc-macro2", "quote", "syn 1.0.109", ] [[package]] name = "textwrap" version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060" dependencies = [ "unicode-width", ] [[package]] name = "textwrap" version = "0.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "222a222a5bfe1bba4a77b45ec488a741b3cb8872e5e499451fd7d0129c9c7c3d" dependencies = [ "terminal_size 0.2.6", "unicode-width", ] [[package]] name = "thiserror" version = "1.0.43" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a35fc5b8971143ca348fa6df4f024d4d55264f3468c71ad1c2f365b0a4d58c42" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" version = "1.0.43" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "463fe12d7993d3b327787537ce8dd4dfa058de32fc2b195ef3cde03dc4771e8f" dependencies = [ "proc-macro2", "quote", "syn 2.0.27", ] [[package]] name = "thread_local" version = "1.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5516c27b78311c50bf42c071425c560ac799b11c30b31f87e3081965fe5e0180" dependencies = [ "once_cell", ] [[package]] name = "time" version = "0.1.44" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6db9e6914ab8b1ae1c260a4ae7a49b6c5611b40328a735b21862567685e73255" dependencies = [ "libc", "wasi 0.10.0+wasi-snapshot-preview1", "winapi", ] [[package]] name = "time" version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a561bf4617eebd33bca6434b988f39ed798e527f51a1e797d0ee4f61c0a38376" dependencies = [ "itoa 1.0.5", "serde", "time-core", "time-macros", ] [[package]] name = "time-core" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2e153e1f1acaef8acc537e68b44906d2db6436e2b35ac2c6b42640fff91f00fd" [[package]] name = "time-macros" version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d967f99f534ca7e495c575c62638eebc2898a8c84c119b89e250477bc4ba16b2" dependencies = [ "time-core", ] [[package]] name = "tinytemplate" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6d3dc76004a03cec1c5932bca4cdc2e39aaa798e3f82363dd94f9adf6098c12f" dependencies = [ "serde", "serde_json", ] [[package]] name = "to_ocaml_impl" version = "0.0.0" dependencies = [ "ocamlrep", "parser_core_types", "stack_limit", ] [[package]] name = "tokio" version = "1.29.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "532826ff75199d5833b9d2c5fe410f29235e25704ee5f0ef599fb51c21f4a4da" dependencies = [ "autocfg", "backtrace", "bytes", "pin-project-lite", ] [[package]] name = "toml" version = "0.5.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f4f7f0dd8d50a853a531c426359045b1998f04219d88799810762cd4ad314234" dependencies = [ "serde", ] [[package]] name = "toml" version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b403acf6f2bb0859c93c7f0d967cb4a75a7ac552100f9322faf64dc047669b21" dependencies = [ "serde", "serde_spanned", "toml_datetime", "toml_edit", ] [[package]] name = "toml_datetime" version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ab8ed2edee10b50132aed5f331333428b011c99402b5a534154ed15746f9622" dependencies = [ "serde", ] [[package]] name = "toml_edit" version = "0.19.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "239410c8609e8125456927e6707163a3b1fdb40561e4b803bc041f466ccfdc13" dependencies = [ "indexmap", "serde", "serde_spanned", "toml_datetime", "winnow", ] [[package]] name = "tracing" version = "0.1.37" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "log", "pin-project-lite", "tracing-attributes", "tracing-core", ] [[package]] name = "tracing-attributes" version = "0.1.23" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "proc-macro2", "quote", "syn 2.0.27", ] [[package]] name = "tracing-core" version = "0.1.30" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "once_cell", ] [[package]] name = "triomphe" version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1ee9bd9239c339d714d657fac840c6d2a4f9c45f4f9ec7b0975113458be78db" [[package]] name = "try_from" version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "283d3b89e1368717881a9d51dad843cc435380d8109c9e47d38780a324698d8b" dependencies = [ "cfg-if 0.1.10", ] [[package]] name = "ty" version = "0.0.0" dependencies = [ "arena_collections", "bumpalo", "eq_modulo_pos", "hash", "hcons", "im", "ocamlrep", "once_cell", "oxidized", "oxidized_by_ref", "pos", "serde", "static_assertions", "utils", ] [[package]] name = "typenum" version = "1.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dcf81ac59edc17cc8697ff311e8f5ef2d99fcbd9817b34cec66f90b6c3dfd987" [[package]] name = "types" version = "0.0.0" dependencies = [ "decl_provider", "hash", "hh_autoimport_rust", "itertools 0.10.5", "lazy_static", "naming_special_names_rust", "oxidized", "oxidized_by_ref", "parser_core_types", ] [[package]] name = "typing_deps_hash" version = "0.0.0" dependencies = [ "fnv", "strum", ] [[package]] name = "ucd-trie" version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed646292ffc8188ef8ea4d1e0e0150fb15a5c2e12ad9b8fc191ae7a8a7f3c4b9" [[package]] name = "unicase" version = "2.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "50f37be617794602aabbeee0be4f259dc1778fabe05e2d67ee8f79326d5cb4f6" dependencies = [ "version_check", ] [[package]] name = "unicode-ident" version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "22049a19f4a68748a168c0fc439f9516686aa045927ff767eca0a85101fb6e73" [[package]] name = "unicode-segmentation" version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1dd624098567895118886609431a7c3b8f516e41d30e0643f03d94592a147e36" [[package]] name = "unicode-width" version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c0edd1e5b14653f783770bce4a4dabb4a5108a5370a5f5d8cfe8710c361f6c8b" [[package]] name = "unicode-xid" version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "957e51f3646910546462e67d5f7599b9e4fb8acdd304b087a6494730f9eebf04" [[package]] name = "unique_id_builder" version = "0.0.0" [[package]] name = "unwrap_ocaml" version = "0.0.0" dependencies = [ "libc", ] [[package]] name = "utf8-width" version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9071ac216321a4470a69fb2b28cfc68dcd1a39acd877c8be8e014df6772d8efa" [[package]] name = "utf8parse" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a" [[package]] name = "utils" version = "0.0.0" dependencies = [ "eq_modulo_pos", "ocamlrep", "oxidized", "pos", "serde", ] [[package]] name = "uuid" version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1674845326ee10d37ca60470760d4288a6f80f304007d92e5c53bab78c9cfd79" dependencies = [ "getrandom", ] [[package]] name = "value-bag" version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a4d330786735ea358f3bc09eea4caa098569c1c93f342d9aca0514915022fe7e" dependencies = [ "value-bag-serde1", "value-bag-sval2", ] [[package]] name = "value-bag-serde1" version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4735c95b4cca1447b448e2e2e87e98d7e7498f4da27e355cf7af02204521001d" dependencies = [ "erased-serde", "serde", "serde_fmt", ] [[package]] name = "value-bag-sval2" version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "859cb4f0ce7da6a118b559ba74b0e63bf569bea867c20ba457a6b1c886a04e97" dependencies = [ "sval", "sval_buffer", "sval_dynamic", "sval_fmt", "sval_json", "sval_ref", "sval_serde", ] [[package]] name = "vcell" version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77439c1b53d2303b20d9459b1ade71a83c716e3f9c34f3228c00e6f185d6c002" [[package]] name = "vcpkg" version = "0.2.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6454029bf181f092ad1b853286f23e2c507d8e8194d01d92da4a55c274a5508c" [[package]] name = "vec1" version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2bda7c41ca331fe9a1c278a9e7ee055f4be7f5eb1c2b72f079b4ff8b5fce9d5c" dependencies = [ "serde", ] [[package]] name = "vergen" version = "7.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3bbc4fafd30514504c7593cfa52eaf4d6c4ef660386e2ec54edc17f14aa08e8d" dependencies = [ "anyhow", "cfg-if 1.0.0", "enum-iterator", "getset", "rustversion", "thiserror", "time 0.3.17", ] [[package]] name = "verify" version = "0.0.0" dependencies = [ "analysis", "ir_core", "itertools 0.10.5", "print", ] [[package]] name = "version_check" version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" [[package]] name = "vint64" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e0b3dd7987b5df43ec8f5a1050d608b4d9c78a5785c70549635870b9cad9442c" [[package]] name = "vob" version = "3.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cbdb3eee5dd38a27129832bca4a3171888e699a6ac36de86547975466997986f" dependencies = [ "num-traits", "rustc_version 0.3.3", "serde", ] [[package]] name = "void" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d" [[package]] name = "volatile-register" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ee8f19f9d74293faf70901bc20ad067dc1ad390d2cbf1e3f75f721ffee908b6" dependencies = [ "vcell", ] [[package]] name = "waker-fn" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9d5b2c62b4012a3e1eca5a7e077d13b3bf498c4073e33ccd58626607748ceeca" [[package]] name = "walkdir" version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "808cf2735cd4b6866113f648b791c6adc5714537bc222d9347bb203386ffda56" dependencies = [ "same-file", "winapi", "winapi-util", ] [[package]] name = "wasi" version = "0.10.0+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f" [[package]] name = "wasi" version = "0.11.0+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "wasm-bindgen" version = "0.2.83" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eaf9f5aceeec8be17c128b2e93e031fb8a4d469bb9c4ae2d7dc1888b26887268" dependencies = [ "cfg-if 1.0.0", "wasm-bindgen-macro", ] [[package]] name = "wasm-bindgen-backend" version = "0.2.83" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4c8ffb332579b0557b52d268b91feab8df3615f265d5270fec2a8c95b17c1142" dependencies = [ "bumpalo", "log", "once_cell", "proc-macro2", "quote", "syn 1.0.109", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-macro" version = "0.2.83" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "052be0f94026e6cbc75cdefc9bae13fd6052cdcaf532fa6c45e7ae33a1e6c810" dependencies = [ "quote", "wasm-bindgen-macro-support", ] [[package]] name = "wasm-bindgen-macro-support" version = "0.2.83" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "07bc0c051dc5f23e307b13285f9d75df86bfdf816c5721e573dec1f9b8aa193c" dependencies = [ "proc-macro2", "quote", "syn 1.0.109", "wasm-bindgen-backend", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" version = "0.2.83" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c38c045535d93ec4f0b4defec448e4291638ee608530863b1e2ba115d4fff7f" [[package]] name = "web-sys" version = "0.3.59" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed055ab27f941423197eb86b2035720b1a3ce40504df082cac2ecc6ed73335a1" dependencies = [ "js-sys", "wasm-bindgen", ] [[package]] name = "wepoll-sys" version = "3.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fcb14dea929042224824779fbc82d9fab8d2e6d3cbc0ac404de8edf489e77ff" dependencies = [ "cc", ] [[package]] name = "winapi" version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" dependencies = [ "winapi-i686-pc-windows-gnu", "winapi-x86_64-pc-windows-gnu", ] [[package]] name = "winapi-i686-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" [[package]] name = "winapi-util" version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" dependencies = [ "winapi", ] [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] name = "windows-sys" version = "0.45.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" dependencies = [ "windows-targets 0.42.1", ] [[package]] name = "windows-sys" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" dependencies = [ "windows-targets 0.48.0", ] [[package]] name = "windows-targets" version = "0.42.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e2522491fbfcd58cc84d47aeb2958948c4b8982e9a2d8a2a35bbaed431390e7" dependencies = [ "windows_aarch64_gnullvm 0.42.1", "windows_aarch64_msvc 0.42.1", "windows_i686_gnu 0.42.1", "windows_i686_msvc 0.42.1", "windows_x86_64_gnu 0.42.1", "windows_x86_64_gnullvm 0.42.1", "windows_x86_64_msvc 0.42.1", ] [[package]] name = "windows-targets" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b1eb6f0cd7c80c79759c929114ef071b87354ce476d9d94271031c0497adfd5" dependencies = [ "windows_aarch64_gnullvm 0.48.0", "windows_aarch64_msvc 0.48.0", "windows_i686_gnu 0.48.0", "windows_i686_msvc 0.48.0", "windows_x86_64_gnu 0.48.0", "windows_x86_64_gnullvm 0.48.0", "windows_x86_64_msvc 0.48.0", ] [[package]] name = "windows_aarch64_gnullvm" version = "0.42.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8c9864e83243fdec7fc9c5444389dcbbfd258f745e7853198f365e3c4968a608" [[package]] name = "windows_aarch64_gnullvm" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "91ae572e1b79dba883e0d315474df7305d12f569b400fcf90581b06062f7e1bc" [[package]] name = "windows_aarch64_msvc" version = "0.42.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4c8b1b673ffc16c47a9ff48570a9d85e25d265735c503681332589af6253c6c7" [[package]] name = "windows_aarch64_msvc" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b2ef27e0d7bdfcfc7b868b317c1d32c641a6fe4629c171b8928c7b08d98d7cf3" [[package]] name = "windows_i686_gnu" version = "0.42.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "de3887528ad530ba7bdbb1faa8275ec7a1155a45ffa57c37993960277145d640" [[package]] name = "windows_i686_gnu" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "622a1962a7db830d6fd0a69683c80a18fda201879f0f447f065a3b7467daa241" [[package]] name = "windows_i686_msvc" version = "0.42.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bf4d1122317eddd6ff351aa852118a2418ad4214e6613a50e0191f7004372605" [[package]] name = "windows_i686_msvc" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4542c6e364ce21bf45d69fdd2a8e455fa38d316158cfd43b3ac1c5b1b19f8e00" [[package]] name = "windows_x86_64_gnu" version = "0.42.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1040f221285e17ebccbc2591ffdc2d44ee1f9186324dd3e84e99ac68d699c45" [[package]] name = "windows_x86_64_gnu" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca2b8a661f7628cbd23440e50b05d705db3686f894fc9580820623656af974b1" [[package]] name = "windows_x86_64_gnullvm" version = "0.42.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "628bfdf232daa22b0d64fdb62b09fcc36bb01f05a3939e20ab73aaf9470d0463" [[package]] name = "windows_x86_64_gnullvm" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7896dbc1f41e08872e9d5e8f8baa8fdd2677f29468c4e156210174edc7f7b953" [[package]] name = "windows_x86_64_msvc" version = "0.42.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "447660ad36a13288b1db4d4248e857b510e8c3a225c822ba4fb748c0aafecffd" [[package]] name = "windows_x86_64_msvc" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1a515f5799fe4961cb532f983ce2b23082366b898e52ffbce459c86f67c8378a" [[package]] name = "winnow" version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ae8970b36c66498d8ff1d66685dc86b91b29db0c7739899012f63a63814b4b28" dependencies = [ "memchr", ] [[package]] name = "write_bytes" version = "0.0.0" dependencies = [ "bstr 1.6.0", "write_bytes-macro", ] [[package]] name = "write_bytes-macro" version = "0.0.0" dependencies = [ "proc-macro2", "quote", "syn 1.0.109", ] [[package]] name = "yansi" version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09041cd90cf85f7f8b2df60c646f853b7f535ce68f85244eb6731cf89fa498ec" [[package]] name = "zstd" version = "0.11.2+zstd.1.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20cc960326ece64f010d2d2107537f26dc589a6573a316bd5b1dba685fa5fde4" dependencies = [ "zstd-safe", ] [[package]] name = "zstd-safe" version = "5.0.1+zstd.1.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c12659121420dd6365c5c3de4901f97145b79651fb1d25814020ed2ed0585ae" dependencies = [ "libc", "zstd-sys", ] [[package]] name = "zstd-sys" version = "2.0.1+zstd.1.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9fd07cbbc53846d9145dbffdf6dd09a7a0aa52be46741825f5c97bdd4f73f12b" dependencies = [ "cc", "libc", ]
TOML
hhvm/hphp/hack/src/Cargo.toml
[workspace] members = [ "arena_collections", "arena_trait", "asdl_to_rust/lrgen", "client/ide_service/cargo/rust_batch_index_ffi", "custom_error/cargo/custom_error_config_ffi", "decl/cargo/rust_decl_ffi", "decl/direct_decl_smart_constructors", "deps/cargo/deps_rust", "deps/cargo/deps_rust_ffi", "deps/cargo/hh_fanout_rust_ffi", "deps/cargo/typing_deps_hash", "facts/cargo/facts_rust", "facts/cargo/rust_facts_ffi", "hackc/bytecode_printer", "hackc", "hackc/compile/cargo/closure_convert", "hackc/compile/cargo/compile", "hackc/compile/cargo/options", "hackc/compile/cargo/rewrite_program", "hackc/compile/cargo/rewrite_xml", "hackc/emitter/cargo/emit_pos", "hackc/emitter/cargo/emit_type_hint", "hackc/emitter/cargo/emit_unit", "hackc/emitter/cargo/env", "hackc/emitter/cargo/global_state", "hackc/emitter/cargo/instruction_sequence", "hackc/emitter/cargo/label_rewriter", "hackc/emitter/cargo/statement_state", "hackc/hhbc/cargo/dump-opcodes", "hackc/hhbc/cargo/hhbc", "hackc/ffi_bridge", "hackc/emitter/cargo/constant_folder", "hackc/emitter/cargo/scope", "hackc/hhvm_cxx/hhvm_hhbc_defs", "hackc/utils/cargo/hhbc_string_utils", "hackc/utils/cargo/stack_depth", "hackc/utils/cargo/unique_id_builder", "heap", "hh_codegen", "hh_fanout/cargo/hh_fanout_build_rust", "hh_fanout/cargo/hh_fanout_dep_graph_is_subgraph_rust", "hh_fanout/cargo/hh_fanout_dep_graph_stats_rust", "hh_naming_table_builder/cargo/naming_table_builder_ffi", "naming", "naming/cargo/elab_ffi", "naming/cargo/elaborate_namespaces", "naming/cargo/naming_attributes", "naming/names_rust", "ocamlrep_marshal/cargo/ocamlrep_marshal_ffi_bindings", "oxidized", "oxidized_by_ref", "package/cargo", "package/ffi_bridge", "package/ocaml_ffi/cargo", "parser/api/cargo/cst_and_decl_parser", "parser/api/cargo/decl_mode_parser", "parser/api/cargo/direct_decl_parser", "parser/api/cargo/positioned_by_ref_parser", "parser/api/cargo/positioned_full_trivia_parser", "parser/api/cargo/positioned_parser", "parser/api/cargo/rescan_trivia", "parser/cargo/aast_parser", "parser/cargo/aast_parser_ffi", "parser/cargo/bench", "parser/cargo/core_types", "parser/cargo/decl_mode_parser", "parser/cargo/errors", "parser/cargo/flatten_smart_constructors", "parser/cargo/hh_autoimport", "parser/cargo/mode_parser", "parser/cargo/namespaces", "parser/cargo/operator", "parser/cargo/pair_smart_constructors", "parser/cargo/positioned_by_ref_parser_ffi", "parser/cargo/positioned_smart_constructors", "parser/cargo/rust_aast_parser_types", "parser/cargo/rust_parser_errors_ffi", "parser/cargo/rust_parser_ffi", "parser/cargo/smart_constructors", "parser/cargo/syntax_smart_constructors", "parser/cargo/to_ocaml_impl", "parser/core", "parser/ffi_bridge", "parser/lowerer", "parser/schema", "providers/cargo/decl_provider_rust", "shmffi/cargo/shmffi", "utils/arena_deserializer", "utils/config_file/rust/ffi", "utils/core", "utils/eq_modulo_pos", "utils/eq_modulo_pos_derive", "utils/escaper", "utils/ffi_cbindgen", "utils/find_utils", "utils/hash", "utils/hh24_types", "utils/html_entities", "utils/html_entities/test", "utils/intern", "utils/line_break_map", "utils/lint", "utils/multifile", "utils/no_pos_hash", "utils/no_pos_hash/derive", "utils/ocaml_helper", "utils/ocaml_runtime", "utils/perf/cargo/profile", "utils/perf/cargo/stats", "utils/rust/measure/ffi", "utils/stack_limit", "utils/test", "utils/test/arena_deserializer", ]
hhvm/hphp/hack/src/dune
(env (_ (flags (:standard -w @a-4-29-35-41-42-44-45-48-50-70 \ -strict-sequence)))) (executable (name hh_single_type_check) (modules hh_single_type_check) (modes exe byte_complete) (link_flags (:standard (:include dune_config/ld-opts.sexp))) (libraries camlp-streams ifc ifc_lib client_get_definition client_highlight_refs code_actions_cli_lib count_imprecise_types custom_error_types decl_parser_options default_injector_config dep_hash_to_symbol direct_decl_parser direct_decl_utils gen_deps hhi hhi_get naming_ast_print memtrace package_info package_config parent rust_provider_backend_stubs refactor_sd remove_dead_unsafe_casts sdt_analysis server_env server_env_build server_code_actions_services server_file_outline server_find_refs server_go_to server_highlight_refs server_symbol_info_service_utils server_type_hierarchy shape_analysis sys_utils temp_file typing utils_core utils_multifile write_symbol_info)) (executable (name hh_single_ai) (modules hh_single_ai) (modes exe byte_complete) (link_flags (:standard (:include dune_config/ld-opts.sexp))) (libraries ai default_injector_config hhi sys_utils temp_file typing utils_core utils_multifile)) (executable (name hh_single_complete) (modules hh_single_complete) (modes exe byte_complete) (link_flags (:standard (:include dune_config/ld-opts.sexp))) (libraries default_injector_config file_content hhi search server_autocomplete_services server_search string sys_utils utils_core)) (executable (name hh_server) (modules hh_server) (modes exe byte_complete) (link_flags (:standard (:include dune_config/ld-opts.sexp))) (libraries client default_injector_config file_content gen_deps hhi hh_server_monitor parent server server_env sys_utils typing utils_core)) (executable (name hh_client) (modules hh_client) (modes exe byte_complete) (link_flags (:standard (:include dune_config/ld-opts.sexp))) (libraries client default_injector_config file_content gen_deps hhi hh_server_monitor lwt_utils parent server server_env sys_utils typing utils_core utils_exit)) (library (name full_fidelity_parse_args) (wrapped false) (modules fullFidelityParseArgs) (libraries global_options parser_options parser)) (executable (name hh_parse) (modes exe byte_complete) (modules hh_parse generate_hhi) (link_flags (:standard (:include dune_config/ld-opts.sexp))) (libraries default_injector_config full_fidelity_parse_args global_config hackfmt parser utils_core)) (executable (name hh_single_decl) (modes exe byte_complete) (modules hh_single_decl) (link_flags (:standard (:include dune_config/ld-opts.sexp))) (libraries decl_parser_options decl_provider default_injector_config direct_decl_parser file_provider ocamlrep_marshal_ffi package_info ppxlib.print_diff provider_context provider_utils server_env utils_core)) (executable (name hackfmt) (modules hackfmt) (modes exe byte_complete) (link_flags (:standard (:include dune_config/ld-opts.sexp))) (libraries default_injector_config folly_stubs hackfmt hackfmt_debug utils_config_file utils_ocaml_overrides)) (executable (name generate_full_fidelity) (modules generate_full_fidelity generate_full_fidelity_data) (link_flags (:standard (:include dune_config/ld-opts.sexp))) (libraries core_kernel str parser_schema collections utils_core)) (executable (name hh_single_fanout) (modules hh_single_fanout) (modes exe byte_complete) (link_flags (:standard (:include dune_config/ld-opts.sexp))) (libraries decl_redecl_service default_injector_config dep_hash_to_symbol direct_decl_service naming_table typing_check_job typing_deps) (preprocess (pps ppx_deriving.std))) (alias (name exe) (deps hackfmt.exe hh_client.exe hh_fanout/hh_fanout.exe hh_parse.exe hh_server.exe hh_single_decl.exe hh_single_type_check.exe hh_single_complete.exe hh_single_ai.exe hh_single_fanout.exe ai/zoncolan.exe)) (alias (name hh) (deps hh_server.exe hh_client.exe)) (alias (name single) (deps hh_single_type_check.exe)) (alias (name debug-single) (deps hh_single_type_check.bc.exe)) (alias (name debug) (deps hackfmt.bc.exe hh_client.bc.exe hh_fanout/hh_fanout.bc.exe hh_parse.bc.exe hh_server.bc.exe hh_single_type_check.bc.exe hh_single_complete.bc.exe hh_single_fanout.bc.exe hh_single_ai.bc.exe))
OCaml
hhvm/hphp/hack/src/fullFidelityParseArgs.ml
(* * Copyright (c) 2016, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) type t = { (* Output options *) full_fidelity_json_parse_tree: bool; full_fidelity_json: bool; full_fidelity_text_json: bool; full_fidelity_dot: bool; full_fidelity_dot_edges: bool; full_fidelity_errors: bool; full_fidelity_errors_all: bool; full_fidelity_ast_s_expr: bool; program_text: bool; pretty_print: bool; pretty_print_json: bool; generate_hhi: bool; schema: bool; show_file_name: bool; (* Configuring the parser *) codegen: bool; php5_compat_mode: bool; elaborate_namespaces: bool; include_line_comments: bool; quick_mode: bool; (* Defining the input *) files: string list; disable_lval_as_an_expression: bool; enable_class_level_where_clauses: bool; disable_legacy_soft_typehints: bool; allow_new_attribute_syntax: bool; disable_legacy_attribute_syntax: bool; const_default_func_args: bool; const_default_lambda_args: bool; const_static_props: bool; abstract_static_props: bool; disallow_func_ptrs_in_constants: bool; error_php_lambdas: bool; disallow_discarded_nullable_awaitables: bool; disable_xhp_element_mangling: bool; allow_unstable_features: bool; enable_xhp_class_modifier: bool; ignore_missing_json: bool; disallow_static_constants_in_default_func_args: bool; } let make full_fidelity_json_parse_tree full_fidelity_json full_fidelity_text_json full_fidelity_dot full_fidelity_dot_edges full_fidelity_errors full_fidelity_errors_all full_fidelity_ast_s_expr program_text pretty_print pretty_print_json generate_hhi schema codegen php5_compat_mode elaborate_namespaces include_line_comments quick_mode show_file_name files disable_lval_as_an_expression enable_class_level_where_clauses disable_legacy_soft_typehints allow_new_attribute_syntax disable_legacy_attribute_syntax const_default_func_args const_default_lambda_args const_static_props abstract_static_props disallow_func_ptrs_in_constants error_php_lambdas disallow_discarded_nullable_awaitables disable_xhp_element_mangling allow_unstable_features enable_xhp_class_modifier ignore_missing_json disallow_static_constants_in_default_func_args = { full_fidelity_json_parse_tree; full_fidelity_json; full_fidelity_dot; full_fidelity_dot_edges; full_fidelity_text_json; full_fidelity_errors; full_fidelity_errors_all; full_fidelity_ast_s_expr; program_text; pretty_print; pretty_print_json; generate_hhi; schema; codegen; php5_compat_mode; elaborate_namespaces; include_line_comments; quick_mode; show_file_name; files; disable_lval_as_an_expression; enable_class_level_where_clauses; disable_legacy_soft_typehints; allow_new_attribute_syntax; disable_legacy_attribute_syntax; const_default_func_args; const_default_lambda_args; const_static_props; abstract_static_props; disallow_func_ptrs_in_constants; error_php_lambdas; disallow_discarded_nullable_awaitables; disable_xhp_element_mangling; allow_unstable_features; enable_xhp_class_modifier; ignore_missing_json; disallow_static_constants_in_default_func_args; } let parse_args () = let usage = Printf.sprintf "Usage: %s [OPTIONS] filename\n" Sys.argv.(0) in let full_fidelity_json_parse_tree = ref false in let set_full_fidelity_json_parse_tree () = full_fidelity_json_parse_tree := true in let full_fidelity_json = ref false in let set_full_fidelity_json () = full_fidelity_json := true in let full_fidelity_text_json = ref false in let set_full_fidelity_text_json () = full_fidelity_text_json := true in let full_fidelity_dot = ref false in let set_full_fidelity_dot () = full_fidelity_dot := true in let full_fidelity_dot_edges = ref false in let set_full_fidelity_dot_edges () = full_fidelity_dot_edges := true in let full_fidelity_errors = ref false in let set_full_fidelity_errors () = full_fidelity_errors := true in let full_fidelity_errors_all = ref false in let set_full_fidelity_errors_all () = full_fidelity_errors_all := true in let full_fidelity_ast_s_expr = ref false in let set_full_fidelity_ast_s_expr () = full_fidelity_ast_s_expr := true in let program_text = ref false in let set_program_text () = program_text := true in let pretty_print = ref false in let set_pretty_print () = pretty_print := true in let pretty_print_json = ref false in let set_pretty_print_json () = pretty_print_json := true in let generate_hhi = ref false in let set_generate_hhi () = generate_hhi := true in let schema = ref false in let set_schema () = schema := true in let codegen = ref false in let php5_compat_mode = ref false in let elaborate_namespaces = ref true in let include_line_comments = ref false in let quick_mode = ref false in let enable_hh_syntax = ref false in let show_file_name = ref false in let disable_lval_as_an_expression = ref false in let set_show_file_name () = show_file_name := true in let files = ref [] in let push_file file = files := file :: !files in let enable_class_level_where_clauses = ref false in let disable_legacy_soft_typehints = ref false in let allow_new_attribute_syntax = ref false in let disable_legacy_attribute_syntax = ref false in let const_default_func_args = ref false in let const_default_lambda_args = ref false in let const_static_props = ref false in let abstract_static_props = ref false in let disallow_func_ptrs_in_constants = ref false in let error_php_lambdas = ref false in let disallow_discarded_nullable_awaitables = ref false in let disable_xhp_element_mangling = ref false in let allow_unstable_features = ref false in let enable_xhp_class_modifier = ref false in let ignore_missing_json = ref false in let disallow_static_constants_in_default_func_arg = ref false in let options = [ (* modes *) ( "--full-fidelity-json-parse-tree", Arg.Unit set_full_fidelity_json_parse_tree, "Displays the full-fidelity parse tree in JSON format." ); ( "--full-fidelity-json", Arg.Unit set_full_fidelity_json, "Displays the source text, FFP schema version, and parse tree in JSON format." ); ( "--full-fidelity-text-json", Arg.Unit set_full_fidelity_text_json, "Displays the source text, FFP schema version, and parse tree (with trivia) in JSON format." ); ( "--full-fidelity-dot", Arg.Unit set_full_fidelity_dot, "Displays the full-fidelity parse tree in GraphViz DOT format." ); ( "--full-fidelity-dot-edges", Arg.Unit set_full_fidelity_dot_edges, "Displays the full-fidelity parse tree in GraphViz DOT format with edge labels." ); ( "--full-fidelity-errors", Arg.Unit set_full_fidelity_errors, "Displays the full-fidelity parser errors, if any. Some errors may be filtered out." ); ( "--full-fidelity-errors-all", Arg.Unit set_full_fidelity_errors_all, "Displays the full-fidelity parser errors, if any. No errors are filtered out." ); ( "--full-fidelity-ast-s-expression", Arg.Unit set_full_fidelity_ast_s_expr, "Displays the AST produced by the FFP in S-expression format." ); ( "--program-text", Arg.Unit set_program_text, "Displays the text of the given file." ); ( "--generate-hhi", Arg.Unit set_generate_hhi, "Generate and display a .hhi file for the given input file." ); ( "--pretty-print", Arg.Unit set_pretty_print, "Displays the text of the given file after pretty-printing." ); ( "--pretty-print-json", Arg.Unit set_pretty_print_json, "Pretty print JSON output." ); ( "--schema", Arg.Unit set_schema, "Displays the parser version and schema of nodes." ); ("--codegen", Arg.Set codegen, "Set the codegen option for the parser."); ( "--no-codegen", Arg.Clear codegen, "Unset the codegen option for the parser." ); ( "--php5-compat-mode", Arg.Set php5_compat_mode, "Set the php5_compat_mode option for the parser." ); ( "--no-php5-compat-mode", Arg.Clear php5_compat_mode, "Unset the php5_compat_mode option for the parser." ); ( "--elaborate-namespaces", Arg.Set elaborate_namespaces, "Set the elaborate_namespaces option for the parser." ); ( "--no-elaborate-namespaces", Arg.Clear elaborate_namespaces, "Unset the elaborate_namespaces option for the parser." ); ( "--include-line-comments", Arg.Set include_line_comments, "Set the include_line_comments option for the parser." ); ( "--no-include-line-comments", Arg.Clear include_line_comments, "Unset the include_line_comments option for the parser." ); ( "--quick-mode", Arg.Set quick_mode, "Set the quick_mode option for the parser." ); ( "--no-quick-mode", Arg.Clear quick_mode, "Unset the quick_mode option for the parser." ); ("--fail-open", Arg.Unit (fun () -> ()), "Unused."); ("--no-fail-open", Arg.Unit (fun () -> ()), "Unused"); ("--force-hh-syntax", Arg.Set enable_hh_syntax, "Ignored. Do not use."); ( "--show-file-name", Arg.Unit set_show_file_name, "Displays the file name." ); ( "--disable-lval-as-an-expression", Arg.Set disable_lval_as_an_expression, "Disable lval as an expression." ); ( "--enable-class-level-where-clauses", Arg.Set enable_class_level_where_clauses, "Enables support for class-level where clauses" ); ( "--disable-legacy-soft-typehints", Arg.Set disable_legacy_soft_typehints, "Disables the legacy @ syntax for soft typehints (use __Soft instead)" ); ( "--allow-new-attribute-syntax", Arg.Set allow_new_attribute_syntax, "Allow the new @ attribute syntax (disables legacy soft typehints)" ); ( "--disable-legacy-attribute-syntax", Arg.Set disable_legacy_attribute_syntax, "Disable the legacy <<...>> user attribute syntax" ); ( "--const-default-func-args", Arg.Set const_default_func_args, "Statically check default function arguments are constant initializers" ); ( "--const-default-lambda-args", Arg.Set const_default_lambda_args, " Statically check default lambda args are constant." ^ " Produces a subset of errors of const-default-func-args" ); ( "--const-static-props", Arg.Set const_static_props, "Enable static properties to be const" ); ( "--abstract-static-props", Arg.Set abstract_static_props, "Enable abstract static properties" ); ( "--disallow-func-ptrs-in-constants", Arg.Set disallow_func_ptrs_in_constants, "Disallow use of HH\\fun and HH\\class_meth in constants and constant initializers" ); ( "--error-php-lambdas", Arg.Set error_php_lambdas, "Report errors on php style anonymous functions" ); ( "--disallow-discarded-nullable-awaitables", Arg.Set disallow_discarded_nullable_awaitables, "Error on using discarded nullable awaitables" ); ( "--enable-first-class-function-pointers", Arg.Unit (fun () -> ()), "Deprecated - delete in coordination with HackAST" ); ( "--enable-xhp-class-modifier", Arg.Set enable_xhp_class_modifier, "Enables the 'xhp class foo' syntax" ); ( "--disable-xhp-element-mangling", Arg.Set disable_xhp_element_mangling, "Disable mangling of XHP elements :foo. That is, :foo:bar is now \\foo\\bar, not xhp_foo__bar" ); ( "--allow-unstable-features", Arg.Set allow_unstable_features, "Enables the __EnableUnstableFeatures attribute" ); ( "--ignore-missing-json", Arg.Set ignore_missing_json, "Ignore missing nodes in JSON output" ); ( "--disallow-static-constants-in-default-func-args", Arg.Set disallow_static_constants_in_default_func_arg, "Disallow `static::*` in default arguments for functions" ); ] in Arg.parse options push_file usage; let modes = [ !full_fidelity_json_parse_tree; !full_fidelity_json; !full_fidelity_text_json; !full_fidelity_dot; !full_fidelity_dot_edges; !full_fidelity_errors; !full_fidelity_errors_all; !full_fidelity_ast_s_expr; !program_text; !pretty_print; !schema; ] in if not (List.exists (fun x -> x) modes) then full_fidelity_errors_all := true; make !full_fidelity_json_parse_tree !full_fidelity_json !full_fidelity_text_json !full_fidelity_dot !full_fidelity_dot_edges !full_fidelity_errors !full_fidelity_errors_all !full_fidelity_ast_s_expr !program_text !pretty_print !pretty_print_json !generate_hhi !schema !codegen !php5_compat_mode !elaborate_namespaces !include_line_comments !quick_mode !show_file_name (List.rev !files) !disable_lval_as_an_expression !enable_class_level_where_clauses !disable_legacy_soft_typehints !allow_new_attribute_syntax !disable_legacy_attribute_syntax !const_default_func_args !const_default_lambda_args !const_static_props !abstract_static_props !disallow_func_ptrs_in_constants !error_php_lambdas !disallow_discarded_nullable_awaitables !disable_xhp_element_mangling !allow_unstable_features !enable_xhp_class_modifier !ignore_missing_json !disallow_static_constants_in_default_func_arg let to_parser_options args = let popt = ParserOptions.default in let popt = ParserOptions.with_codegen popt args.codegen in let popt = ParserOptions.with_disable_lval_as_an_expression popt args.disable_lval_as_an_expression in let popt = { popt with GlobalOptions.po_enable_class_level_where_clauses = args.enable_class_level_where_clauses; } in let popt = ParserOptions.with_disable_legacy_soft_typehints popt args.disable_legacy_soft_typehints in let popt = ParserOptions.with_allow_new_attribute_syntax popt args.allow_new_attribute_syntax in let popt = ParserOptions.with_disable_legacy_attribute_syntax popt args.disable_legacy_attribute_syntax in let popt = ParserOptions.with_const_default_func_args popt args.const_default_func_args in let popt = ParserOptions.with_const_default_lambda_args popt args.const_default_lambda_args in let popt = ParserOptions.with_const_static_props popt args.const_static_props in let popt = ParserOptions.with_abstract_static_props popt args.abstract_static_props in let popt = ParserOptions.with_disallow_func_ptrs_in_constants popt args.disallow_func_ptrs_in_constants in let popt = ParserOptions.with_disable_xhp_element_mangling popt args.disable_xhp_element_mangling in let popt = ParserOptions.with_allow_unstable_features popt args.allow_unstable_features in let popt = ParserOptions.with_enable_xhp_class_modifier popt args.enable_xhp_class_modifier in let popt = ParserOptions.with_disallow_static_constants_in_default_func_args popt args.disallow_static_constants_in_default_func_args in popt let to_parser_env args ~leak_rust_tree ~mode = Full_fidelity_parser_env.make ~disable_lval_as_an_expression:args.disable_lval_as_an_expression ~disable_legacy_soft_typehints:args.disable_legacy_soft_typehints ~allow_new_attribute_syntax:args.allow_new_attribute_syntax ~disable_legacy_attribute_syntax:args.disable_legacy_attribute_syntax ~leak_rust_tree ?mode ()
OCaml
hhvm/hphp/hack/src/generate_full_fidelity.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 () = List.iter Generate_full_fidelity_data.templates ~f:Full_fidelity_schema.generate_file
OCaml
hhvm/hphp/hack/src/generate_full_fidelity_data.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 OcamlPrintf = Printf open Hh_prelude open Printf open Full_fidelity_schema let full_fidelity_path_prefix = "hphp/hack/src/parser/" let rust_keywords = [ "as"; "break"; "const"; "continue"; "crate"; "else"; "enum"; "extern"; "false"; "fn"; "for"; "if"; "impl"; "in"; "let"; "loop"; "match"; "mod"; "move"; "mut"; "pub"; "ref"; "return"; "self"; "Self"; "static"; "struct"; "super"; "trait"; "true"; "type"; "unsafe"; "use"; "where"; "while"; "async"; "await"; "dyn" ] [@@ocamlformat "disable"] let escape_rust_keyword field_name = if List.mem rust_keywords field_name ~equal:String.equal then sprintf "%s_" field_name else field_name type comment_style = | CStyle | MLStyle [@@deriving show] let make_header comment_style (header_comment : string) : string = let (open_char, close_char) = match comment_style with | CStyle -> ("/*", '/') | MLStyle -> ("(", ')') in sprintf "%s* * 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 @%s; DO NOT EDIT IT * To regenerate this file, run * * buck run //hphp/hack/src:generate_full_fidelity * ** *%s *%c" open_char (* Any file containing '@' followed by the word 'generated' is considered a * generated file in Phabricator. Cheeky trick to avoid making this script * being seen as generated. *) "generated" header_comment close_char type valign = (string -> string -> string, unit, string, string -> string) format4 let all_tokens = given_text_tokens @ variable_text_tokens @ no_text_tokens let align_fmt : 'a. ('a -> string) -> 'a list -> valign = fun f xs -> let folder acc x = max acc (String.length (f x)) in let width = List.fold_left ~f:folder ~init:0 xs in Scanf.format_from_string (sprintf "%%-%ds" width) "%-1s" let kind_name_fmt = align_fmt (fun x -> x.kind_name) schema let type_name_fmt = align_fmt (fun x -> x.type_name) schema let trivia_kind_fmt = align_fmt (fun x -> x.trivia_kind) trivia_kinds let token_kind_fmt = align_fmt (fun x -> x.token_kind) all_tokens let omit_syntax_record = let names = SSet.of_list [ "anonymous_function"; "closure_type_specifier"; "function_declaration"; "function_declaration_header"; "lambda_expression"; "lambda_signature"; "methodish_declaration"; ] in (fun x -> not (SSet.mem x.type_name names)) module GenerateFFSyntaxType = struct let to_parse_tree x = if omit_syntax_record x then "" else let field_width = 50 - String.length x.prefix in let fmt = sprintf "%s_%%-%ds: t\n" x.prefix field_width in let mapper (f, _) = sprintf (Scanf.format_from_string fmt "%-1s") f in let fields = map_and_concat_separated " ; " mapper x.fields in sprintf " and %s =\n { %s }\n" x.type_name fields let to_syntax x = let field_width = 50 - String.length x.prefix in let fmt = sprintf "%s_%%-%ds: t\n" x.prefix field_width in let mapper (f, _) = sprintf (Scanf.format_from_string fmt "%-1s") f in let fields = map_and_concat_separated " ; " mapper x.fields in sprintf (" | " ^^ kind_name_fmt ^^ " of\n { %s }\n") x.kind_name fields let to_aggregate_type x = let aggregated_types = aggregation_of x in let (prefix, trim) = aggregate_type_pfx_trim x in let compact = Str.global_replace (Str.regexp trim) "" in let valign = align_fmt (fun x -> compact x.kind_name) aggregated_types in let type_name = aggregate_type_name x in let make_constructor ty = sprintf ("%s" ^^ valign ^^ " of %s") prefix (compact ty.kind_name) ty.type_name in let type_body = List.map ~f:make_constructor aggregated_types in sprintf " and %s =\n | %s\n" type_name (String.concat ~sep:"\n | " type_body) let full_fidelity_syntax_template : string = make_header MLStyle " * 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] PARSE_TREE and syntax = | Token of Token.t | Missing | SyntaxList of t list SYNTAX [@@deriving sexp_of] end " let full_fidelity_syntax_type = Full_fidelity_schema.make_template_file ~transformations: [ { pattern = "PARSE_TREE"; func = to_parse_tree }; { pattern = "SYNTAX"; func = to_syntax }; ] ~aggregate_transformations: [ { aggregate_pattern = "AGGREGATE_TYPES"; aggregate_func = to_aggregate_type; }; ] ~filename:(full_fidelity_path_prefix ^ "full_fidelity_syntax_type.ml") ~template:full_fidelity_syntax_template () end module GenerateFFRustSyntaxImplByRef = struct let to_kind x = sprintf " SyntaxVariant::%s {..} => SyntaxKind::%s,\n" x.kind_name x.kind_name let template = make_header CStyle "" ^ " use crate::{syntax_kind::SyntaxKind, lexable_token::LexableToken}; use super::{syntax::Syntax, syntax_variant_generated::SyntaxVariant}; impl<T: LexableToken, V> Syntax<'_, T, V> { pub fn kind(&self) -> SyntaxKind { match &self.children { SyntaxVariant::Missing => SyntaxKind::Missing, SyntaxVariant::Token (t) => SyntaxKind::Token(t.kind()), SyntaxVariant::SyntaxList (_) => SyntaxKind::SyntaxList, TO_KIND } } } " let full_fidelity_syntax = Full_fidelity_schema.make_template_file ~transformations:[{ pattern = "TO_KIND"; func = to_kind }] ~filename: (full_fidelity_path_prefix ^ "syntax_by_ref/syntax_impl_generated.rs") ~template () end module GenerateSyntaxSerialize = struct let match_arm x = let get_field x = escape_rust_keyword (fst x) in let serialize_fields = map_and_concat_separated "\n" (fun y -> sprintf "ss.serialize_field(\"%s_%s\", &self.with(%s))?;" x.prefix (fst y) (get_field y)) x.fields in let fields = map_and_concat_separated "," get_field x.fields in sprintf "SyntaxVariant::%s (%sChildren{%s} ) => { let mut ss = s.serialize_struct(\"\", %d)?; ss.serialize_field(\"kind\", \"%s\")?; %s ss.end() } \n" x.kind_name x.kind_name fields (1 + List.length x.fields) x.description serialize_fields let template = make_header CStyle "" ^ " use super::{serialize::WithContext, syntax::Syntax, syntax_variant_generated::*}; use serde::{ser::SerializeStruct, Serialize, Serializer}; impl<'a, T, V> Serialize for WithContext<'a, Syntax<'a, T, V>> where T: 'a, WithContext<'a, T>: Serialize, { fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { match self.1.children { SyntaxVariant::Missing => { let mut ss = s.serialize_struct(\"\", 1)?; ss.serialize_field(\"kind\", \"missing\")?; ss.end() } SyntaxVariant::Token(ref t) => { let mut ss = s.serialize_struct(\"\", 2)?; ss.serialize_field(\"kind\", \"token\")?; ss.serialize_field(\"token\", &self.with(t))?; ss.end() } SyntaxVariant::SyntaxList(l) => { let mut ss = s.serialize_struct(\"\", 2)?; ss.serialize_field(\"kind\", \"list\")?; ss.serialize_field(\"elements\", &self.with(l))?; ss.end() } MATCH_ARMS } } } " let gen = Full_fidelity_schema.make_template_file ~transformations:[{ pattern = "MATCH_ARMS"; func = match_arm }] ~filename: (full_fidelity_path_prefix ^ "syntax_by_ref/syntax_serialize_generated.rs") ~template () end module GenerateFFRustSyntaxVariantByRef = struct let to_syntax_variant_children x = let mapper (f, _) = sprintf " pub %s: Syntax<'a, T, V>," (escape_rust_keyword f) in let fields = map_and_concat_separated "\n" mapper x.fields in sprintf "#[derive(Debug, Clone)]\npub struct %sChildren<'a, T, V> {\n%s\n}\n\n" x.kind_name fields let to_syntax_variant x = sprintf " %s(&'a %sChildren<'a, T, V>),\n" x.kind_name x.kind_name let full_fidelity_syntax_template = make_header CStyle "" ^ " use super::{ syntax::Syntax, syntax_children_iterator::SyntaxChildrenIterator, }; #[derive(Debug, Clone)] pub enum SyntaxVariant<'a, T, V> { Token(T), Missing, SyntaxList(&'a [Syntax<'a, T, V>]), SYNTAX_VARIANT} SYNTAX_CHILDREN impl<'a, T, V> SyntaxVariant<'a, T, V> { pub fn iter_children(&'a self) -> SyntaxChildrenIterator<'a, T, V> { SyntaxChildrenIterator { syntax: &self, index: 0, index_back: 0, } } } " let full_fidelity_syntax = Full_fidelity_schema.make_template_file ~transformations: [ { pattern = "SYNTAX_VARIANT"; func = to_syntax_variant }; { pattern = "SYNTAX_CHILDREN"; func = to_syntax_variant_children }; ] ~filename: (full_fidelity_path_prefix ^ "syntax_by_ref/syntax_variant_generated.rs") ~template:full_fidelity_syntax_template () end module GenerateSyntaxChildrenIterator = struct let to_iter_children x = let index = ref 0 in let mapper (f, _) = let res = sprintf "%d => Some(&x.%s)," !index (escape_rust_keyword f) in let () = incr index in res in let fields = map_and_concat_separated "\n " mapper x.fields in sprintf " %s(x) => { get_index(%d).and_then(|index| { match index { %s _ => None, } }) },\n" x.kind_name (List.length x.fields) fields let full_fidelity_syntax_template = make_header CStyle "" ^ " use super::{ syntax_children_iterator::*, syntax_variant_generated::*, syntax::* }; impl<'a, T, V> SyntaxChildrenIterator<'a, T, V> { pub fn next_impl(&mut self, direction : bool) -> Option<&'a Syntax<'a, T, V>> { use SyntaxVariant::*; let get_index = |len| { let back_index_plus_1 = len - self.index_back; if back_index_plus_1 <= self.index { return None } if direction { Some (self.index) } else { Some (back_index_plus_1 - 1) } }; let res = match self.syntax { Missing => None, Token (_) => None, SyntaxList(elems) => { get_index(elems.len()).and_then(|x| elems.get(x)) }, ITER_CHILDREN }; if res.is_some() { if direction { self.index = self.index + 1 } else { self.index_back = self.index_back + 1 } } res } } " let full_fidelity_syntax = Full_fidelity_schema.make_template_file ~transformations:[{ pattern = "ITER_CHILDREN"; func = to_iter_children }] ~filename: (full_fidelity_path_prefix ^ "syntax_by_ref/syntax_children_iterator_generated.rs") ~template:full_fidelity_syntax_template () end module GenerateSyntaxTypeImpl = struct let to_syntax_constructors x = let mapper (f, _) = sprintf "%s: Self" (escape_rust_keyword f) in let args = map_and_concat_separated ", " mapper x.fields in let mapper (f, _) = sprintf "%s" (escape_rust_keyword f) in let fields = map_and_concat_separated ",\n " mapper x.fields in sprintf " fn make_%s(ctx: &C, %s) -> Self { let syntax = SyntaxVariant::%s(ctx.get_arena().alloc(%sChildren { %s, })); let value = V::from_values(syntax.iter_children().map(|child| &child.value)); Self::make(syntax, value) }\n\n" x.type_name args x.kind_name x.kind_name fields let full_fidelity_syntax_template = make_header CStyle "" ^ " use super::{ has_arena::HasArena, syntax::*, syntax_variant_generated::*, }; use crate::{ lexable_token::LexableToken, syntax::{SyntaxType, SyntaxValueType}, }; impl<'a, C, T, V> SyntaxType<C> for Syntax<'a, T, V> where T: LexableToken + Copy, V: SyntaxValueType<T>, C: HasArena<'a>, { SYNTAX_CONSTRUCTORS } " let full_fidelity_syntax = Full_fidelity_schema.make_template_file ~transformations: [{ pattern = "SYNTAX_CONSTRUCTORS"; func = to_syntax_constructors }] ~filename: (full_fidelity_path_prefix ^ "syntax_by_ref/syntax_type_impl_generated.rs") ~template:full_fidelity_syntax_template () end module GenerateFFRustSyntax = struct let from_children x = let mapper prefix (f, _) = sprintf "%s_%s : (Box::new(ts.pop().unwrap()))" prefix f in let fields = map_and_concat_separated ",\n " (mapper x.prefix) x.fields in sprintf "SyntaxKind::%s => SyntaxVariant::%s { %s }," x.kind_name x.kind_name fields let to_kind x = sprintf " SyntaxVariant::%s {..} => SyntaxKind::%s,\n" x.kind_name x.kind_name let to_children x = let mapper prefix (f, _) = sprintf "&*%s_%s" prefix f in let fields2 = map_and_concat_separated ",\n " (mapper x.prefix) x.fields in let mapper prefix (f, _) = sprintf "ref %s_%s" prefix f in let fields = map_and_concat_separated ",\n " (mapper x.prefix) x.fields in sprintf "SyntaxVariant::%s { %s } => vec![%s]," x.kind_name fields fields2 let to_iter_children x = let index = ref 0 in let mapper prefix (f, _) = let res = sprintf "%d => Some(&x.%s_%s)," !index prefix f in let () = incr index in res in let fields = map_and_concat_separated "\n " (mapper x.prefix) x.fields in sprintf " %s(x) => { get_index(%d).and_then(|index| { match index { %s _ => None, } }) },\n" x.kind_name (List.length x.fields) fields let syntax_as_slice x = (* SAFETY: We have `#[repr(C)]` on all the children structs, and all their fields are of type Syntax. So a child struct with 3 fields should have the same layout as the array `[Syntax; 3]`, and it should be valid to take a slice of length 3 from a pointer to its first field. *) sprintf " SyntaxVariant::%s(x) => unsafe { std::slice::from_raw_parts(&x.%s_%s, %d) },\n" x.kind_name x.prefix (fst (List.hd_exn x.fields)) (List.length x.fields) let syntax_as_slice_mut x = (* SAFETY: As above in `syntax_as_slice` *) sprintf " SyntaxVariant::%s(x) => unsafe { std::slice::from_raw_parts_mut(&mut x.%s_%s, %d) },\n" x.kind_name x.prefix (fst (List.hd_exn x.fields)) (List.length x.fields) let fold_over_owned x = let fold_mapper prefix (f, _) = sprintf "let acc = f(%s_%s, acc)" prefix f in let fold_fields = map_and_concat_separated ";\n " (fold_mapper x.prefix) x.fields in let destructure_mapper prefix (f, _) = sprintf "%s_%s" prefix f in let destructure_fields = map_and_concat_separated ", " (destructure_mapper x.prefix) x.fields in sprintf " SyntaxVariant::%s(x) => { let %sChildren { %s } = *x; %s; acc },\n" x.kind_name x.kind_name destructure_fields fold_fields let to_syntax_variant x = sprintf " %s(Box<%sChildren<T, V>>),\n" x.kind_name x.kind_name let to_syntax_variant_children x = let mapper prefix (f, _) = sprintf " pub %s_%s: Syntax<T, V>," prefix f in let fields = map_and_concat_separated "\n" (mapper x.prefix) x.fields in (* NB: The `#[repr(C)]` here is required for the `from_raw_parts` and `from_raw_parts_mut` above (in `syntax_as_slice` and `syntax_as_slice_mut`) to be valid. *) sprintf "#[derive(Debug, Clone)]\n#[repr(C)]\npub struct %sChildren<T, V> {\n%s\n}\n\n" x.kind_name fields let to_syntax_constructors x = let mapper prefix (f, _) = sprintf "%s_%s: Self" prefix f in let args = map_and_concat_separated ", " (mapper x.prefix) x.fields in let mapper prefix (f, _) = sprintf "%s_%s" prefix f in let fields = map_and_concat_separated ",\n " (mapper x.prefix) x.fields in sprintf " fn make_%s(_: &C, %s) -> Self { let syntax = SyntaxVariant::%s(Box::new(%sChildren { %s, })); let value = V::from_values(syntax.iter_children().map(|child| &child.value)); Self::make(syntax, value) }\n\n" x.type_name args x.kind_name x.kind_name fields let to_syntax_from_children x = let mapper (f, _) = sprintf "%s_%s: ts.pop().unwrap(),\n " x.prefix f in let fields = map_and_concat mapper (List.rev x.fields) in sprintf " (SyntaxKind::%s, %d) => SyntaxVariant::%s(Box::new(%sChildren { %s })),\n" x.kind_name (List.length x.fields) x.kind_name x.kind_name fields let full_fidelity_syntax_template = make_header CStyle "" ^ " use crate::lexable_token::LexableToken; use crate::syntax::*; use crate::syntax_kind::SyntaxKind; impl<T, V, C> SyntaxType<C> for Syntax<T, V> where T: LexableToken, V: SyntaxValueType<T>, { SYNTAX_CONSTRUCTORS } impl<T, V> Syntax<T, V> where T: LexableToken, { pub fn fold_over_children_owned<U>( f: &dyn Fn(Self, U) -> U, acc: U, syntax: SyntaxVariant<T, V>, ) -> U { match syntax { SyntaxVariant::Missing => acc, SyntaxVariant::Token (_) => acc, SyntaxVariant::SyntaxList(elems) => { let mut acc = acc; for item in elems { acc = f(item, acc); } acc }, FOLD_OVER_CHILDREN_OWNED } } pub fn kind(&self) -> SyntaxKind { match &self.syntax { SyntaxVariant::Missing => SyntaxKind::Missing, SyntaxVariant::Token (t) => SyntaxKind::Token(t.kind()), SyntaxVariant::SyntaxList (_) => SyntaxKind::SyntaxList, TO_KIND } } pub fn from_children(kind : SyntaxKind, mut ts : Vec<Self>) -> SyntaxVariant<T, V> { match (kind, ts.len()) { (SyntaxKind::Missing, 0) => SyntaxVariant::Missing, (SyntaxKind::SyntaxList, _) => SyntaxVariant::SyntaxList(ts), SYNTAX_FROM_CHILDREN _ => panic!(\"from_children called with wrong number of children\"), } } pub fn children(&self) -> &[Self] { match &self.syntax { SyntaxVariant::Missing => &[], SyntaxVariant::Token(..) => &[], SyntaxVariant::SyntaxList(l) => l.as_slice(), SYNTAX_AS_SLICE } } pub fn children_mut(&mut self) -> &mut [Self] { match &mut self.syntax { SyntaxVariant::Missing => &mut [], SyntaxVariant::Token(..) => &mut [], SyntaxVariant::SyntaxList(l) => l.as_mut_slice(), SYNTAX_AS_SLICE_MUT } } } SYNTAX_CHILDREN #[derive(Debug, Clone)] pub enum SyntaxVariant<T, V> { Token(Box<T>), Missing, SyntaxList(Vec<Syntax<T, V>>), SYNTAX_VARIANT} impl<'a, T, V> SyntaxChildrenIterator<'a, T, V> { pub fn next_impl(&mut self, direction : bool) -> Option<&'a Syntax<T, V>> { use SyntaxVariant::*; let get_index = |len| { let back_index_plus_1 = len - self.index_back; if back_index_plus_1 <= self.index { return None } if direction { Some (self.index) } else { Some (back_index_plus_1 - 1) } }; let res = match &self.syntax { Missing => None, Token (_) => None, SyntaxList(elems) => { get_index(elems.len()).and_then(|x| elems.get(x)) }, ITER_CHILDREN }; if res.is_some() { if direction { self.index = self.index + 1 } else { self.index_back = self.index_back + 1 } } res } } " let full_fidelity_syntax = Full_fidelity_schema.make_template_file ~transformations: [ { pattern = "SYNTAX_VARIANT"; func = to_syntax_variant }; { pattern = "SYNTAX_CHILDREN"; func = to_syntax_variant_children }; { pattern = "SYNTAX_CONSTRUCTORS"; func = to_syntax_constructors }; { pattern = "ITER_CHILDREN"; func = to_iter_children }; { pattern = "FOLD_OVER_CHILDREN_OWNED"; func = fold_over_owned }; { pattern = "TO_KIND"; func = to_kind }; { pattern = "SYNTAX_FROM_CHILDREN"; func = to_syntax_from_children }; { pattern = "SYNTAX_AS_SLICE"; func = syntax_as_slice }; { pattern = "SYNTAX_AS_SLICE_MUT"; func = syntax_as_slice_mut }; ] ~filename:(full_fidelity_path_prefix ^ "syntax_generated.rs") ~template:full_fidelity_syntax_template () end (* GenerateFFRustSyntax *) module GenerateFFRustSyntaxType = struct let to_kind x = sprintf " SyntaxVariant::%s {..} => SyntaxKind::%s,\n" x.kind_name x.kind_name let to_children x = let mapper prefix (f, _) = sprintf "&*%s_%s" prefix f in let fields2 = map_and_concat_separated ",\n " (mapper x.prefix) x.fields in let mapper prefix (f, _) = sprintf "ref %s_%s" prefix f in let fields = map_and_concat_separated ",\n " (mapper x.prefix) x.fields in sprintf "SyntaxVariant::%s { %s } => vec![%s]," x.kind_name fields fields2 let into_children x = let mapper prefix (f, _) = sprintf "x.%s_%s" prefix f in let fields = map_and_concat_separated ",\n " (mapper x.prefix) x.fields in sprintf " SyntaxVariant::%s (x) => { vec!( %s )},\n" x.kind_name fields let fold_over x = let mapper prefix (f, _) = sprintf "let acc = f(&x.%s_%s, acc)" prefix f in let fields = map_and_concat_separated ";\n " (mapper x.prefix) x.fields in sprintf " SyntaxVariant::%s(x) => { %s; acc },\n" x.kind_name fields let to_syntax_constructors x = let mapper prefix (f, _) = sprintf "%s_%s: Self" prefix f in let args = map_and_concat_separated ", " (mapper x.prefix) x.fields in sprintf " fn make_%s(ctx: &C, %s) -> Self;\n" x.type_name args let full_fidelity_syntax_template = make_header CStyle "" ^ " use crate::syntax::*; pub trait SyntaxType<C>: SyntaxTypeBase<C> { SYNTAX_CONSTRUCTORS } " let full_fidelity_syntax = Full_fidelity_schema.make_template_file ~transformations: [{ pattern = "SYNTAX_CONSTRUCTORS"; func = to_syntax_constructors }] ~filename:(full_fidelity_path_prefix ^ "syntax_type.rs") ~template:full_fidelity_syntax_template () end (* GenerateFFRustSyntaxType *) module GenerateFFSyntaxSig = struct let to_constructor_methods x = let mapper1 (_f, _) = " t ->" in let fields1 = map_and_concat mapper1 x.fields in sprintf " val make_%s :%s t\n" x.type_name fields1 let to_type_tests x = sprintf " val is_%s : t -> bool\n" x.type_name let to_syntax x = let field_width = 50 - String.length x.prefix in let fmt = sprintf "%s_%%-%ds: t\n" x.prefix field_width in let mapper (f, _) = sprintf (Scanf.format_from_string fmt "%-1s") f in let fields = map_and_concat_separated " ; " mapper x.fields in sprintf (" | " ^^ kind_name_fmt ^^ " of\n { %s }\n") x.kind_name fields let full_fidelity_syntax_template : string = make_header MLStyle " * This module contains a signature which can be used to describe the public * surface area of a constructable syntax tree. " ^ " module TriviaKind = Full_fidelity_trivia_kind module TokenKind = Full_fidelity_token_kind module type Syntax_S = sig module Token : Lexable_token_sig.LexableToken_S type value [@@deriving show, eq, sexp_of] type t = { syntax : syntax ; value : value } [@@deriving show, eq, sexp_of] and syntax = | Token of Token.t | Missing | SyntaxList of t list SYNTAX [@@deriving sexp_of] val rust_parse : Full_fidelity_source_text.t -> Full_fidelity_parser_env.t -> unit * t * Full_fidelity_syntax_error.t list * Rust_pointer.t option val rust_parser_errors : Full_fidelity_source_text.t -> Rust_pointer.t -> ParserOptions.ffi_t -> Full_fidelity_syntax_error.t list val has_leading_trivia : TriviaKind.t -> Token.t -> bool val to_json : ?with_value:bool -> ?ignore_missing:bool -> t -> Hh_json.json val extract_text : t -> string option val is_in_body : t -> int -> bool val syntax_node_to_list : t -> t list val width : t -> int val full_width : t -> int val trailing_width : t -> int val leading_width : t -> int val leading_token : t -> Token.t option val children : t -> t list val syntax : t -> syntax val kind : t -> Full_fidelity_syntax_kind.t val value : t -> value val make_token : Token.t -> t val get_token : t -> Token.t option val all_tokens : t -> Token.t list val make_missing : Full_fidelity_source_text.t -> int -> t val make_list : Full_fidelity_source_text.t -> int -> t list -> t val is_namespace_prefix : t -> bool val syntax_list_fold : init:'a -> f:('a -> t -> 'a) -> t -> 'a CONSTRUCTOR_METHODS val position : Relative_path.t -> t -> Pos.t option val offset : t -> int option val is_missing : t -> bool val is_list : t -> bool TYPE_TESTS val is_specific_token : TokenKind.t -> t -> bool val is_loop_statement : t -> bool val is_external : t -> bool val is_name : t -> bool val is_construct : t -> bool val is_static : t -> bool val is_private : t -> bool val is_public : t -> bool val is_protected : t -> bool val is_abstract : t -> bool val is_final : t -> bool val is_async : t -> bool val is_void : t -> bool val is_left_brace : t -> bool val is_ellipsis : t -> bool val is_comma : t -> bool val is_ampersand : t -> bool val is_inout : t -> bool end " let full_fidelity_syntax_sig = Full_fidelity_schema.make_template_file ~transformations: [ { pattern = "SYNTAX"; func = to_syntax }; { pattern = "CONSTRUCTOR_METHODS"; func = to_constructor_methods }; { pattern = "TYPE_TESTS"; func = to_type_tests }; ] ~filename:(full_fidelity_path_prefix ^ "syntax_sig.ml") ~template:full_fidelity_syntax_template () end (* GenerateFFSyntaxSig *) module GenerateFFSmartConstructors = struct let full_fidelity_smart_constructors_template : string = make_header MLStyle " * This module contains a signature which can be used to describe smart * constructors. " ^ " module ParserEnv = Full_fidelity_parser_env module type SmartConstructors_S = sig module Token : Lexable_token_sig.LexableToken_S type t (* state *) [@@deriving show, sexp_of] type r (* smart constructor return type *) [@@deriving show] val rust_parse : Full_fidelity_source_text.t -> ParserEnv.t -> t * r * Full_fidelity_syntax_error.t list * Rust_pointer.t option val initial_state : ParserEnv.t -> t end " let full_fidelity_smart_constructors = Full_fidelity_schema.make_template_file ~transformations:[] ~filename: (full_fidelity_path_prefix ^ "smart_constructors/smartConstructors.ml") ~template:full_fidelity_smart_constructors_template () end (* GenerateFFSmartConstructors *) module GenerateFFRustSmartConstructors = struct let to_make_methods x = let fields = List.mapi x.fields ~f:(fun i _ -> "arg" ^ string_of_int i ^ ": Self::Output") in let stack = String.concat ~sep:", " fields in sprintf " fn make_%s(&mut self, %s) -> Self::Output;\n" x.type_name stack let full_fidelity_smart_constructors_template : string = make_header CStyle "" ^ " use parser_core_types::token_factory::TokenFactory; use parser_core_types::lexable_token::LexableToken; pub type Token<S> = <<S as SmartConstructors>::Factory as TokenFactory>::Token; pub type Trivia<S> = <Token<S> as LexableToken>::Trivia; pub trait SmartConstructors: Clone { type Factory: TokenFactory; type State; type Output; fn state_mut(&mut self) -> &mut Self::State; fn into_state(self) -> Self::State; fn token_factory_mut(&mut self) -> &mut Self::Factory; fn make_missing(&mut self, offset : usize) -> Self::Output; fn make_token(&mut self, arg0: Token<Self>) -> Self::Output; fn make_list(&mut self, arg0: Vec<Self::Output>, offset: usize) -> Self::Output; fn begin_enumerator(&mut self) {} fn begin_enum_class_enumerator(&mut self) {} fn begin_constant_declarator(&mut self) {} MAKE_METHODS } " let full_fidelity_smart_constructors = Full_fidelity_schema.make_template_file ~transformations:[{ pattern = "MAKE_METHODS"; func = to_make_methods }] ~filename:(full_fidelity_path_prefix ^ "smart_constructors_generated.rs") ~template:full_fidelity_smart_constructors_template () end (* GenerateFFRustSmartConstructors *) module GenerateFFRustPositionedSmartConstructors = struct let to_constructor_methods x = let args = List.mapi x.fields ~f:(fun i _ -> sprintf "arg%d: Self::Output" i) in let args = String.concat ~sep:", " args in let fwd_args = List.mapi x.fields ~f:(fun i _ -> sprintf "arg%d" i) in let fwd_args = String.concat ~sep:", " fwd_args in sprintf " fn make_%s(&mut self, %s) -> Self::Output { <Self as SyntaxSmartConstructors<S, TF, St>>::make_%s(self, %s) }\n\n" x.type_name args x.type_name fwd_args let positioned_smart_constructors_template : string = make_header CStyle "" ^ " use parser_core_types::{ syntax::*, lexable_token::LexableToken, token_factory::TokenFactory, }; use smart_constructors::SmartConstructors; use syntax_smart_constructors::{SyntaxSmartConstructors, StateType}; #[derive(Clone)] pub struct PositionedSmartConstructors<S, TF, St: StateType<S>> { pub state: St, token_factory: TF, phantom_s: std::marker::PhantomData<S>, } impl<S, TF, St: StateType<S>> PositionedSmartConstructors<S, TF, St> { pub fn new(state: St, token_factory: TF) -> Self { Self { state, token_factory, phantom_s: std::marker::PhantomData } } } impl<S, TF, St> SyntaxSmartConstructors<S, TF, St> for PositionedSmartConstructors<S, TF, St> where TF: TokenFactory<Token = S::Token>, St: StateType<S>, S: SyntaxType<St> + Clone, S::Token: LexableToken, {} impl<S, TF, St> SmartConstructors for PositionedSmartConstructors<S, TF, St> where TF: TokenFactory<Token = S::Token>, S::Token: LexableToken, S: SyntaxType<St> + Clone, St: StateType<S>, { type Factory = TF; type State = St; type Output = S; fn state_mut(&mut self) -> &mut St { &mut self.state } fn into_state(self) -> St { self.state } fn token_factory_mut(&mut self) -> &mut Self::Factory { &mut self.token_factory } fn make_missing(&mut self, offset: usize) -> Self::Output { <Self as SyntaxSmartConstructors<S, TF, St>>::make_missing(self, offset) } fn make_token(&mut self, offset: <Self::Factory as TokenFactory>::Token) -> Self::Output { <Self as SyntaxSmartConstructors<S, TF, St>>::make_token(self, offset) } fn make_list(&mut self, lst: Vec<Self::Output>, offset: usize) -> Self::Output { <Self as SyntaxSmartConstructors<S, TF, St>>::make_list(self, lst, offset) } CONSTRUCTOR_METHODS} " let positioned_smart_constructors = Full_fidelity_schema.make_template_file ~transformations: [{ pattern = "CONSTRUCTOR_METHODS"; func = to_constructor_methods }] ~filename:(full_fidelity_path_prefix ^ "positioned_smart_constructors.rs") ~template:positioned_smart_constructors_template () end module GenerateFFSyntaxSmartConstructors = struct let full_fidelity_syntax_smart_constructors_template : string = make_header MLStyle " * This module contains smart constructors implementation that can be used to * build AST. " ^ " open Sexplib.Std module type SC_S = SmartConstructors.SmartConstructors_S module ParserEnv = Full_fidelity_parser_env module type State_S = sig type r [@@deriving show] type t [@@deriving show, sexp_of] val initial : ParserEnv.t -> t val next : t -> r list -> t end module type RustParser_S = sig type t type r val rust_parse : Full_fidelity_source_text.t -> ParserEnv.t -> t * r * Full_fidelity_syntax_error.t list * Rust_pointer.t option end module WithSyntax (Syntax : Syntax_sig.Syntax_S) = struct module WithState (State : State_S with type r = Syntax.t) = struct module WithRustParser (RustParser : RustParser_S with type t = State.t with type r = Syntax.t) = struct module Token = Syntax.Token type t = State.t [@@deriving show, sexp_of] type r = Syntax.t [@@deriving show] let rust_parse = RustParser.rust_parse let initial_state = State.initial end end include WithState (struct type r = Syntax.t [@@deriving show] type t = unit [@@deriving show, sexp_of] let initial _ = () let next () _ = () end) include WithRustParser (struct type r = Syntax.t type t = unit let rust_parse = Syntax.rust_parse end) end " let full_fidelity_syntax_smart_constructors = Full_fidelity_schema.make_template_file ~transformations:[] ~filename: (full_fidelity_path_prefix ^ "smart_constructors/syntaxSmartConstructors.ml") ~template:full_fidelity_syntax_smart_constructors_template () end (* GenerateFFSyntaxSmartConstructors *) module GenerateFFRustSyntaxSmartConstructors = struct let to_constructor_methods x = let params = List.mapi x.fields ~f:(fun i _ -> sprintf "arg%d : Self::Output" i) in let params = String.concat ~sep:", " params in let args = List.mapi x.fields ~f:(fun i _ -> sprintf "arg%d" i) in let args = String.concat ~sep:", " args in let next_args = List.mapi x.fields ~f:(fun i _ -> sprintf "&arg%d" i) in let next_args = String.concat ~sep:", " next_args in sprintf " fn make_%s(&mut self, %s) -> Self::Output { self.state_mut().next(&[%s]); Self::Output::make_%s(self.state_mut(), %s) }\n\n" x.type_name params next_args x.type_name args let full_fidelity_syntax_smart_constructors_template : string = make_header CStyle "" ^ " use parser_core_types::{ syntax::*, token_factory::TokenFactory, }; use smart_constructors::{NoState, SmartConstructors}; use crate::StateType; pub trait SyntaxSmartConstructors<S: SyntaxType<St>, TF: TokenFactory<Token = S::Token>, St = NoState>: SmartConstructors<State = St, Output=S, Factory = TF> where St: StateType<S>, { fn make_missing(&mut self, offset: usize) -> Self::Output { let r = Self::Output::make_missing(self.state_mut(), offset); self.state_mut().next(&[]); r } fn make_token(&mut self, arg: <Self::Factory as TokenFactory>::Token) -> Self::Output { let r = Self::Output::make_token(self.state_mut(), arg); self.state_mut().next(&[]); r } fn make_list(&mut self, items: Vec<Self::Output>, offset: usize) -> Self::Output { if items.is_empty() { <Self as SyntaxSmartConstructors<S, TF, St>>::make_missing(self, offset) } else { let item_refs: Vec<_> = items.iter().collect(); self.state_mut().next(&item_refs); Self::Output::make_list(self.state_mut(), items, offset) } } CONSTRUCTOR_METHODS} " let full_fidelity_syntax_smart_constructors = Full_fidelity_schema.make_template_file ~transformations: [{ pattern = "CONSTRUCTOR_METHODS"; func = to_constructor_methods }] ~filename: (full_fidelity_path_prefix ^ "syntax_smart_constructors_generated.rs") ~template:full_fidelity_syntax_smart_constructors_template () end (* GenerateFFRustSyntaxSmartConstructors *) module GenerateFFRustDeclModeSmartConstructors = struct let to_constructor_methods x = let args = List.mapi x.fields ~f:(fun i _ -> sprintf "arg%d: Self::Output" i) in let args = String.concat ~sep:", " args in let fwd_args = List.mapi x.fields ~f:(fun i _ -> sprintf "arg%d" i) in let fwd_args = String.concat ~sep:", " fwd_args in sprintf " fn make_%s(&mut self, %s) -> Self::Output { <Self as SyntaxSmartConstructors<Self::Output, Self::Factory, State<'_, '_, Self::Output>>>::make_%s(self, %s) }\n\n" x.type_name args x.type_name fwd_args let decl_mode_smart_constructors_template : string = make_header CStyle "" ^ " 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) } CONSTRUCTOR_METHODS} " let decl_mode_smart_constructors = Full_fidelity_schema.make_template_file ~transformations: [{ pattern = "CONSTRUCTOR_METHODS"; func = to_constructor_methods }] ~filename: (full_fidelity_path_prefix ^ "decl_mode_smart_constructors_generated.rs") ~template:decl_mode_smart_constructors_template () end (* GenerateFFRustDeclModeSmartConstructors *) module GenerateRustFlattenSmartConstructors = struct let to_constructor_methods x = let args = List.mapi x.fields ~f:(fun i _ -> sprintf "arg%d: Self::Output" i) in let args = String.concat ~sep:", " args in let if_cond = List.mapi x.fields ~f:(fun i _ -> sprintf "Self::is_zero(&arg%d)" i) in let if_cond = String.concat ~sep:" && " if_cond in let flatten_args = List.mapi x.fields ~f:(fun i _ -> sprintf "arg%d" i) in let flatten_args = String.concat ~sep:", " flatten_args in sprintf " fn make_%s(&mut self, %s) -> Self::Output { if %s { Self::zero(SyntaxKind::%s) } else { self.flatten(SyntaxKind::%s, vec!(%s)) } }\n\n" x.type_name args if_cond x.kind_name x.kind_name flatten_args let flatten_smart_constructors_template : string = make_header CStyle "" ^ " 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) {} CONSTRUCTOR_METHODS} " let flatten_smart_constructors = Full_fidelity_schema.make_template_file ~transformations: [{ pattern = "CONSTRUCTOR_METHODS"; func = to_constructor_methods }] ~filename:(full_fidelity_path_prefix ^ "flatten_smart_constructors.rs") ~template:flatten_smart_constructors_template () end (* GenerateRustFlattenSmartConstructors *) module GenerateRustDirectDeclSmartConstructors = struct let to_constructor_methods x = let args = List.map x.fields ~f:(fun (name, _) -> sprintf "%s: Self::Output" (escape_rust_keyword name)) in let args = String.concat ~sep:", " args in let fwd_args = List.map x.fields ~f:(fun (name, _) -> escape_rust_keyword name) in let fwd_args = String.concat ~sep:", " fwd_args in sprintf " fn make_%s(&mut self, %s) -> Self::Output { <Self as FlattenSmartConstructors>::make_%s(self, %s) }\n\n" x.type_name args x.type_name fwd_args let direct_decl_smart_constructors_template : string = make_header CStyle "" ^ " use flatten_smart_constructors::*; use parser_core_types::compact_token::CompactToken; use parser_core_types::token_factory::SimpleTokenFactoryImpl; use smart_constructors::SmartConstructors; use crate::{DirectDeclSmartConstructors, Node, SourceTextAllocator}; impl<'a, 'o, 't, S: SourceTextAllocator<'t, 'a>> SmartConstructors for DirectDeclSmartConstructors<'a, 'o, 't, S> { type State = Self; type Factory = SimpleTokenFactoryImpl<CompactToken>; type Output = Node<'a>; fn state_mut(&mut self) -> &mut Self { self } fn into_state(self) -> Self { self } fn token_factory_mut(&mut self) -> &mut Self::Factory { &mut self.token_factory } fn make_missing(&mut self, offset: usize) -> Self::Output { <Self as FlattenSmartConstructors>::make_missing(self, offset) } fn make_token(&mut self, token: CompactToken) -> Self::Output { <Self as FlattenSmartConstructors>::make_token(self, token) } fn make_list(&mut self, items: Vec<Self::Output>, offset: usize) -> Self::Output { <Self as FlattenSmartConstructors>::make_list(self, items, offset) } fn begin_enumerator(&mut self) { <Self as FlattenSmartConstructors>::begin_enumerator(self) } fn begin_enum_class_enumerator(&mut self) { <Self as FlattenSmartConstructors>::begin_enum_class_enumerator(self) } fn begin_constant_declarator(&mut self) { <Self as FlattenSmartConstructors>::begin_constant_declarator(self) } CONSTRUCTOR_METHODS} " let direct_decl_smart_constructors = Full_fidelity_schema.make_template_file ~transformations: [{ pattern = "CONSTRUCTOR_METHODS"; func = to_constructor_methods }] ~filename: (full_fidelity_path_prefix ^ "../decl/direct_decl_smart_constructors_generated.rs") ~template:direct_decl_smart_constructors_template () end (* GenerateRustDirectDeclSmartConstructors *) module GenerateRustPairSmartConstructors = struct let to_constructor_methods x = let args = List.map x.fields ~f:(fun (name, _) -> sprintf "%s: Self::Output" (escape_rust_keyword name)) in let args = String.concat ~sep:", " args in let fwd_args = List.map x.fields ~f:(fun (name, _) -> escape_rust_keyword name) in let fwd_args idx = List.map fwd_args ~f:(fun name -> name ^ "." ^ idx) |> String.concat ~sep:", " in sprintf " fn make_%s(&mut self, %s) -> Self::Output { Node(self.0.make_%s(%s), self.1.make_%s(%s)) }\n\n" x.type_name args x.type_name (fwd_args "0") x.type_name (fwd_args "1") let pair_smart_constructors_template : string = make_header CStyle "" ^ " use parser_core_types::token_factory::TokenFactory; use smart_constructors::{NodeType, SmartConstructors}; use crate::{PairTokenFactory, Node}; #[derive(Clone)] pub struct PairSmartConstructors<SC0, SC1>(pub SC0, pub SC1, PairTokenFactory<SC0::Factory, SC1::Factory>) where SC0: SmartConstructors, SC0::Output: NodeType, SC1: SmartConstructors, SC1::Output: NodeType; impl<SC0, SC1> PairSmartConstructors<SC0, SC1> where SC0: SmartConstructors, SC0::Output: NodeType, SC1: SmartConstructors, SC1::Output: NodeType, { pub fn new(mut sc0: SC0, mut sc1: SC1) -> Self { let tf0 = sc0.token_factory_mut().clone(); let tf1 = sc1.token_factory_mut().clone(); let tf = PairTokenFactory::new(tf0, tf1); Self(sc0, sc1, tf) } } impl<SC0, SC1> SmartConstructors for PairSmartConstructors<SC0, SC1> where SC0: SmartConstructors, SC0::Output: NodeType, SC1: SmartConstructors, SC1::Output: NodeType, { type State = Self; type Factory = PairTokenFactory<SC0::Factory, SC1::Factory>; type Output = Node<SC0::Output, SC1::Output>; fn state_mut(&mut self) -> &mut Self { self } fn into_state(self) -> Self { self } fn token_factory_mut(&mut self) -> &mut Self::Factory { &mut self.2 } fn make_missing(&mut self, offset: usize) -> Self::Output { Node(self.0.make_missing(offset), self.1.make_missing(offset)) } fn make_token(&mut self, token: <Self::Factory as TokenFactory>::Token) -> Self::Output { Node(self.0.make_token(token.0), self.1.make_token(token.1)) } fn make_list(&mut self, items: Vec<Self::Output>, offset: usize) -> Self::Output { let (items0, items1) = items.into_iter().map(|n| (n.0, n.1)).unzip(); Node(self.0.make_list(items0, offset), self.1.make_list(items1, offset)) } CONSTRUCTOR_METHODS} " let pair_smart_constructors = Full_fidelity_schema.make_template_file ~transformations: [{ pattern = "CONSTRUCTOR_METHODS"; func = to_constructor_methods }] ~filename: (full_fidelity_path_prefix ^ "pair_smart_constructors_generated.rs") ~template:pair_smart_constructors_template () end (* GenerateRustPairSmartConstructors *) module GenerateFFSmartConstructorsWrappers = struct let full_fidelity_smart_constructors_wrappers_template : string = make_header MLStyle " * This module contains smart constructors implementation that can be used to * build AST. " ^ " module type SC_S = SmartConstructors.SmartConstructors_S module SK = Full_fidelity_syntax_kind module type SyntaxKind_S = sig include SC_S type original_sc_r [@@deriving show] end module SyntaxKind (SC : SC_S) : SyntaxKind_S with module Token = SC.Token and type original_sc_r = SC.r and type t = SC.t = struct module Token = SC.Token type original_sc_r = SC.r [@@deriving show] type t = SC.t [@@deriving show, sexp_of] type r = SK.t * SC.r [@@deriving show] let compose : SK.t -> t * SC.r -> t * r = (fun kind (state, res) -> (state, (kind, res))) let rust_parse text env = let (state, res, errors, pointer) = SC.rust_parse text env in let (state, res) = compose SK.Script (state, res) in (state, res, errors, pointer) let initial_state = SC.initial_state end " let full_fidelity_smart_constructors_wrappers = Full_fidelity_schema.make_template_file ~transformations:[] ~filename: (full_fidelity_path_prefix ^ "smart_constructors/smartConstructorsWrappers.ml") ~template:full_fidelity_smart_constructors_wrappers_template () end (* GenerateFFSmartConstructorsWrappers *) module GenerateFFRustSmartConstructorsWrappers = struct let to_constructor_methods x = let params = List.mapi x.fields ~f:(fun i _ -> "arg" ^ string_of_int i ^ " : Self::Output") in let params = String.concat ~sep:", " params in let args = List.mapi x.fields ~f:(fun i _ -> sprintf "arg%d" i) in let raw_args = map_and_concat_separated ", " (fun x -> x ^ ".1") args in sprintf " fn make_%s(&mut self, %s) -> Self::Output { compose(SyntaxKind::%s, self.s.make_%s(%s)) }\n" x.type_name params x.kind_name x.type_name raw_args let full_fidelity_smart_constructors_wrappers_template : string = make_header CStyle "" ^ " // This module contains smart constructors implementation that can be used to // build AST. " ^ " use parser_core_types::{ lexable_token::LexableToken, syntax_kind::SyntaxKind, token_factory::TokenFactory, }; use crate::SmartConstructors; #[derive(Clone)] pub struct WithKind<S> { s: S, } impl<S> WithKind<S> { pub fn new(s: S) -> Self { Self { s } } } impl<S, St> SmartConstructors for WithKind<S> where S: SmartConstructors<State = St>, { type Factory = S::Factory; type State = St; type Output = (SyntaxKind, S::Output); fn state_mut(&mut self) -> &mut St { self.s.state_mut() } fn into_state(self) -> St { self.s.into_state() } fn token_factory_mut(&mut self) -> &mut Self::Factory { self.s.token_factory_mut() } fn make_token(&mut self, token: <Self::Factory as TokenFactory>::Token) -> Self::Output { compose(SyntaxKind::Token(token.kind()), self.s.make_token(token)) } fn make_missing(&mut self, p: usize) -> Self::Output { compose(SyntaxKind::Missing, self.s.make_missing(p)) } fn make_list(&mut self, items: Vec<Self::Output>, p: usize) -> Self::Output { let kind = if items.is_empty() { SyntaxKind::Missing } else { SyntaxKind::SyntaxList }; compose(kind, self.s.make_list(items.into_iter().map(|x| x.1).collect(), p)) } CONSTRUCTOR_METHODS } #[inline(always)] fn compose<R>(kind: SyntaxKind, r: R) -> (SyntaxKind, R) { (kind, r) } " let full_fidelity_smart_constructors_wrappers = Full_fidelity_schema.make_template_file ~transformations: [{ pattern = "CONSTRUCTOR_METHODS"; func = to_constructor_methods }] ~filename:(full_fidelity_path_prefix ^ "smart_constructors_wrappers.rs") ~template:full_fidelity_smart_constructors_wrappers_template () end (* GenerateFFRustSmartConstructorsWrappers *) module GenerateFFSyntax = struct let to_to_kind x = sprintf (" | " ^^ kind_name_fmt ^^ " _ -> SyntaxKind.%s\n") x.kind_name x.kind_name let to_type_tests x = sprintf (" let is_" ^^ type_name_fmt ^^ " = has_kind SyntaxKind.%s\n") x.type_name x.kind_name let to_children x = let mapper (f, _) = sprintf " %s_%s;\n" x.prefix f in let fields = map_and_concat mapper x.fields in sprintf " | %s {\n%s } -> [\n%s ]\n" x.kind_name fields fields let to_fold_from_syntax x = let mapper (f, _) = sprintf " %s_%s;\n" x.prefix f in let fields = map_and_concat mapper x.fields in let mapper2 (f, _) = sprintf " let acc = f acc %s_%s in\n" x.prefix f in let fields2 = map_and_concat mapper2 x.fields in sprintf " | %s {\n%s } ->\n%s acc\n" x.kind_name fields fields2 let to_children_names x = let mapper1 (f, _) = sprintf " %s_%s;\n" x.prefix f in let mapper2 (f, _) = sprintf " \"%s_%s\";\n" x.prefix f in let fields1 = map_and_concat mapper1 x.fields in let fields2 = map_and_concat mapper2 x.fields in sprintf " | %s {\n%s } -> [\n%s ]\n" x.kind_name fields1 fields2 let to_syntax_from_children x = let mapper (f, _) = sprintf " %s_%s;\n" x.prefix f in let fields = map_and_concat mapper x.fields in sprintf " | (SyntaxKind.%s, [ %s ]) -> %s { %s } " x.kind_name fields x.kind_name fields let to_constructor_methods x = let mapper1 (f, _) = sprintf " %s_%s\n" x.prefix f in let fields1 = map_and_concat mapper1 x.fields in let mapper2 (f, _) = sprintf " %s_%s;\n" x.prefix f in let fields2 = map_and_concat mapper2 x.fields in sprintf " let make_%s %s = let syntax = %s { %s } in let value = ValueBuilder.value_from_syntax syntax in make syntax value " x.type_name fields1 x.kind_name fields2 let to_from_methods x = if omit_syntax_record x then "" else let mapper (f, _) = sprintf " %s_%s;\n" x.prefix f in let fields = map_and_concat mapper x.fields in sprintf " let from_%s { %s } = %s { %s } " x.type_name fields x.kind_name fields let to_get_methods x = if omit_syntax_record x then "" else let mapper (f, _) = sprintf " %s_%s;\n" x.prefix f in let fields = map_and_concat mapper x.fields in sprintf " let get_%s x = match x with | %s {\n%s } -> {\n%s } | _ -> failwith \"get_%s: not a %s\" " x.type_name x.kind_name fields fields x.type_name x.kind_name let full_fidelity_syntax_template = make_header MLStyle " * 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 TO_KIND 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 TYPE_TESTS 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 FOLD_FROM_SYNTAX (* 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 CHILDREN let children node = children_from_syntax node.syntax let children_names node = match node.syntax with | Missing -> [] | Token _ -> [] | SyntaxList _ -> [] CHILDREN_NAMES 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 SYNTAX_FROM_CHILDREN | (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 CONSTRUCTOR_METHODS FROM_METHODS GET_METHODS end end end " let full_fidelity_syntax = Full_fidelity_schema.make_template_file ~transformations: [ { pattern = "TO_KIND"; func = to_to_kind }; { pattern = "TYPE_TESTS"; func = to_type_tests }; { pattern = "CHILDREN"; func = to_children }; { pattern = "FOLD_FROM_SYNTAX"; func = to_fold_from_syntax }; { pattern = "CHILDREN_NAMES"; func = to_children_names }; { pattern = "SYNTAX_FROM_CHILDREN"; func = to_syntax_from_children }; { pattern = "CONSTRUCTOR_METHODS"; func = to_constructor_methods }; { pattern = "FROM_METHODS"; func = to_from_methods }; { pattern = "GET_METHODS"; func = to_get_methods }; ] ~filename:(full_fidelity_path_prefix ^ "full_fidelity_syntax.ml") ~template:full_fidelity_syntax_template () end module GenerateFFTriviaKind = struct let to_trivia { trivia_kind; trivia_text = _ } = sprintf " | %s\n" trivia_kind let to_to_string { trivia_kind; trivia_text } = sprintf (" | " ^^ trivia_kind_fmt ^^ " -> \"%s\"\n") trivia_kind trivia_text let full_fidelity_trivia_kind_template = make_header MLStyle "" ^ " type t = TRIVIA [@@deriving show, enum, eq, sexp_of] let to_string kind = match kind with TO_STRING" let full_fidelity_trivia_kind = Full_fidelity_schema.make_template_file ~trivia_transformations: [ { trivia_pattern = "TRIVIA"; trivia_func = map_and_concat to_trivia }; { trivia_pattern = "TO_STRING"; trivia_func = map_and_concat to_to_string; }; ] ~filename:(full_fidelity_path_prefix ^ "/full_fidelity_trivia_kind.ml") ~template:full_fidelity_trivia_kind_template () end (* GenerateFFSyntaxKind *) module GenerateFFRustTriviaKind = struct let ocaml_tag = ref (-1) let to_trivia { trivia_kind; trivia_text = _ } = incr ocaml_tag; sprintf " %s = %d,\n" trivia_kind !ocaml_tag let to_to_string { trivia_kind; trivia_text } = sprintf " TriviaKind::%s => \"%s\",\n" trivia_kind trivia_text let full_fidelity_trivia_kind_template = make_header CStyle "" ^ " use ocamlrep::{FromOcamlRep, ToOcamlRep}; #[derive(Debug, Copy, Clone, FromOcamlRep, ToOcamlRep, PartialEq)] #[repr(u8)] pub enum TriviaKind { TRIVIA} impl TriviaKind { pub fn to_string(&self) -> &str { match self { TO_STRING } } pub const fn ocaml_tag(self) -> u8 { self as u8 } } " let full_fidelity_trivia_kind = Full_fidelity_schema.make_template_file ~trivia_transformations: [ { trivia_pattern = "TRIVIA"; trivia_func = map_and_concat to_trivia }; { trivia_pattern = "TO_STRING"; trivia_func = map_and_concat to_to_string; }; ] ~filename:(full_fidelity_path_prefix ^ "trivia_kind.rs") ~template:full_fidelity_trivia_kind_template () end (* GenerateFFRustTriviaKind *) module GenerateFFSyntaxKind = struct let to_tokens x = sprintf " | %s\n" x.kind_name let to_to_string x = sprintf (" | " ^^ kind_name_fmt ^^ " -> \"%s\"\n") x.kind_name x.description let full_fidelity_syntax_kind_template = make_header MLStyle "" ^ " type t = | Token of Full_fidelity_token_kind.t | Missing | SyntaxList TOKENS [@@deriving show, eq] let to_string kind = match kind with | Token _ -> \"token\" | Missing -> \"missing\" | SyntaxList -> \"list\" TO_STRING" let full_fidelity_syntax_kind = Full_fidelity_schema.make_template_file ~transformations: [ { pattern = "TOKENS"; func = to_tokens }; { pattern = "TO_STRING"; func = to_to_string }; ] ~filename:(full_fidelity_path_prefix ^ "full_fidelity_syntax_kind.ml") ~template:full_fidelity_syntax_kind_template () end (* GenerateFFTriviaKind *) module GenerateFFRustSyntaxKind = struct let to_tokens x = sprintf " %s,\n" x.kind_name let to_to_string x = sprintf (" SyntaxKind::" ^^ kind_name_fmt ^^ " => \"%s\",\n") x.kind_name x.description let tag = ref 1 let to_ocaml_tag x = incr tag; sprintf " SyntaxKind::%s => %d,\n" x.kind_name !tag let full_fidelity_syntax_kind_template = make_header CStyle "" ^ " use ocamlrep::{FromOcamlRep, ToOcamlRep}; use crate::token_kind::TokenKind; #[derive(Debug, Copy, Clone, FromOcamlRep, ToOcamlRep, PartialEq)] pub enum SyntaxKind { Missing, Token(TokenKind), SyntaxList, TOKENS } impl SyntaxKind { pub fn to_string(&self) -> &str { match self { SyntaxKind::SyntaxList => \"list\", SyntaxKind::Missing => \"missing\", SyntaxKind::Token(_) => \"token\", TO_STRING } } pub fn ocaml_tag(self) -> u8 { match self { SyntaxKind::Missing => 0, SyntaxKind::Token(_) => 0, SyntaxKind::SyntaxList => 1, OCAML_TAG } } } " let full_fidelity_syntax_kind = Full_fidelity_schema.make_template_file ~transformations: [ { pattern = "TOKENS"; func = to_tokens }; { pattern = "TO_STRING"; func = to_to_string }; { pattern = "OCAML_TAG"; func = to_ocaml_tag }; ] ~filename:(full_fidelity_path_prefix ^ "syntax_kind.rs") ~template:full_fidelity_syntax_kind_template () end (* GenerateFFRustSyntaxKind *) module GenerateFFTokenKind = struct let given_text_width = let folder acc x = max acc (String.length x.token_text) in List.fold_left ~f:folder ~init:0 given_text_tokens let to_kind_declaration x = sprintf " | %s\n" x.token_kind let add_guard_or_pad : cond:bool * string -> ?else_cond:bool * string -> string -> string = fun ~cond:(cond, guard) ?else_cond guards -> let pad str = String.make (String.length str) ' ' in let is_only_spaces str = String.equal str (pad str) in let make_same_length str1 str2 = let blanks n = try String.make n ' ' with | Invalid_argument _ -> "" in let (len1, len2) = (String.length str1, String.length str2) in let str1 = str1 ^ blanks (len2 - len1) in let str2 = str2 ^ blanks (len1 - len2) in (str1, str2) in let (else_cond, else_guard) = match else_cond with | Some (cond, guard) -> (cond, guard) | None -> (false, "") in let prefix = if cond || else_cond then if is_only_spaces guards then "when " else "&& " else " " in let (guard, else_guard) = make_same_length guard else_guard in let guard = if cond then guard else if else_cond then else_guard else pad guard in guards ^ prefix ^ guard ^ " " let to_from_string x = let token_text = escape_token_text x.token_text in let spacer_width = given_text_width - String.length token_text in let spacer = String.make spacer_width ' ' in let guards = add_guard_or_pad "" ~cond:(x.allowed_as_identifier, "not only_reserved") in sprintf " | \"%s\"%s %s-> Some %s\n" token_text spacer guards x.token_kind let to_to_string x = let token_text = escape_token_text x.token_text in sprintf (" | " ^^ token_kind_fmt ^^ " -> \"%s\"\n") x.token_kind token_text let to_is_variable_text x = sprintf " | %s -> true\n" x.token_kind let full_fidelity_token_kind_template = make_header MLStyle "" ^ " type t = (* No text tokens *) KIND_DECLARATIONS_NO_TEXT (* Given text tokens *) KIND_DECLARATIONS_GIVEN_TEXT (* Variable text tokens *) KIND_DECLARATIONS_VARIABLE_TEXT [@@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 FROM_STRING_GIVEN_TEXT | _ -> None let to_string kind = match kind with (* No text tokens *) TO_STRING_NO_TEXT (* Given text tokens *) TO_STRING_GIVEN_TEXT (* Variable text tokens *) TO_STRING_VARIABLE_TEXT let is_variable_text kind = match kind with IS_VARIABLE_TEXT_VARIABLE_TEXT | _ -> false " let full_fidelity_token_kind = Full_fidelity_schema.make_template_file ~token_no_text_transformations: [ { token_pattern = "KIND_DECLARATIONS_NO_TEXT"; token_func = map_and_concat to_kind_declaration; }; { token_pattern = "TO_STRING_NO_TEXT"; token_func = map_and_concat to_to_string; }; ] ~token_given_text_transformations: [ { token_pattern = "KIND_DECLARATIONS_GIVEN_TEXT"; token_func = map_and_concat to_kind_declaration; }; { token_pattern = "FROM_STRING_GIVEN_TEXT"; token_func = map_and_concat to_from_string; }; { token_pattern = "TO_STRING_GIVEN_TEXT"; token_func = map_and_concat to_to_string; }; ] ~token_variable_text_transformations: [ { token_pattern = "KIND_DECLARATIONS_VARIABLE_TEXT"; token_func = map_and_concat to_kind_declaration; }; { token_pattern = "TO_STRING_VARIABLE_TEXT"; token_func = map_and_concat to_to_string; }; { token_pattern = "IS_VARIABLE_TEXT_VARIABLE_TEXT"; token_func = map_and_concat to_is_variable_text; }; ] ~filename:(full_fidelity_path_prefix ^ "full_fidelity_token_kind.ml") ~template:full_fidelity_token_kind_template () end (* GenerateFFTokenKind *) module GenerateFFRustTokenKind = struct let token_kind x = match x.token_kind with | "Self" -> "SelfToken" | x -> x let to_from_string x = let token_text = escape_token_text x.token_text in let guard = if x.allowed_as_identifier then "!only_reserved" else "" in let guard = if String.equal guard "" then "" else " if " ^ guard in sprintf " b\"%s\"%s => Some(TokenKind::%s),\n" token_text guard (token_kind x) let rust_tag = ref (-1) let to_kind_declaration x = incr rust_tag; sprintf " %s = %d,\n" (token_kind x) !rust_tag let token_text x = escape_token_text x.token_text let to_to_string x = sprintf " TokenKind::%s => \"%s\",\n" (token_kind x) (token_text x) let ocaml_tag = ref (-1) let to_ocaml_tag x = incr ocaml_tag; sprintf " TokenKind::%s => %d,\n" (token_kind x) !ocaml_tag let from_u8_tag = ref (-1) let to_try_from_u8 x = incr from_u8_tag; sprintf " %d => Some(TokenKind::%s),\n" !from_u8_tag (token_kind x) let to_width x = let len = if String.equal (token_kind x) "Backslash" then 1 else String.length (token_text x) in assert (len > 0); sprintf " TokenKind::%s => Some(unsafe { NonZeroUsize::new_unchecked(%d) }),\n" (token_kind x) len let full_fidelity_rust_token_kind_template = make_header CStyle "" ^ " use std::num::NonZeroUsize; use ocamlrep::{FromOcamlRep, ToOcamlRep}; #[allow(non_camel_case_types)] // allow Include_once and Require_once #[derive(Debug, Copy, Clone, PartialEq, Ord, Eq, PartialOrd, FromOcamlRep, ToOcamlRep)] #[repr(u8)] pub enum TokenKind { // No text tokens KIND_DECLARATIONS_NO_TEXT // Given text tokens KIND_DECLARATIONS_GIVEN_TEXT // Variable text tokens KIND_DECLARATIONS_VARIABLE_TEXT} impl TokenKind { pub fn to_string(self) -> &'static str { match self { // No text tokens TO_STRING_NO_TEXT // Given text tokens TO_STRING_GIVEN_TEXT // Variable text tokes TO_STRING_VARIABLE_TEXT } } pub fn from_string( keyword: &[u8], only_reserved: bool, ) -> Option<Self> { match keyword { b\"true\" if !only_reserved => Some(TokenKind::BooleanLiteral), b\"false\" if !only_reserved => Some(TokenKind::BooleanLiteral), FROM_STRING_GIVEN_TEXT _ => None, } } pub fn ocaml_tag(self) -> u8 { match self { OCAML_TAG_NO_TEXTOCAML_TAG_GIVEN_TEXTOCAML_TAG_VARIABLE_TEXT } } pub fn try_from_u8(tag: u8) -> Option<Self> { match tag { FROM_U8_NO_TEXTFROM_U8_GIVEN_TEXTFROM_U8_VARIABLE_TEXT _ => None, } } pub fn fixed_width(self) -> Option<NonZeroUsize> { match self { WIDTH_GIVEN_TEXT _ => None, } } } " let full_fidelity_token_kind = Full_fidelity_schema.make_template_file ~token_no_text_transformations: [ { token_pattern = "KIND_DECLARATIONS_NO_TEXT"; token_func = map_and_concat to_kind_declaration; }; { token_pattern = "TO_STRING_NO_TEXT"; token_func = map_and_concat to_to_string; }; { token_pattern = "OCAML_TAG_NO_TEXT"; token_func = map_and_concat to_ocaml_tag; }; { token_pattern = "FROM_U8_NO_TEXT"; token_func = map_and_concat to_try_from_u8; }; ] ~token_given_text_transformations: [ { token_pattern = "KIND_DECLARATIONS_GIVEN_TEXT"; token_func = map_and_concat to_kind_declaration; }; { token_pattern = "FROM_STRING_GIVEN_TEXT"; token_func = map_and_concat to_from_string; }; { token_pattern = "TO_STRING_GIVEN_TEXT"; token_func = map_and_concat to_to_string; }; { token_pattern = "OCAML_TAG_GIVEN_TEXT"; token_func = map_and_concat to_ocaml_tag; }; { token_pattern = "FROM_U8_GIVEN_TEXT"; token_func = map_and_concat to_try_from_u8; }; { token_pattern = "WIDTH_GIVEN_TEXT"; token_func = map_and_concat to_width; }; ] ~token_variable_text_transformations: [ { token_pattern = "KIND_DECLARATIONS_VARIABLE_TEXT"; token_func = map_and_concat to_kind_declaration; }; { token_pattern = "TO_STRING_VARIABLE_TEXT"; token_func = map_and_concat to_to_string; }; { token_pattern = "OCAML_TAG_VARIABLE_TEXT"; token_func = map_and_concat to_ocaml_tag; }; { token_pattern = "FROM_U8_VARIABLE_TEXT"; token_func = map_and_concat to_try_from_u8; }; ] ~filename:(full_fidelity_path_prefix ^ "token_kind.rs") ~template:full_fidelity_rust_token_kind_template () end (* GenerateFFTRustTokenKind *) module GenerateFFOperatorRust = struct let template = make_header CStyle "" ^ " use ocamlrep::{FromOcamlRep, ToOcamlRep}; #[derive(FromOcamlRep, ToOcamlRep)] pub enum Operator { OPERATORS} " let full_fidelity_operators = Full_fidelity_schema.make_template_file ~operator_transformations: [ { operator_pattern = "OPERATORS"; operator_func = map_and_concat (fun op -> sprintf " %sOperator,\n" op.name); }; ] ~filename:(full_fidelity_path_prefix ^ "operator_generated.rs") ~template () end (* GenerateFFOperatorRust *) module GenerateFFOperator = struct let template = make_header MLStyle "" ^ " module type Sig = sig type t = OPERATOR_DECL_SIGend module Impl : Sig = struct type t = OPERATOR_DECL_IMPLend " let op_pattern prefix op = sprintf "%s| %sOperator\n" prefix op.name let transform pattern = { operator_pattern = pattern; operator_func = map_and_concat (op_pattern " "); } let full_fidelity_operator = Full_fidelity_schema.make_template_file ~operator_transformations: [transform "OPERATOR_DECL_SIG"; transform "OPERATOR_DECL_IMPL"] ~filename: (full_fidelity_path_prefix ^ "full_fidelity_operator_generated.ml") ~template () end module GenerateSchemaVersion = struct let template = make_header CStyle "" ^ sprintf " pub const VERSION: &str = \"%s\"; " Full_fidelity_schema.full_fidelity_schema_version_number let gen = Full_fidelity_schema.make_template_file ~filename: "hphp/hack/src/parser/schema/full_fidelity_schema_version_number.rs" ~template () end let templates = [ GenerateFFOperatorRust.full_fidelity_operators; GenerateFFOperator.full_fidelity_operator; GenerateFFSyntaxType.full_fidelity_syntax_type; GenerateFFSyntaxSig.full_fidelity_syntax_sig; GenerateFFTriviaKind.full_fidelity_trivia_kind; GenerateFFRustTriviaKind.full_fidelity_trivia_kind; GenerateFFSyntax.full_fidelity_syntax; GenerateFFRustSyntax.full_fidelity_syntax; GenerateFFRustSyntaxType.full_fidelity_syntax; GenerateFFSyntaxKind.full_fidelity_syntax_kind; GenerateFFRustSyntaxKind.full_fidelity_syntax_kind; GenerateFFTokenKind.full_fidelity_token_kind; GenerateFFRustTokenKind.full_fidelity_token_kind; GenerateFFJSONSchema.full_fidelity_json_schema; GenerateFFSmartConstructors.full_fidelity_smart_constructors; GenerateFFRustSmartConstructors.full_fidelity_smart_constructors; GenerateFFRustPositionedSmartConstructors.positioned_smart_constructors; GenerateFFSyntaxSmartConstructors.full_fidelity_syntax_smart_constructors; GenerateFFRustSyntaxSmartConstructors .full_fidelity_syntax_smart_constructors; GenerateFFRustDeclModeSmartConstructors.decl_mode_smart_constructors; GenerateRustFlattenSmartConstructors.flatten_smart_constructors; GenerateRustDirectDeclSmartConstructors.direct_decl_smart_constructors; GenerateRustPairSmartConstructors.pair_smart_constructors; GenerateFFSmartConstructorsWrappers .full_fidelity_smart_constructors_wrappers; GenerateFFRustSmartConstructorsWrappers .full_fidelity_smart_constructors_wrappers; GenerateFFRustSyntaxVariantByRef.full_fidelity_syntax; GenerateSyntaxTypeImpl.full_fidelity_syntax; GenerateSyntaxChildrenIterator.full_fidelity_syntax; GenerateFFRustSyntaxImplByRef.full_fidelity_syntax; GenerateSyntaxSerialize.gen; GenerateSchemaVersion.gen; ]
OCaml
hhvm/hphp/hack/src/generate_hhi.ml
(* * Copyright (c) 2016-present , 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. * *) (** * Usage: hh_parse --generate-hhi [FILE] * * Generates a .hhi file from a .hack or .php file; intended for use in the * build system for a typechecked systemlib. *) open Hh_prelude module Syntax = Full_fidelity_editable_syntax module SourceText = Full_fidelity_source_text module Rewriter = Full_fidelity_rewriter.WithSyntax (Syntax) module Token = Full_fidelity_editable_token module TokenKind = Full_fidelity_token_kind let go editable = let without_bodies = Rewriter.rewrite_pre_and_stop (fun inner -> match Syntax.syntax inner with | Syntax.MarkupSuffix _ -> (* remove `<?hh` line if present *) Rewriter.Replace (Syntax.make_missing SourceText.empty 0) | Syntax.FunctionDeclaration f -> (* remove function bodies *) Rewriter.Replace (Syntax.make_function_declaration f.function_attribute_spec f.function_declaration_header (* replace body *) (Syntax.make_token (Token.create TokenKind.Semicolon ";" [] []))) | Syntax.MethodishDeclaration m -> (* remove method bodies *) Rewriter.Replace (Syntax.make_methodish_declaration m.methodish_attribute m.methodish_function_decl_header (* no body *) (Syntax.make_missing SourceText.empty 0) (* but always a semicolon, even if not abstract *) (Syntax.make_token (Token.create TokenKind.Semicolon ";" [] []))) | Syntax.ConstantDeclarator c -> (* remove constant values *) Rewriter.Replace (Syntax.make_constant_declarator c.constant_declarator_name (* no value *) (Syntax.make_missing SourceText.empty 0)) | _ -> Rewriter.Keep) editable in let text = Syntax.text without_bodies in "<?hh\n// @" ^ "generated from implementation\n\n" ^ text
OCaml
hhvm/hphp/hack/src/hackfmt.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 SyntaxError = Full_fidelity_syntax_error module SyntaxTree = Full_fidelity_syntax_tree.WithSyntax (Full_fidelity_positioned_syntax) module Logger = HackfmtEventLogger module FEnv = Format_env open Printf open Boundaries open Hackfmt_error open Ocaml_overrides open FindUtils type filename = string type range = (* 0-based byte offsets; half-open/inclusive-exclusive *) | Byte of Interval.t (* 1-based line numbers; inclusive *) | Line of Interval.t type text_source = | File of filename (* Optional filename for logging. *) | Stdin of filename option let text_source_to_filename = function | File filename -> Some filename | Stdin filename -> filename let file_exists path = Option.is_some (Sys_utils.realpath path) let rec guess_root config start recursion_limit = if Path.equal start (Path.parent start) then None (* Reach fs root, nothing to do. *) else if Wwwroot.is_www_directory ~config start then Some start else if recursion_limit <= 0 then None else guess_root config (Path.parent start) (recursion_limit - 1) let get_root_for_diff () = eprintf "No root specified, trying to guess one\n"; let config = ".hhconfig" in let start_path = Path.make "." in let root = match guess_root config start_path 50 with | None -> start_path | Some r -> r in Wwwroot.assert_www_directory ~config root; eprintf "Guessed root: %a\n%!" Path.output root; root let get_root_for_format files = let cur = Path.make "." in let start_path = match files with | [] -> cur (* just use the first file here. specifying more than one will result in an * error during validation *) | hd :: _ -> Path.make hd |> Path.dirname in match guess_root ".hhconfig" start_path 50 with | Some p -> p | None -> cur let read_hhconfig path = let (_hash, config) = Config_file.parse_hhconfig path in ( FEnv. { add_trailing_commas = Config_file.Getters.bool_ "hackfmt.add_trailing_commas" ~default:default.add_trailing_commas config; indent_width = Config_file.Getters.int_ "hackfmt.indent_width" ~default:default.indent_width config; indent_with_tabs = Config_file.Getters.bool_ "hackfmt.tabs" (* keep consistent with CLI arg name *) ~default:default.indent_with_tabs config; line_width = Config_file.Getters.int_ "hackfmt.line_width" ~default:default.line_width config; format_generated_code = Config_file.Getters.bool_ "hackfmt.format_generated_code" ~default:default.format_generated_code config; version = Config_file.Getters.int_opt "hackfmt.version" config; }, Full_fidelity_parser_env.make ?enable_xhp_class_modifier: (Config_file.Getters.bool_opt "enable_xhp_class_modifier" config) ?allow_new_attribute_syntax: (Config_file.Getters.bool_opt "allow_new_attribute_syntax" config) () ) let opt_default opt def = match opt with | Some v -> v | None -> def module Env = struct type t = { debug: bool; test: bool; mutable mode: string option; mutable text_source: text_source; root: string; } end let usage = sprintf "Usage: %s [--range s e] [filename or read from stdin]\n" Sys.argv.(0) let parse_options () = let files = ref [] in let filename_for_logging = ref None in let start_char = ref None in let end_char = ref None in let start_line = ref None in let end_line = ref None in let at_char = ref None in let inplace = ref false in let diff = ref false in let diff_dry = ref false in let check = ref false in let debug = ref false in let test = ref false in (* The following are either inferred from context (cwd and .hhconfig), * or via CLI flags, with priority given to the latter. *) let cli_indent_width = ref None in let cli_indent_with_tabs = ref false in let cli_line_width = ref None in let cli_root = ref None in let cli_format_generated_code = ref false in let cli_version = ref None in let rec options = ref [ ( "--range", Arg.Tuple [ Arg.Int (fun x -> start_char := Some x); Arg.Int (fun x -> end_char := Some x); ], "[start end] Range of character positions to be formatted (1 indexed)" ); ( "--line-range", Arg.Tuple [ Arg.Int (fun x -> start_line := Some x); Arg.Int (fun x -> end_line := Some x); ], "[start end] Range of lines to be formatted (1 indexed, inclusive)" ); ( "--at-char", Arg.Int (fun x -> at_char := Some x), "[idx] Format a node ending at the given character" ^ " (0 indexed)" ); ("-i", Arg.Set inplace, " Format file in-place"); ("--in-place", Arg.Set inplace, " Format file in-place"); ( "--indent-width", Arg.Int (fun x -> cli_indent_width := Some x), sprintf " Specify the number of spaces per indentation level. Defaults to %d" FEnv.(default.indent_width) ); ( "--line-width", Arg.Int (fun x -> cli_line_width := Some x), sprintf " Specify the maximum length for each line. Defaults to %d" FEnv.(default.line_width) ); ( "--tabs", Arg.Set cli_indent_with_tabs, " Indent with tabs rather than spaces" ); ( "--format-generated-code", Arg.Set cli_format_generated_code, " Enable formatting of generated files and generated sections in " ^ "partially-generated files. By default, generated code will be left " ^ "untouched." ); ( "--version", Arg.Int (fun x -> cli_version := Some x), " For version-gated formatter features, specify the version to use. " ^ "Defaults to latest." ); ( "--diff", Arg.Set diff, " Format the changed lines in a diff" ^ " (example: hg diff | hackfmt --diff)" ); ( "--root", Arg.String (fun x -> cli_root := Some x), "[dir] Specify a root directory for --diff mode, or a directory " ^ "containing .hhconfig for standard mode" ); ( "--diff-dry-run", Arg.Set diff_dry, " Preview the files that would be overwritten by --diff mode" ); ( "--check-formatting", Arg.Set check, " Given a list of filenames, check whether they are formatted and " ^ "print the filenames which would be modified by hackfmt -i" ); ( "--debug", Arg.Unit (fun () -> debug := true; options := Hackfmt_debug.init_with_options ()), " Print debug statements" ); ( "--filename-for-logging", Arg.String (fun x -> filename_for_logging := Some x), " The filename for logging purposes, when providing file contents " ^ "through stdin." ); ("--test", Arg.Set test, " Disable logging"); ] in Arg.parse_dynamic options (fun file -> files := file :: !files) usage; let range = match (!start_char, !end_char, !start_line, !end_line) with | (Some s, Some e, None, None) -> Some (Byte (s - 1, e - 1)) | (None, None, Some s, Some e) -> Some (Line (s, e)) | (Some _, Some _, Some _, Some _) -> raise (InvalidCliArg "Cannot use --range with --line-range") | _ -> None in let root = match !cli_root with | Some p -> Path.make p | None -> if !diff then get_root_for_diff () else get_root_for_format !files in let hhconfig_path = Path.concat root ".hhconfig" |> Path.to_string in let (config, parser_env) = if file_exists hhconfig_path then read_hhconfig hhconfig_path else (FEnv.default, Full_fidelity_parser_env.default) in let config = FEnv. { add_trailing_commas = config.add_trailing_commas; indent_width = opt_default !cli_indent_width config.indent_width; indent_with_tabs = !cli_indent_with_tabs || config.indent_with_tabs; line_width = opt_default !cli_line_width config.line_width; format_generated_code = !cli_format_generated_code || config.format_generated_code; version = (if Option.is_some !cli_version then !cli_version else config.version); } in ( ( !files, !filename_for_logging, range, !at_char, !inplace, !diff, !diff_dry, !check, config ), root, parser_env, (!debug, !test) ) type format_options = | Print of { text_source: text_source; range: range option; config: FEnv.t; } | InPlace of { files: filename list; config: FEnv.t; } | Check of { files: filename list; config: FEnv.t; } | AtChar of { text_source: text_source; pos: int; config: FEnv.t; } | Diff of { dry: bool; config: FEnv.t; } let mode_string format_options = match format_options with | Print { text_source = File _; range = None; _ } -> "FILE" | Print { text_source = File _; range = Some _; _ } -> "RANGE" | Print { text_source = Stdin _; range = None; _ } -> "STDIN" | Print { text_source = Stdin _; range = Some _; _ } -> "STDIN_RANGE" | InPlace _ -> "IN_PLACE" | Check _ -> "CHECK_FORMATTING" | AtChar _ -> "AT_CHAR" | Diff { dry = false; _ } -> "DIFF" | Diff { dry = true; _ } -> "DIFF_DRY" type validate_options_input = { text_source: text_source; range: range option; at_char: int option; inplace: bool; diff: bool; check: bool; } let validate_options env ( files, filename_for_logging, range, at_char, inplace, diff, diff_dry, check, config ) = let fail msg = raise (InvalidCliArg msg) in let multifile_allowed = inplace || check in let filename = match files with | [filename] -> Some filename | filename :: _ :: _ when multifile_allowed -> Some filename | [] -> None | _ -> fail "More than one file given" in let text_source = match (filename, filename_for_logging) with | (Some _, Some _) -> fail "Can't supply both a filename and a filename for logging" | (Some filename, None) -> File filename | (None, Some filename_for_logging) -> Stdin (Some filename_for_logging) | (None, None) -> Stdin None in let assert_file_exists = function | None -> () | Some path -> if not (file_exists path) then fail ("No such file or directory: " ^ path) in assert_file_exists filename; assert_file_exists (Some env.Env.root); let files = if multifile_allowed then List.rev_filter files ~f:(fun path -> is_hack path || (Printf.eprintf "Unexpected file extension (probably not a Hack file): %s\n" path; false)) else ( (match text_source with | File path | Stdin (Some path) when not (is_hack path) -> fail ("Unexpected file extension (probably not a Hack file): " ^ path) | _ -> ()); files ) in (* Let --diff-dry-run imply --diff *) let diff = diff || diff_dry in match { diff; inplace; text_source; range; at_char; check } with | _ when env.Env.debug && diff -> fail "Can't format diff in debug mode" | { diff = true; text_source = File _; _ } | { diff = true; text_source = Stdin (Some _); _ } -> fail "--diff mode expects no files" | { diff = true; range = Some _; _ } -> fail "--diff mode expects no range" | { diff = true; at_char = Some _; _ } -> fail "--diff mode can't format at-char" | { diff = true; check = true; _ } -> fail "Can't check formatting in --diff mode" | { inplace = true; text_source = Stdin _; _ } -> fail "Provide a filename to format in-place" | { inplace = true; range = Some _; _ } -> fail "Can't format a range in-place" | { inplace = true; at_char = Some _; _ } -> fail "Can't format at-char in-place" | { check = true; text_source = Stdin _; _ } -> fail "Provide a filename to check formatting" | { inplace = true; check = true; _ } -> fail "Can't check formatting in-place" | { check = true; range = Some _; _ } -> fail "Can't check formatting for a range" | { check = true; at_char = Some _; _ } -> fail "Can't check formatting at-char" | { diff = false; inplace = false; range = Some _; at_char = Some _; _ } -> fail "--at-char expects no range" | { diff = false; inplace = false; at_char = None; check = false; _ } -> Print { text_source; range; config } | { diff = false; inplace = true; text_source = File _; range = None; _ } -> InPlace { files; config } | { diff = false; check = true; text_source = File _; range = None; _ } -> Check { files; config } | { diff = false; inplace = false; range = None; at_char = Some pos; _ } -> AtChar { text_source; pos; config } | { diff = true; text_source = Stdin None; range = None; _ } -> Diff { dry = diff_dry; config } let read_stdin () = let buf = Buffer.create 256 in try while true do Buffer.add_string buf (Out_channel.(flush stdout); In_channel.(input_line_exn stdin)); Buffer.add_char buf '\n' done; assert false with | End_of_file -> Buffer.contents buf let print_error source_text error = let text = SyntaxError.to_positioned_string error (SourceText.offset_to_position source_text) in Printf.eprintf "%s\n" text let parse_text ~parser_env source_text = let parser_env = { parser_env with Full_fidelity_parser_env.mode = Full_fidelity_parser.parse_mode source_text; } in let tree = SyntaxTree.make ~env:parser_env source_text in if List.is_empty (SyntaxTree.all_errors tree) then tree else ( List.iter (SyntaxTree.all_errors tree) ~f:(print_error source_text); raise Hackfmt_error.InvalidSyntax ) let read_file filename = SourceText.from_file @@ Relative_path.create Relative_path.Dummy filename let parse ~parser_env text_source = let source_text = match text_source with | File filename -> read_file filename | Stdin _ -> SourceText.make Relative_path.default @@ read_stdin () in parse_text ~parser_env source_text let logging_time_taken env logger thunk = let start_t = Unix.gettimeofday () in let res = thunk () in let end_t = Unix.gettimeofday () in if not env.Env.test then logger ~start_t ~end_t ~mode:env.Env.mode ~file:(text_source_to_filename env.Env.text_source) ~root:env.Env.root; res (* If the range is a byte range, expand it to line boundaries. * If the range is a line range, convert it to a byte range. *) let expand_or_convert_range ?ranges source_text range = match range with | Byte range -> expand_to_line_boundaries ?ranges source_text range | Line (st, ed) -> let line_boundaries = match ranges with | Some ranges -> ranges | None -> get_line_boundaries (SourceText.text source_text) in let st = max st 1 in let ed = min ed (Array.length line_boundaries) in (try line_interval_to_offset_range line_boundaries (st, ed) with | Invalid_argument msg -> raise (InvalidCliArg msg)) let format ?config ?range ?ranges env tree = let source_text = SyntaxTree.text tree in match range with | None -> logging_time_taken env Logger.format_tree_end (fun () -> Libhackfmt.format_tree ?config tree) | Some range -> let range = expand_or_convert_range ?ranges source_text range in logging_time_taken env Logger.format_range_end (fun () -> let formatted = Libhackfmt.format_range ?config range tree in (* This is a bit of a hack to deal with situations where a newline exists * in the original source in a location where hackfmt refuses to split, * and the range end falls at that newline. It is correct for format_range * not to add the trailing newline, but it looks better to add an * incorrect newline than to omit it, which would cause the following line * (along with its indentation spaces) to be joined with the last line in * the range. See test case: binary_expression_range_formatting.php *) if Char.equal formatted.[String.length formatted - 1] '\n' then formatted else formatted ^ "\n") let output ?text_source str = let with_out_channel f = match text_source with | Some (File filename) -> let out_channel = Out_channel.create filename in f out_channel; Out_channel.close out_channel | Some (Stdin _) | None -> f stdout in with_out_channel (fun out_channel -> fprintf out_channel "%s%!" str) let format_diff_intervals ?config env intervals tree = try logging_time_taken env Logger.format_intervals_end (fun () -> Libhackfmt.format_intervals ?config intervals tree) with | Invalid_argument s -> raise (InvalidDiff s) let debug_print ?range ?config text_source = let tree = parse ~parser_env:Full_fidelity_parser_env.default text_source in let source_text = SyntaxTree.text tree in let range = Option.map range ~f:(expand_or_convert_range source_text) in let env = Libhackfmt.env_from_config config in let doc = Hack_format.transform env (SyntaxTransforms.editable_from_positioned tree) in let chunk_groups = Chunk_builder.build env doc in Hackfmt_debug.debug env ~range source_text doc chunk_groups let main (env : Env.t) (options : format_options) (parser_env : Full_fidelity_parser_env.t) = env.Env.mode <- Some (mode_string options); match options with | Print { text_source; range; config } -> env.Env.text_source <- text_source; if env.Env.debug then debug_print ?range ~config text_source else text_source |> parse ~parser_env |> format ?range ~config env |> output | InPlace { files; config } -> List.iter files ~f:(fun filename -> let text_source = File filename in env.Env.text_source <- text_source; if env.Env.debug then debug_print ~config text_source; let source_text = read_file filename in let source_text_string = SourceText.text source_text in try let formatted_text = text_source |> parse ~parser_env |> format ~config env in if String.(source_text_string <> formatted_text) then output ~text_source formatted_text with | InvalidSyntax -> eprintf "Parse error in file: %s\n%!" filename) | Check { files; config } -> List.iter files ~f:(fun filename -> let text_source = File filename in env.Env.text_source <- text_source; let source_text = read_file filename in let source_text_string = SourceText.text source_text in try let formatted_text = text_source |> parse ~parser_env |> format ~config env in if String.(source_text_string <> formatted_text) then printf "%s\n" filename with | InvalidSyntax -> eprintf "Parse error in file: %s\n%!" filename) | AtChar { text_source; pos; config } -> env.Env.text_source <- text_source; let tree = parse ~parser_env text_source in let (range, formatted) = try logging_time_taken env Logger.format_at_offset_end (fun () -> Libhackfmt.format_at_offset ~config tree pos) with | Invalid_argument s -> raise (InvalidCliArg s) in if env.Env.debug then debug_print text_source ~range:(Byte range) ~config; Printf.printf "%d %d\n" (fst range) (snd range); output formatted | Diff { dry; config } -> let root = Path.make env.Env.root in read_stdin () |> Parse_diff.go |> List.filter ~f:(fun (rel_path, _intervals) -> is_hack rel_path) |> List.filter_map ~f:(fun (rel_path, intervals) -> (* We intentionally raise an exception here instead of printing a * message and moving on--if a file is missing, it may be a signal that * this diff is out of date and may lead us to format unexpected ranges * (typically diffs will be directly piped from `hg diff`, and thus * won't be out of date). * * Similarly, InvalidDiff exceptions thrown by format_diff_intervals * (caused by out-of-bounds line numbers, etc) will cause us to bail * before writing to any files. *) let filename = Path.to_string (Path.concat root rel_path) in if not (file_exists filename) then raise (InvalidDiff ("No such file or directory: " ^ rel_path)); (* Store the name of the file we're working with, so if we encounter an * exception, this filename will be the one that is logged. *) let text_source = File filename in env.Env.text_source <- text_source; try let contents = text_source |> parse ~parser_env |> format_diff_intervals ~config env intervals in Some (text_source, rel_path, contents) with (* A parse error isn't a signal that there's something wrong with the * diff--there's just something wrong with that file. We can leave that * file alone and move on. *) | InvalidSyntax -> Printf.eprintf "Parse error in file: %s\n%!" rel_path; None) |> List.iter ~f:(fun (text_source, rel_path, contents) -> (* Log this filename in the event of an exception. *) env.Env.text_source <- text_source; if dry then printf "*** %s\n" rel_path; let output_text_source = if dry then Stdin None else text_source in output ~text_source:output_text_source contents) let () = (* no-op, needed at entry point for the Daemon module (used by HackfmtEventLogger) to behave correctly *) Daemon.check_entry_point (); Folly.ensure_folly_init (); let (options, root, parser_env, (debug, test)) = parse_options () in let env = { Env.debug; test; mode = None; text_source = Stdin None; root = Path.to_string root; } in let start_time = Unix.gettimeofday () in if not env.Env.test then Logger.init start_time; let (err_msg, exit_code) = try let options = validate_options env options in main env options parser_env; (None, 0) with | exn -> let exit_code = get_exception_exit_value exn in if exit_code = 255 then Printexc.print_backtrace stderr; let err_str = get_error_string_from_exn exn in let err_msg = match exn with | InvalidSyntax -> err_str | InvalidCliArg s | InvalidDiff s -> err_str ^ ": " ^ s | _ -> err_str ^ ": " ^ Exn.to_string exn in (Some err_msg, exit_code) in (if not env.Env.test then let time_taken = Unix.gettimeofday () -. start_time in Logger.exit ~time_taken ~error:err_msg ~exit_code:(Some exit_code) ~mode:env.Env.mode ~file:(text_source_to_filename env.Env.text_source) ~root:env.Env.root); Option.iter err_msg ~f:(eprintf "%s\n"); exit exit_code
OCaml
hhvm/hphp/hack/src/hh_client.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. * *) (** * Hack for HipHop: type checker's client code. * * This code gets called in various different ways: * - from emacs, where the output is asynchronous * - from vim, where vim is blocked until this code exits * - from arc diff, our linter * - from arc land, our commit hook * - from check trunk, our irc bot which checks the state of trunk * - manually, from the command line * * Usage: hh_client [OPTION]... [WWW DIRECTORY] [FILE]... * *) open Hh_prelude let () = Random.self_init () let () = (* no-op, needed at entry-point for Daemon hookup *) Daemon.check_entry_point (); Folly.ensure_folly_init (); (* Ignore SIGPIPE since if it arises from clientConnect then it might indicate server hangup; we detect this case already and handle it better than a signal (unhandled signals cause program exit). *) Sys_utils.set_signal Sys.sigpipe Sys.Signal_ignore; Sys_utils.set_signal Sys.sigint (Sys.Signal_handle (fun _ -> raise Exit_status.(Exit_with Interrupted))); let init_id = Random_id.short_string () in let init_proc_stack = Proc.get_proc_stack (Unix.getpid ()) in let from_default = if Proc.is_likely_from_interactive_shell init_proc_stack then "[sh]" else "" in let command = ClientArgs.parse_args ~from_default in let command_name = match command with | ClientCommand.CCheck _ -> "Check" | ClientCommand.CStart _ -> "Start" | ClientCommand.CStop _ -> "Stop" | ClientCommand.CRestart _ -> "Restart" | ClientCommand.CLsp _ -> "Lsp" | ClientCommand.CSavedStateProjectMetadata _ -> "SavedStateProjectMetadata" | ClientCommand.CDownloadSavedState _ -> "DownloadSavedState" | ClientCommand.CRage _ -> "Rage" in (* The global variable Relative_path.root must be initialized for a wide variety of things *) let root = ClientArgs.root command in Option.iter root ~f:(Relative_path.set_path_prefix Relative_path.Root); let from = ClientArgs.from command in (* We'll chose where Hh_logger.log gets sent *) Hh_logger.Level.set_min_level_file Hh_logger.Level.Info; Hh_logger.Level.set_min_level_stderr Hh_logger.Level.Error; Hh_logger.set_id (Printf.sprintf "%s#%s" command_name init_id); begin match root with | None -> () | Some root -> let client_log_fn = ServerFiles.client_log root in (try (* For irritating reasons T67177821 we might not have permissions to write to the file. Pending a fix, let's only set up Hh_logger to write to the file if we can indeed safely write to it. *) Sys_utils.touch (Sys_utils.Touch_existing_or_create_new { mkdir_if_new = false; perm_if_new = 0o666 }) client_log_fn; Hh_logger.set_log client_log_fn with | _ -> ()) end; Hh_logger.log "[hh_client] %s" (String.concat ~sep:" " (Array.to_list Sys.argv)); HackEventLogger.client_init ~init_id ~custom_columns:(ClientCommand.get_custom_telemetry_data command) (Option.value root ~default:Path.dummy_path); (* we also have to patch up HackEventLogger with stuff we learn from root, if available... *) let local_config = match root with | None -> None | Some root -> ServerProgress.set_root root; (* The code to load hh.conf (ServerLocalConfig) is a bit weirdly factored. It requires a ServerArgs structure, solely to pick out --from and --config options. We dont have ServerArgs (we only have client args!) but we do parse --from and --config options and will patch them onto a fake ServerArgs. *) let fake_server_args = ServerArgs.default_options_with_check_mode ~root:(Path.to_string root) in let fake_server_args = ServerArgs.set_from fake_server_args from in let fake_server_args = match ClientArgs.config command with | None -> fake_server_args | Some config -> ServerArgs.set_config fake_server_args config in let (config, local_config) = ServerConfig.load ~silent:true fake_server_args in HackEventLogger.set_hhconfig_version (ServerConfig.version config |> Config_file.version_to_string_opt); HackEventLogger.set_rollout_flags (ServerLocalConfig.to_rollout_flags local_config); Some local_config in try let exit_status = match command with | ClientCommand.CCheck check_env -> let local_config = Option.value_exn local_config in let init_proc_stack = if String.is_empty from || local_config .ServerLocalConfig.log_init_proc_stack_also_on_absent_from then Some init_proc_stack else None in ClientCheck.main check_env local_config ~init_proc_stack (* never returns; does [Exit.exit] itself *) | ClientCommand.CStart env -> Lwt_utils.run_main (fun () -> ClientStart.main env) | ClientCommand.CStop env -> Lwt_utils.run_main (fun () -> ClientStop.main env) | ClientCommand.CRestart env -> Lwt_utils.run_main (fun () -> ClientRestart.main env) | ClientCommand.CLsp args -> Lwt_utils.run_main (fun () -> ClientLsp.main args ~init_id) | ClientCommand.CRage env -> Lwt_utils.run_main (fun () -> ClientRage.main env (Option.value_exn local_config)) | ClientCommand.CSavedStateProjectMetadata env -> Lwt_utils.run_main (fun () -> ClientSavedStateProjectMetadata.main env (Option.value_exn local_config)) | ClientCommand.CDownloadSavedState env -> Lwt_utils.run_main (fun () -> ClientDownloadSavedState.main env (Option.value_exn local_config)) in Exit.exit exit_status with | exn -> let e = Exception.wrap exn in (* hide the spinner *) ClientSpinner.report ~to_stderr:false ~angery_reaccs_only:false None; (* We trust that if someone raised Exit_with then they had the decency to print out a user-facing message; we will only print out a user-facing message here for uncaught exceptions: lvl=Error gets sent to stderr, but lvl=Info doesn't. *) let (es, lvl) = match exn with | Exit_status.Exit_with es -> (es, Hh_logger.Level.Info) | _ -> (Exit_status.Uncaught_exception e, Hh_logger.Level.Error) in Hh_logger.log ~lvl "CLIENT_BAD_EXIT [%s] %s" command_name (Exit_status.show_expanded es); HackEventLogger.client_bad_exit ~command_name es e; Exit.exit es
OCaml
hhvm/hphp/hack/src/hh_deps.ml
(* * Copyright (c) 2021, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude let children_files (file_list : String.t list) = let module StringSet = Set.Make (String) in let rec children_files_inner acc (parent : String.t) (file_list : String.t list) = let file_list = List.map file_list ~f:(fun s -> if String.equal parent "" then s else parent ^ "/" ^ s) in let on_child acc child = if Path.is_directory (Path.make child) then children_files_inner acc child (Sys.readdir child |> Array.to_list) else StringSet.add acc child in List.fold file_list ~init:acc ~f:on_child in let file_set = children_files_inner StringSet.empty "" file_list in StringSet.to_list file_set let json_array_of_json_strings (l_in : String.t list) = let add_json_string acc s = Hh_json.JSON_String s :: acc in let list_of_json = List.fold_left l_in ~init:[] ~f:add_json_string in Hh_json.JSON_Array list_of_json (*parse command line arguments *) let parse_options () = let input_files = ref [] in let input_dirs = ref [] in let anon_fun filename = input_files := filename :: !input_files in let output_file = ref "hh_deps_out" in let speclist = [ ("-o", Arg.Set_string output_file, "Set output file name"); ( "-d", Arg.String (fun s -> input_dirs := s :: !input_dirs), "Declare next string is a directory" ); ( "--dirs", Arg.Rest (fun s -> input_dirs := s :: !input_dirs), "All remaining strings are directories" ); ] in Arg.parse speclist anon_fun "Get incoming and outgoing dependencies for all specified files, and for all files in specified directories"; (!input_files, !input_dirs, !output_file) (** let get_files_from_dirs input_dirs = *) (*Check files and dirs exist, and are correctly labeled as such*) let validate_paths input_files input_dirs = let check_exists = Unix.handle_unix_error (fun s -> if not (Path.file_exists (Path.make s)) then raise (Unix.Unix_error (Unix.EBADF, "check file exists", s))) in List.iter ~f:check_exists input_files; List.iter ~f:check_exists input_dirs; let check_is_dir = Unix.handle_unix_error (fun s -> if not (Path.is_directory (Path.make s)) then raise (Unix.Unix_error (Unix.ENOTDIR, "check is directory", s))) in List.iter ~f:check_is_dir input_dirs; let check_not_dir = Unix.handle_unix_error (fun s -> if Path.is_directory (Path.make s) then raise (Unix.Unix_error (Unix.EISDIR, "check not directory", s))) in List.iter ~f:check_not_dir input_files let main_deps input_files input_dirs output_file = validate_paths input_files input_dirs; let all_inputs = List.append input_files input_dirs in let all_files = children_files all_inputs in Printf.printf "Output File: %s\n%!" output_file; List.iter input_files ~f:(fun s -> Printf.printf "Input: %s\n%!" s); List.iter input_dirs ~f:(fun s -> Printf.printf "Input dir: %s\n%!" s); let out_file_channel = Sys_utils.open_out_no_fail output_file in Hh_json.json_to_multiline_output out_file_channel (json_array_of_json_strings all_files); Sys_utils.close_out_no_fail output_file out_file_channel (* command line driver *) let () = if !Sys.interactive then () else (* On windows, setting 'binary mode' avoids to output CRLF on stdout. The 'text mode' would not hurt the user in general, but it breaks the testsuite where the output is compared to the expected one (i.e. in given file without CRLF). *) Out_channel.set_binary_mode stdout true; let (input_files, input_dirs, output_file) = parse_options () in main_deps input_files input_dirs output_file
OCaml
hhvm/hphp/hack/src/hh_parse.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. * *) (** * * Usage: hh_parse [OPTIONS] [FILES] * * --full-fidelity-json * --full-fidelity-json-parse-tree * --full-fidelity-errors * --full-fidelity-errors-all * --full-fidelity-ast-s-expression * --program-text * --pretty-print * --pretty-print-json * --show-file-name * * TODO: Parser for things other than scripts: * types, expressions, statements, declarations, etc. *) module Schema = Full_fidelity_schema module SyntaxError = Full_fidelity_syntax_error module SyntaxTree = Full_fidelity_syntax_tree.WithSyntax (Full_fidelity_positioned_syntax) module SourceText = Full_fidelity_source_text module ParserErrors = Full_fidelity_parser_errors.WithSyntax (Full_fidelity_positioned_syntax) open FullFidelityParseArgs (* Prints a single FFP error. *) let print_full_fidelity_error source_text error = let text = SyntaxError.to_positioned_string error (SourceText.offset_to_position source_text) in Printf.printf "%s\n" text let print_ast_check_errors errors = let error_list = Errors.get_error_list errors in List.iter (fun e -> let text = Errors.to_string (User_error.to_absolute e) in if Core.String.is_substring text ~substring:SyntaxError.this_in_static || Core.String.is_substring text ~substring:SyntaxError.toplevel_await_use then Printf.eprintf "%s\n%!" text) error_list let handle_existing_file args filename = let popt = FullFidelityParseArgs.to_parser_options args in (* Parse with the full fidelity parser *) let file = Relative_path.create Relative_path.Dummy filename in let source_text = SourceText.from_file file in let mode = Full_fidelity_parser.parse_mode source_text in let print_errors = args.codegen || args.full_fidelity_errors || args.full_fidelity_errors_all in let env = FullFidelityParseArgs.to_parser_env (* When print_errors is true, the leaked tree will be passed to ParserErrors, * which will consume it. *) ~leak_rust_tree:print_errors ~mode args in let syntax_tree = SyntaxTree.make ~env source_text in let editable = SyntaxTransforms.editable_from_positioned syntax_tree in if args.show_file_name then Printf.printf "%s\n" filename; (if args.program_text then let text = Full_fidelity_editable_syntax.text editable in Printf.printf "%s\n" text); (if args.pretty_print then let pretty = Libhackfmt.format_tree syntax_tree in Printf.printf "%s\n" pretty); (if args.generate_hhi then let hhi = Generate_hhi.go editable in Printf.printf "%s\n" hhi); (if print_errors then let level = if args.full_fidelity_errors_all then ParserErrors.Maximum else ParserErrors.Typical in let hhvm_compat_mode = if args.codegen then ParserErrors.HHVMCompat else ParserErrors.NoCompat in let error_env = ParserErrors.make_env syntax_tree ~level ~hhvm_compat_mode ~codegen:args.codegen ~parser_options:popt in let errors = ParserErrors.parse_errors error_env in List.iter (print_full_fidelity_error source_text) errors); begin let dump_needed = args.full_fidelity_ast_s_expr in let lowered = if dump_needed || print_errors then ( let env = Full_fidelity_ast.make_env ~codegen:args.codegen ~php5_compat_mode:args.php5_compat_mode ~elaborate_namespaces:args.elaborate_namespaces ~include_line_comments:args.include_line_comments ~quick_mode:args.quick_mode ~parser_options:popt file in try let (errors, res) = Errors.do_ (fun () -> Full_fidelity_ast.from_file_with_legacy env) in if print_errors then print_ast_check_errors errors; Some res with | e when print_errors -> let err = Base.Exn.to_string e in let fn = Relative_path.suffix file in (* If we've already found a parsing error, it's okay for lowering to fail *) if not (Errors.currently_has_errors ()) then Printf.eprintf "Warning, lowering failed for %s\n - error: %s\n" fn err; None ) else None in match lowered with | Some res -> if dump_needed then let ast = res.Parser_return.ast in let str = Nast.show_program ast in Printf.printf "%s\n" str | None -> () end; (if args.full_fidelity_json_parse_tree then let json = SyntaxTree.parse_tree_to_json ~ignore_missing:args.ignore_missing_json syntax_tree in let str = Hh_json.json_to_string json ~pretty:args.pretty_print_json in Printf.printf "%s\n" str); (if args.full_fidelity_json then let json = SyntaxTree.to_json ~ignore_missing:args.ignore_missing_json syntax_tree in let str = Hh_json.json_to_string json ~pretty:args.pretty_print_json in Printf.printf "%s\n" str); (if args.full_fidelity_text_json then let json = Full_fidelity_editable_syntax.to_json editable in let str = Hh_json.json_to_string json in Printf.printf "%s\n" str); (if args.full_fidelity_dot then let dot = Full_fidelity_editable_syntax.to_dot editable false in Printf.printf "%s\n" dot); if args.full_fidelity_dot_edges then let dot = Full_fidelity_editable_syntax.to_dot editable true in Printf.printf "%s\n" dot let handle_file args filename = if Path.file_exists (Path.make filename) then handle_existing_file args filename else Printf.printf "File %s does not exist.\n" filename let rec main args files = (if args.schema then let schema = Schema.schema_as_json () in Printf.printf "%s\n" schema); match files with | [] -> () | file :: tail -> Unix.handle_unix_error (handle_file args) file; main args tail let () = let args = parse_args () in EventLogger.init_fake (); let handle = SharedMem.init ~num_workers:0 SharedMem.default_config in ignore (handle : SharedMem.handle); main args args.files
OCaml
hhvm/hphp/hack/src/hh_server.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. * *) (** * Hack for HipHop: type checker daemon code. * * See README for high level overview. * * Interesting files/directory: * - hh_server.ml: contains mostly the ugly inotify code. * * Parser code: * The parser is a recursive descent full-fidelity parser * - parser/ * * Naming: * Naming consists in "solving" all the names (making sure every * class/variable/etc. are bound). * - naming/nast.ml: * Named abstract syntax tree (the datastructure). * - naming/naming.ml: * Naming operations (takes an ast and returns a nast). * - naming/nastInitCheck.ml: * Checks that all the members in a class are always properly initialized. * * Typing: * - typing/typing_defs.ml: * The datastructures required for typing. * - typing/typing_env.ml: * All the operations on the typing environment (e.g. unifying types). * - typing/typing_reason.ml: * Documents why something has a given type (witness system). * - typing/typing.ml: * Where everything happens, in two phases: * 1. type declarations: we build the environment where we know the type of * everything. (see make_env). * 2. for every function and method definition, we check that their * implementation matches their signature (assuming that all other * signatures are correct). *) let () = MonitorStart.start ()
OCaml
hhvm/hphp/hack/src/hh_single_ai.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 (*****************************************************************************) (* Types, constants *) (*****************************************************************************) type options = { files: string list; extra_builtins: string list; ai_options: Ai_options.t; error_format: Errors.format; no_builtins: bool; tcopt: GlobalOptions.t; } (** If the user passed --root, then all pathnames have to be canonicalized. The fact of whether they passed --root is kind of stored inside Relative_path global variables: the Relative_path.(path_of_prefix Root) is either "/" if they failed to pass something, or the thing that they passed. *) let use_canonical_filenames () = not (String.equal "/" (Relative_path.path_of_prefix Relative_path.Root)) (* Canonical builtins from our hhi library *) let hhi_builtins = Hhi.get_raw_hhi_contents () (* All of the stuff that hh_single_type_check relies on is sadly not contained * in the hhi library, so we include a very small number of magic builtins *) let magic_builtins = [| ( "hh_single_type_check_magic.hhi", "<?hh\n" ^ "namespace {\n" ^ "async function gena<Tk as arraykey, Tv>( KeyedTraversable<Tk, Awaitable<Tv>> $awaitables, ): Awaitable<darray<Tk, Tv>>;\n" ^ "function hh_show(<<__AcceptDisposable>> $val) {}\n" ^ "function hh_expect(<<__AcceptDisposable>> $val) {}\n" ^ "function hh_expect_equivalent(<<__AcceptDisposable>> $val) {}\n" ^ "function hh_show_env() {}\n" ^ "function hh_log_level($key, $level) {}\n" ^ "function hh_force_solve () {}" ^ "}\n" ^ "namespace HH\\Lib\\Tuple{\n" ^ "function gen();\n" ^ "function from_async();\n" ^ "}\n" ); |] (*****************************************************************************) (* Helpers *) (*****************************************************************************) let die str = let oc = stderr in Out_channel.output_string oc str; Out_channel.close oc; exit 2 let print_error format ?(oc = stderr) l = let formatter = match format with | Errors.Context -> (fun e -> Contextual_error_formatter.to_string e) | Errors.Raw -> (fun e -> Raw_error_formatter.to_string e) | Errors.Plain -> (fun e -> Errors.to_string e) | Errors.Highlighted -> Highlighted_error_formatter.to_string in let absolute_errors = if use_canonical_filenames () then User_error.to_absolute l else User_error.to_absolute_for_test l in Out_channel.output_string oc (formatter absolute_errors) let comma_string_to_iset (s : string) : ISet.t = Str.split (Str.regexp ", *") s |> List.map ~f:int_of_string |> ISet.of_list let parse_options () = let fn_ref = ref [] in let extra_builtins = ref [] in let usage = Printf.sprintf "Usage: %s filename\n" Sys.argv.(0) in let no_builtins = ref false in let ai_options = ref None in let set_ai_options x = let options = Ai_options.prepare ~server:false x in match !ai_options with | None -> ai_options := Some options | Some existing -> ai_options := Some (Ai_options.merge_for_unit_tests existing options) in let error_format = ref Errors.Highlighted in let check_xhp_attribute = ref false in let disable_xhp_element_mangling = ref false in let disable_xhp_children_declarations = ref false in let enable_xhp_class_modifier = ref false in let allowed_fixme_codes_strict = ref None in let disable_hh_ignore_error = ref 0 in let allowed_decl_fixme_codes = ref None in let options = [ ( "--extra-builtin", Arg.String (fun f -> extra_builtins := f :: !extra_builtins), " HHI file to parse and declare" ); ( "--ai", Arg.String set_ai_options, " Run the abstract interpreter (Zoncolan)" ); ( "--error-format", Arg.String (fun s -> match s with | "raw" -> error_format := Errors.Raw | "plain" -> error_format := Errors.Plain | "context" -> error_format := Errors.Context | "highlighted" -> error_format := Errors.Highlighted | _ -> print_string "Warning: unrecognized error format.\n"), "<raw|context|highlighted|plain> Error formatting style; (default: highlighted)" ); ( "--check-xhp-attribute", Arg.Set check_xhp_attribute, " Typechecks xhp required attributes" ); ( "--disable-xhp-element-mangling", Arg.Set disable_xhp_element_mangling, "Disable mangling of XHP elements :foo. That is, :foo:bar is now \\foo\\bar, not xhp_foo__bar" ); ( "--disable-xhp-children-declarations", Arg.Set disable_xhp_children_declarations, "Disable XHP children declarations, e.g. children (foo, bar+)" ); ( "--enable-xhp-class-modifier", Arg.Set enable_xhp_class_modifier, "Enable the XHP class modifier, xhp class name {} will define an xhp class." ); ( "--allowed-fixme-codes-strict", Arg.String (fun s -> allowed_fixme_codes_strict := Some (comma_string_to_iset s)), "List of fixmes that are allowed in strict mode." ); ( "--disable-hh-ignore-error", Arg.Int (( := ) disable_hh_ignore_error), " Forbid HH_IGNORE_ERROR comments as an alternative to HH_FIXME, or treat them as normal comments." ); ( "--allowed-decl-fixme-codes", Arg.String (fun s -> allowed_decl_fixme_codes := Some (comma_string_to_iset s)), "List of fixmes that are allowed in declarations." ); ] in let options = Arg.align ~limit:25 options in Arg.parse options (fun fn -> fn_ref := fn :: !fn_ref) usage; let (fns, ai_options) = match (!fn_ref, !ai_options) with | ([], _) | (_, None) -> die usage | (x, Some ai_options) -> (x, ai_options) in let root = Path.make "/" (* if none specified, we use this dummy *) in let tcopt = GlobalOptions.set ~tco_saved_state:GlobalOptions.default_saved_state ~allowed_fixme_codes_strict: (Option.value !allowed_fixme_codes_strict ~default:ISet.empty) ~po_disable_hh_ignore_error:!disable_hh_ignore_error ~po_keep_user_attributes:true ~tco_check_xhp_attribute:!check_xhp_attribute ~po_disable_xhp_element_mangling:!disable_xhp_element_mangling ~po_disable_xhp_children_declarations:!disable_xhp_children_declarations ~po_enable_xhp_class_modifier:!enable_xhp_class_modifier ~po_allowed_decl_fixme_codes: (Option.value !allowed_decl_fixme_codes ~default:ISet.empty) GlobalOptions.default in Errors.allowed_fixme_codes_strict := GlobalOptions.allowed_fixme_codes_strict tcopt; Errors.report_pos_from_reason := TypecheckerOptions.report_pos_from_reason tcopt; ( { files = fns; extra_builtins = !extra_builtins; ai_options; error_format = !error_format; no_builtins = !no_builtins; tcopt; }, root, None, Ai_options.modify_shared_mem ai_options SharedMem.default_config ) let parse_and_name ctx files_contents = Relative_path.Map.mapi files_contents ~f:(fun fn contents -> (* Get parse errors *) let _ = Errors.run_in_context fn (fun () -> let popt = Provider_context.get_tcopt ctx in let parsed_file = Full_fidelity_ast.defensive_program popt fn contents in let ast = let { Parser_return.ast; _ } = parsed_file in if ParserOptions.deregister_php_stdlib popt then Nast.deregister_ignored_attributes ast else ast in Ast_provider.provide_ast_hint fn ast Ast_provider.Full; { parsed_file with Parser_return.ast }) in match Direct_decl_utils.direct_decl_parse_and_cache ctx fn with | None -> failwith "no file contents" | Some decls -> Direct_decl_utils.decls_to_fileinfo fn decls) let parse_name_and_skip_decl ctx files_contents = Errors.do_ (fun () -> let files_info = parse_and_name ctx files_contents in Relative_path.Map.iter files_info ~f:(fun fn fileinfo -> let _failed_naming_fns = Naming_global.ndecl_file_and_get_conflict_files ctx fn fileinfo in ()); files_info) let handle_mode ai_options ctx files_info parse_errors error_format = if not (List.is_empty parse_errors) then List.iter ~f:(print_error error_format) parse_errors else (* No type check *) Ai.do_ files_info ai_options ctx (*****************************************************************************) (* Main entry point *) (*****************************************************************************) let decl_and_run_mode { files; extra_builtins; ai_options; error_format; no_builtins; tcopt } (popt : TypecheckerOptions.t) (hhi_root : Path.t) (naming_table_path : string option) : unit = Ident.track_names := true; let builtins = if no_builtins then Relative_path.Map.empty else let extra_builtins = let add_file_content map filename = Relative_path.create Relative_path.Dummy filename |> Multifile.file_to_file_list |> List.map ~f:(fun (path, contents) -> (Filename.basename (Relative_path.suffix path), contents)) |> List.unordered_append map in extra_builtins |> List.fold ~f:add_file_content ~init:[] |> Array.of_list in let magic_builtins = Array.append magic_builtins extra_builtins in (* Check that magic_builtin filenames are unique *) let () = let n_of_builtins = Array.length magic_builtins in let n_of_unique_builtins = Array.to_list magic_builtins |> List.map ~f:fst |> SSet.of_list |> SSet.cardinal in if n_of_builtins <> n_of_unique_builtins then die "Multiple magic builtins share the same base name.\n" in Array.iter magic_builtins ~f:(fun (file_name, file_contents) -> let file_path = Path.concat hhi_root file_name in let file = Path.to_string file_path in Sys_utils.try_touch (Sys_utils.Touch_existing { follow_symlinks = true }) file; Sys_utils.write_file ~file file_contents); (* Take the builtins (file, contents) array and create relative paths *) Array.fold (Array.append magic_builtins hhi_builtins) ~init:Relative_path.Map.empty ~f:(fun acc (f, src) -> let f = Path.concat hhi_root f |> Path.to_string in Relative_path.Map.add acc ~key:(Relative_path.create Relative_path.Hhi f) ~data:src) in let files = if use_canonical_filenames () then files |> List.map ~f:Sys_utils.realpath |> List.map ~f:(fun s -> Option.value_exn s) |> List.map ~f:Relative_path.create_detect_prefix else files |> List.map ~f:(Relative_path.create Relative_path.Dummy) in let files_contents = List.fold files ~f:(fun acc filename -> let files_contents = Multifile.file_to_files filename in Relative_path.Map.union acc files_contents) ~init:Relative_path.Map.empty in (* Merge in builtins *) let files_contents_with_builtins = Relative_path.Map.fold builtins ~f: begin (fun k src acc -> Relative_path.Map.add acc ~key:k ~data:src) end ~init:files_contents in Relative_path.Map.iter files_contents ~f:(fun filename contents -> File_provider.(provide_file_for_tests filename contents)); (* Don't declare all the filenames in batch_errors mode *) let to_decl = files_contents_with_builtins in let ctx = Provider_context.empty_for_test ~popt ~tcopt ~deps_mode:(Typing_deps_mode.InMemoryMode None) in (* We make the following call for the side-effect of updating ctx's "naming-table fallback" so it will look in the sqlite database for names it doesn't know. This function returns the forward naming table, but we don't care about that; it's only needed for tools that process file changes, to know in the event of a file-change which old symbols used to be defined in the file. *) let _naming_table_for_root : Naming_table.t option = Option.map naming_table_path ~f:(fun path -> Naming_table.load_from_sqlite ctx path) in let (errors, files_info) = parse_name_and_skip_decl ctx to_decl in handle_mode ai_options ctx files_info (Errors.get_sorted_error_list errors) error_format let main_hack ({ tcopt; _ } as opts) (root : Path.t) (naming_table : string option) (sharedmem_config : SharedMem.config) : unit = Folly.ensure_folly_init (); (* TODO: We should have a per file config *) Sys_utils.signal Sys.sigusr1 (Sys.Signal_handle Typing.debug_print_last_pos); EventLogger.init_fake (); let () = FlashSharedMem.pre_init None in let (_handle : SharedMem.handle) = SharedMem.init ~num_workers:0 sharedmem_config in Tempfile.with_tempdir (fun hhi_root -> Hhi.set_hhi_root_for_unit_test hhi_root; Relative_path.set_path_prefix Relative_path.Root root; Relative_path.set_path_prefix Relative_path.Hhi hhi_root; Relative_path.set_path_prefix Relative_path.Tmp (Path.make "tmp"); decl_and_run_mode opts tcopt hhi_root naming_table; TypingLogger.flush_buffers ()) (* command line driver *) let () = if !Sys.interactive then () else (* On windows, setting 'binary mode' avoids to output CRLF on stdout. The 'text mode' would not hurt the user in general, but it breaks the testsuite where the output is compared to the expected one (i.e. in given file without CRLF). *) Out_channel.set_binary_mode stdout true; let (options, root, naming_table, sharedmem_config) = parse_options () in Unix.handle_unix_error main_hack options root naming_table sharedmem_config
OCaml
hhvm/hphp/hack/src/hh_single_complete.ml
(* * Copyright (c) 2021, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude let comma_string_to_iset (s : string) : ISet.t = Str.split (Str.regexp ", *") s |> List.map ~f:int_of_string |> ISet.of_list (*****************************************************************************) (* Types, constants *) (*****************************************************************************) type mode = | NoMode | Autocomplete of { is_manually_invoked: bool } | Autocomplete_glean of { dry_run: bool } | Search of { glean_only: bool; (** if true, uses glean; if false, uses ServerSearch *) dry_run: bool; (** only applies to [glean_only]; skips actually running the glean query *) } | Findrefs_glean of { dry_run: bool } type options = { files: string list; extra_builtins: string list; mode: mode; no_builtins: bool; naming_table_path: string option; tcopt: GlobalOptions.t; } (* Canonical builtins from our hhi library *) let hhi_builtins = Hhi.get_raw_hhi_contents () (* All of the stuff that hh_single_type_check relies on is sadly not contained * in the hhi library, so we include a very small number of magic builtins *) let magic_builtins = [| ( "hh_single_type_check_magic.hhi", "<?hh\n" ^ "namespace {\n" ^ "async function gena<Tk as arraykey, Tv>( KeyedTraversable<Tk, Awaitable<Tv>> $awaitables, ): Awaitable<darray<Tk, Tv>>;\n" ^ "function hh_show(<<__AcceptDisposable>> $val) {}\n" ^ "function hh_expect<T>(<<__AcceptDisposable>> $val) {}\n" ^ "function hh_expect_equivalent<T>(<<__AcceptDisposable>> $val) {}\n" ^ "function hh_show_env() {}\n" ^ "function hh_log_level($key, $level) {}\n" ^ "function hh_force_solve () {}" ^ "}\n" ^ "namespace HH\\Lib\\Tuple{\n" ^ "function gen();\n" ^ "function from_async();\n" ^ "}\n" ); |] (*****************************************************************************) (* Helpers *) (*****************************************************************************) let die str = let oc = stderr in Out_channel.output_string oc str; Out_channel.close oc; exit 2 let parse_options () = let fn_ref = ref [] in let extra_builtins = ref [] in let usage = Printf.sprintf "Usage: %s filename\n" Sys.argv.(0) in let mode = ref NoMode in let no_builtins = ref false in let set_mode x () = match !mode with | NoMode -> mode := x | _ -> raise (Arg.Bad "only a single mode should be specified") in let set name reference value = match !reference with | None -> reference := Some value | Some _ -> failwith (Printf.sprintf "Attempted to set %s twice" name) in let check_xhp_attribute = ref false in let disable_xhp_element_mangling = ref false in let disable_xhp_children_declarations = ref false in let enable_xhp_class_modifier = ref false in let root = ref None in let naming_table = ref None in let saved_state_manifold_api_key = ref None in let glean_reponame = ref "" in let auto_namespace_map = ref None in let options = [ ( "--extra-builtin", Arg.String (fun f -> extra_builtins := f :: !extra_builtins), " HHI file to parse and declare" ); ( "--no-builtins", Arg.Set no_builtins, " Don't use builtins (e.g. ConstSet); implied by --root" ); ( "--check-xhp-attribute", Arg.Set check_xhp_attribute, " Typechecks xhp required attributes" ); ( "--disable-xhp-element-mangling", Arg.Set disable_xhp_element_mangling, "Disable mangling of XHP elements :foo. That is, :foo:bar is now \\foo\\bar, not xhp_foo__bar" ); ( "--disable-xhp-children-declarations", Arg.Set disable_xhp_children_declarations, "Disable XHP children declarations, e.g. children (foo, bar+)" ); ( "--enable-xhp-class-modifier", Arg.Set enable_xhp_class_modifier, "Enable the XHP class modifier, xhp class name {} will define an xhp class." ); ( "--auto-namespace-map", Arg.String (fun m -> auto_namespace_map := Some (ServerConfig.convert_auto_namespace_to_map m)), " Alias namespaces" ); ( "--auto-complete", Arg.Unit (set_mode (Autocomplete { is_manually_invoked = false })), " Produce autocomplete suggestions as if triggered by trigger character" ); ( "--auto-complete-manually-invoked", Arg.Unit (set_mode (Autocomplete { is_manually_invoked = true })), " Produce autocomplete suggestions as if manually triggered by user" ); ( "--auto-complete-show-glean", Arg.Unit (set_mode (Autocomplete_glean { dry_run = true })), " Show the glean query for the prefix contained in the file" ); ( "--auto-complete-glean", Arg.Unit (set_mode (Autocomplete_glean { dry_run = false })), " Show the glean query for the prefix contained in the file, and run that query" ); ( "--search-show-glean", Arg.Unit (set_mode (Search { glean_only = true; dry_run = true })), " Show the glean query for newline-separated queries in file" ); ( "--search-glean", Arg.Unit (set_mode (Search { glean_only = true; dry_run = false })), " Show+run the glean query for newline-separated queries in file" ); ( "--search", Arg.Unit (set_mode (Search { glean_only = false; dry_run = false })), " Run the search (including new definitions) for newline-separated queries in file" ); ( "--find-refs-show-glean", Arg.Unit (set_mode (Findrefs_glean { dry_run = true })), " Show the glean query for newline-separated queries in file" ); ( "--find-refs-glean", Arg.Unit (set_mode (Findrefs_glean { dry_run = false })), " Show+run the glean query for newline-separated queries in file" ); ( "--manifold-api-key", Arg.String (set "manifold api key" saved_state_manifold_api_key), " API key used to download a saved state from Manifold (optional)" ); ( "--naming-table", Arg.String (fun s -> naming_table := Some s), " Naming table, to typecheck undefined symbols; needs --root." ^ " (Hint: buck2 run //hphp/hack/src/hh_naming_table_builder)" ); ( "--root", Arg.String (fun s -> root := Some s), " Root for where to typecheck undefined symbols; needs --naming-table" ); ( "--glean-reponame", Arg.String (fun str -> glean_reponame := str), " Glean repo for autocompleting undefined symbols" ); ] in let options = Arg.align ~limit:25 options in Arg.parse options (fun fn -> fn_ref := fn :: !fn_ref) usage; let fns = match (!fn_ref, !mode) with | ([], _) -> die usage | (x, _) -> x in if Option.is_some !naming_table && Option.is_none !root then failwith "--naming-table needs --root"; begin match !mode with | Search { glean_only = false; _ } when (not (String.is_empty !glean_reponame)) && (Option.is_none !root || Option.is_none !naming_table) -> (* --search --glean-reponame looks up glean to find symbol names, but then uses reverse-naming-table and root to fetch the AST and find its position. *) failwith "--search --glean-reponame needs --naming-table and --root" | _ -> () end; (* --root implies certain things... *) let (allowed_fixme_codes_strict, sharedmem_config, root) = match !root with | None -> let allowed_fixme_codes_strict = None in let sharedmem_config = SharedMem.default_config in let root = Path.make "/" (* if none specified, we use this dummy *) in (allowed_fixme_codes_strict, sharedmem_config, root) | Some root -> if Option.is_none !naming_table then failwith "--root needs --naming-table"; (* builtins are already provided by project at --root, so we shouldn't provide our own *) no_builtins := true; (* Following will throw an exception if .hhconfig not found *) let (_config_hash, config) = Config_file.parse_hhconfig (Filename.concat root Config_file.file_path_relative_to_repo_root) in (* We will pick up values from .hhconfig, unless they've been overridden at the command-line. *) if Option.is_none !auto_namespace_map then auto_namespace_map := config |> Config_file.Getters.string_opt "auto_namespace_map" |> Option.map ~f:ServerConfig.convert_auto_namespace_to_map; let allowed_fixme_codes_strict = config |> Config_file.Getters.string_opt "allowed_fixme_codes_strict" |> Option.map ~f:comma_string_to_iset in let sharedmem_config = ServerConfig.make_sharedmem_config config (ServerArgs.default_options ~root) ServerLocalConfig.default in (* Path.make canonicalizes it, i.e. resolves symlinks *) let root = Path.make root in (allowed_fixme_codes_strict, sharedmem_config, root) in let tcopt = GlobalOptions.set ~tco_saved_state: (GlobalOptions.default_saved_state |> GlobalOptions.with_saved_state_manifold_api_key !saved_state_manifold_api_key) ~tco_check_xhp_attribute:!check_xhp_attribute ~po_disable_xhp_element_mangling:!disable_xhp_element_mangling ~po_disable_xhp_children_declarations:!disable_xhp_children_declarations ~po_enable_xhp_class_modifier:!enable_xhp_class_modifier ~tco_everything_sdt:true ~tco_enable_sound_dynamic:true ?po_auto_namespace_map:!auto_namespace_map ~allowed_fixme_codes_strict: (Option.value allowed_fixme_codes_strict ~default:ISet.empty) ~glean_reponame:!glean_reponame GlobalOptions.default in ( { files = fns; extra_builtins = !extra_builtins; mode = !mode; no_builtins = !no_builtins; naming_table_path = !naming_table; tcopt; }, root, sharedmem_config ) (** This is an almost-pure function which returns what we get out of parsing. The only side-effect it has is on the global errors list. *) let parse_and_name ctx files_contents = Relative_path.Map.mapi files_contents ~f:(fun fn contents -> (* Get parse errors. *) let () = Errors.run_in_context fn (fun () -> let popt = Provider_context.get_tcopt ctx in let parsed_file = Full_fidelity_ast.defensive_program popt fn contents in let ast = let { Parser_return.ast; _ } = parsed_file in if ParserOptions.deregister_php_stdlib popt then Nast.deregister_ignored_attributes ast else ast in Ast_provider.provide_ast_hint fn ast Ast_provider.Full; ()) in match Direct_decl_utils.direct_decl_parse ctx fn with | None -> failwith "no file contents" | Some decls -> ( Direct_decl_parser.decls_to_fileinfo fn decls, Direct_decl_parser.decls_to_addenda decls )) (** This function is used for gathering naming and parsing errors, and the side-effect of updating the global reverse naming table (and picking up duplicate-name errors along the way), and for the side effect of updating the decl heap (and picking up decling errors along the way). *) let parse_name_and_decl ctx files_contents = Errors.do_ (fun () -> (* parse_and_name has side effect of reporting errors *) let files_info_and_addenda = parse_and_name ctx files_contents in (* ndecl_file has side effect of updating the global reverse naming-table, and reporting errors. *) Relative_path.Map.iter files_info_and_addenda ~f:(fun fn (fileinfo, _addenda) -> let _failed_naming_fns = Naming_global.ndecl_file_and_get_conflict_files ctx fn fileinfo in ()); (* Decl.make_env has the side effect of updating the decl heap, and reporting errors. *) Relative_path.Map.iter files_info_and_addenda ~f:(fun fn _ -> Decl.make_env ~sh:SharedMem.Uses ctx fn); files_info_and_addenda) (** Our tests expect files that contain newline-separated queries. This function takes a file and splits it on newlines into queries, trimming and filtering out blank lines and //comment lines. To help avoid foot-guns (in the form of the tester accidentally forgetting <?hh so that hack source code would get interpreted as queries), we fail if any line contains a space in it... all the queries we care about don't have spaces in it. *) let extract_nonblank_lines contents = String_utils.split_on_newlines contents |> List.map ~f:String.strip |> List.filter ~f:(fun s -> if String.is_empty s then false else if String.is_prefix s ~prefix:"//" then false else begin if String.is_substring s ~substring:" " then failwith ("Files must be either hack with <?hh, or lists of query_text; not " ^ s); true end) (** This helper invokes ServerAutoComplete, with the additional arguments it needs to describe the "context" of the AUTO332 i.e. surrounding characters. *) let do_auto332 ~(ctx : Provider_context.t) ~(is_manually_invoked : bool) ~(sienv_ref : SearchUtils.si_env ref) ~(naming_table : Naming_table.t) (path : Relative_path.t) (contents : string) : AutocompleteTypes.autocomplete_item list Utils.With_complete_flag.t = (* Search backwards: there should only be one /real/ case. If there's multiple, *) (* guess that the others are preceding explanation comments *) let offset = Str.search_backward (Str.regexp AutocompleteTypes.autocomplete_token) contents (String.length contents) in let pos = File_content.offset_to_position contents offset in let (ctx, entry) = Provider_context.add_or_overwrite_entry_contents ~ctx ~path ~contents in let autocomplete_context = ServerAutoComplete.get_autocomplete_context ~file_content:contents ~pos ~is_manually_invoked in ServerAutoComplete.go_at_auto332_ctx ~ctx ~entry ~sienv_ref ~autocomplete_context ~naming_table (** This function takes a list of searches of the form (title, query_text, context, kind_filter). If [show_query_text] then it prints each search. It obtains and prints the Glean angle query for it, using [Glean_autocomplete_query.make_symbols_query]. If not [dry_run] then it runs the query against [reponame] and displays the results, plus timing information. *) let do_glean_symbol_searches ~reponame ~dry_run ~show_query_text (searches : (string * string * SearchTypes.autocomplete_type * SearchTypes.si_kind option) list) : unit = let handle = if dry_run then None else let () = if String.is_empty reponame then failwith "--glean-reponame required" in let () = Folly.ensure_folly_init () in Some (Glean.initialize ~reponame ~prev_init_time:None |> Option.value_exn) in List.iter searches ~f:(fun (title, query_text, context, kind_filter) -> if List.length searches > 1 then Printf.printf "//// %s\n" title; let angle = Glean_autocomplete_query.make_symbols_query ~prefix:query_text ~context ~kind_filter in let query_text_for_show = Printf.sprintf "%s [%s,%s]" query_text (SearchTypes.show_autocomplete_type context) (Option.value_map kind_filter ~default:"*" ~f:SearchTypes.show_si_kind) in if show_query_text then Printf.printf "query_text:\n%s\n\n" query_text_for_show; Printf.printf "query:\n%s\n\n%!" angle; if not dry_run then begin let start_time = Unix.gettimeofday () in let (results, _is_complete) = Glean.query_autocomplete (Option.value_exn handle) ~query_text ~max_results:100 ~context ~kind_filter in List.iter results ~f:(fun { SearchTypes.si_name; si_kind; si_file; si_fullname = _ } -> let file = match si_file with | SearchTypes.SI_Filehash hash -> Printf.sprintf "#%s" hash | SearchTypes.SI_Path path -> Relative_path.show path in Printf.printf "[%s] %s - %s\n%!" (SearchTypes.show_si_kind si_kind) si_name file); Printf.printf "\n--> %s - %d results, %0.3fs\n\n%!" query_text_for_show (List.length results) (Unix.gettimeofday () -. start_time) end) (** This handles "--auto-complete-show-glean" and "--auto-complete-glean". The input [filename] is either a single file or a multifile. It can contain <?hh files, or newline-separated query_text files. In the case of <?hh files, it figures out query_text+context+filter based on the AUTO332 in that file (if any). Once it has the search (comprising query_text, context, filter) it either simply shows the glean angle query, or also runs the query against glean and shows the results. *) let handle_autocomplete_glean ctx sienv naming_table ~dry_run filename = let files_contents = Multifile.file_to_file_list filename in let any_hack_files = List.exists files_contents ~f:(fun (_path, content) -> String.is_prefix content ~prefix:"<?hh") in let searches = if any_hack_files then files_contents |> List.filter_map ~f:(fun (path, contents) -> (* We're going to run the file through autocomplete, but with a mock sienv, one which tells us what [SymbolIndex.find] was performed -- i.e. what query_text, context, filter. *) let search = ref None in let mock_sienv = SymbolIndex.mock ~on_find:(fun ~query_text ~context ~kind_filter -> search := Some ( Multifile.short_suffix path, query_text, context, kind_filter ); []) in let sienv_ref = ref mock_sienv in let _results = do_auto332 ~ctx ~is_manually_invoked:true ~naming_table ~sienv_ref path contents in !search) else files_contents |> List.concat_map ~f:(fun (_path, contents) -> extract_nonblank_lines contents |> List.map ~f:(fun s -> (s, s, SearchTypes.Acid, None))) in do_glean_symbol_searches searches ~reponame:sienv.SearchUtils.glean_reponame ~dry_run ~show_query_text:any_hack_files; () (** This handles "--auto-complete" and "--auto-complete-manually-invoked". It parses the input file/multifiles for AUTO332, and runs them through ServerAutoComplete, and shows the results. These results will include both locally defined symbols in input files if present, and glean results if --glean-reponame has been provided. *) let handle_autocomplete ctx sienv naming_table ~is_manually_invoked filename = let files_contents = Multifile.file_to_file_list filename in let files_with_token = files_contents |> List.filter ~f:(fun (_path, contents) -> String.is_substring contents ~substring:AutocompleteTypes.autocomplete_token) in let show_file_titles = List.length files_with_token > 1 in List.iter files_with_token ~f:(fun (path, contents) -> let sienv_ref = ref sienv in let result = do_auto332 ~ctx ~is_manually_invoked ~sienv_ref ~naming_table path contents in if show_file_titles then Printf.printf "//// %s\n" (Multifile.short_suffix path); List.iter result.Utils.With_complete_flag.value ~f:(fun r -> let open AutocompleteTypes in Printf.printf "%s\n" r.res_label; List.iter r.res_additional_edits ~f:(fun (s, _) -> Printf.printf " INSERT %s\n" s); Printf.printf " INSERT %s\n" (match r.res_insert_text with | InsertLiterally s -> s | InsertAsSnippet { snippet; _ } -> snippet); Printf.printf " %s\n" r.res_detail; match r.res_documentation with | Some doc -> List.iter (String.split_lines doc) ~f:(fun line -> Printf.printf " %s\n" line) | None -> ())) (** This handles --search, --search-glean, --search-show-glean. The filename be a single file or a multifile, and accepts both <?hh files that define symbols, and newline-separated lists of search queries. For each query, it either shows the angle query (--search-show-glean) or shows the query and runs it and shows the results (--search-glean) or runs the query through ServerSearch (--search) which will also pick up any symbols defined in <?hh files. Note that in the final case, ServerSearch uses the naming-table and root in [ctx] to validate the results it got from glean -- to find their filename and load the file and get its AST -- and if glean gives results without [ctx] being set up right then the glean results will be filtered out. *) let handle_search ctx sienv ~glean_only ~dry_run filename = let queries = Multifile.file_to_file_list filename |> List.filter ~f:(fun (_path, contents) -> not (String.is_prefix contents ~prefix:"<?hh")) |> List.concat_map ~f:(fun (_path, contents) -> extract_nonblank_lines contents) in if glean_only then queries |> List.map ~f:(fun query -> (query, query, SearchTypes.Ac_workspace_symbol, None)) |> do_glean_symbol_searches ~reponame:sienv.SearchUtils.glean_reponame ~dry_run ~show_query_text:true else List.iter queries ~f:(fun query -> Printf.printf "query: %s\n%!" query; let sienv_ref = ref sienv in let results = ServerSearch.go ctx query ~kind_filter:"" sienv_ref in List.iter results ~f:(fun { SearchUtils.name; pos; result_type } -> let filename = Pos.filename pos |> Filename.basename in let (line, start_, end_) = Pos.info_pos pos in Printf.printf " %s:%s - %s:%d:%d-%d\n%!" name (SearchTypes.show_si_kind result_type) filename line start_ end_)); () let handle_findrefs_glean sienv ~dry_run filename = (* We expect a newline-separated query file. See ServerCommandTypes.Find_refs.symbol_and_action_to_string_exn for documentation and examples of that format. Another way to obtain examples is to open a hack file in the IDE, right-click > FindRefs, and then examine [hh --client-logname] to find the invocation of [hh --ide-find-refs-by-symbol-name <EXAMPLE>]. *) let queries = Sys_utils.cat (Relative_path.to_absolute filename) |> extract_nonblank_lines in let reponame = sienv.SearchUtils.glean_reponame in let handle = if dry_run then None else let () = if String.is_empty reponame then failwith "--glean-reponame required" in let () = Folly.ensure_folly_init () in Some (Glean.initialize ~reponame ~prev_init_time:None |> Option.value_exn) in List.iter queries ~f:(fun query -> let { FindRefsWireFormat.CliArgs.action; _ } = FindRefsWireFormat.CliArgs.from_string_exn query in Printf.printf "//// %s\n" query; let angle = Glean_autocomplete_query.make_refs_query ~action in Printf.printf "query:\n%s\n\n%!" angle; if not dry_run then begin let start_time = Unix.gettimeofday () in let results = Glean.query_refs (Option.value_exn handle) ~action ~max_results:10 in List.iter results ~f:(fun path -> Printf.printf "%s\n" (Relative_path.show path)); Printf.printf "\n--> %s - %d results, %0.3fs\n\n%!" query (List.length results) (Unix.gettimeofday () -. start_time) end); () let handle_mode mode filenames ctx (sienv : SearchUtils.si_env) naming_table = let filename = match filenames with | [x] -> x | _ -> die "Only single file expected" in match mode with | NoMode -> die "Exactly one mode must be set up" | Search { glean_only; dry_run } -> handle_search ctx sienv ~glean_only ~dry_run filename | Autocomplete_glean { dry_run } -> handle_autocomplete_glean ctx sienv naming_table ~dry_run filename | Autocomplete { is_manually_invoked } -> handle_autocomplete ctx sienv naming_table ~is_manually_invoked filename | Findrefs_glean { dry_run } -> handle_findrefs_glean sienv ~dry_run filename (*****************************************************************************) (* Main entry point *) (*****************************************************************************) let decl_and_run_mode { files; extra_builtins; mode; no_builtins; tcopt; naming_table_path } (popt : TypecheckerOptions.t) (hhi_root : Path.t) : unit = Ident.track_names := true; let builtins = if no_builtins then Relative_path.Map.empty else let extra_builtins = let add_file_content map filename = Relative_path.create Relative_path.Dummy filename |> Multifile.file_to_file_list |> List.map ~f:(fun (path, contents) -> (Filename.basename (Relative_path.suffix path), contents)) |> List.unordered_append map in extra_builtins |> List.fold ~f:add_file_content ~init:[] |> Array.of_list in let magic_builtins = Array.append magic_builtins extra_builtins in (* Check that magic_builtin filenames are unique *) let () = let n_of_builtins = Array.length magic_builtins in let n_of_unique_builtins = Array.to_list magic_builtins |> List.map ~f:fst |> SSet.of_list |> SSet.cardinal in if n_of_builtins <> n_of_unique_builtins then die "Multiple magic builtins share the same base name.\n" in Array.iter magic_builtins ~f:(fun (file_name, file_contents) -> let file_path = Path.concat hhi_root file_name in let file = Path.to_string file_path in Sys_utils.try_touch (Sys_utils.Touch_existing { follow_symlinks = true }) file; Sys_utils.write_file ~file file_contents); (* Take the builtins (file, contents) array and create relative paths *) Array.fold (Array.append magic_builtins hhi_builtins) ~init:Relative_path.Map.empty ~f:(fun acc (f, src) -> let f = Path.concat hhi_root f |> Path.to_string in Relative_path.Map.add acc ~key:(Relative_path.create Relative_path.Hhi f) ~data:src) in let files = files |> List.map ~f:(Relative_path.create Relative_path.Dummy) in let hh_files_contents = List.fold files ~f:(fun acc filename -> let hh_files_contents = Multifile.file_to_files filename |> Relative_path.Map.filter ~f:(fun _path contents -> String.is_prefix contents ~prefix:"<?hh") in Relative_path.Map.union acc hh_files_contents) ~init:Relative_path.Map.empty in (* Merge in builtins *) let hh_files_contents_with_builtins = Relative_path.Map.fold builtins ~f: begin (fun k src acc -> Relative_path.Map.add acc ~key:k ~data:src) end ~init:hh_files_contents in Relative_path.Map.iter hh_files_contents ~f:(fun filename contents -> File_provider.provide_file_for_tests filename contents); let to_decl = hh_files_contents_with_builtins in let ctx = Provider_context.empty_for_test ~popt ~tcopt ~deps_mode:(Typing_deps_mode.InMemoryMode None) in (* The reverse naming table (name->filename, used for Naming_provider and Decl_provider) is stored (1) through ctx pointing to the backing sqlite file if desired, (2) plus a delta stored in a shmem heap, as per Provider_backend. The forward naming table (filename->FileInfo.t, used for incremental updates and also for fake-arrow autocomplete) is stored (1) through our [Naming_table.t] having a pointer to the sqlitefile if desired, (2) plus a delta stored in [Naming_table.t] ocaml data structures. This hh_single_complete tool is run in two modes: either with a sqlite file in which case sqlite should contain builtins since [to_decl] doesn't, or without a sqlite file in which case the delta ends up containing all provided files and all builtins. *) (* NAMING PHASE 1: point to the sqlite backing if desired, for both reverse and forward, but leave both reverse and forward deltas empty for now. *) let naming_table = match naming_table_path with | Some path -> Naming_table.load_from_sqlite ctx path | None -> Naming_table.create Relative_path.Map.empty in (* NAMING PHASE 2: for the reverse naming table delta, remove any old names from the files we're about to redeclare -- otherwise when we declare them it'd count as a duplicate definition! *) if Option.is_some naming_table_path then begin Relative_path.Map.iter hh_files_contents ~f:(fun file _content -> let file_info = Naming_table.get_file_info naming_table file in Option.iter file_info ~f:(fun file_info -> let ids_to_strings ids = List.map ids ~f:(fun (_, name, _) -> name) in Naming_global.remove_decls ~backend:(Provider_context.get_backend ctx) ~funs:(ids_to_strings file_info.FileInfo.funs) ~classes:(ids_to_strings file_info.FileInfo.classes) ~typedefs:(ids_to_strings file_info.FileInfo.typedefs) ~consts:(ids_to_strings file_info.FileInfo.consts) ~modules:(ids_to_strings file_info.FileInfo.modules))) end; (* NAMING PHASE 3: for the reverse naming table delta, add all new items from files we're declaring. Note that [to_decl] either omits or includes builtins, according to whether we're working from a sqlite naming table or from nothing. *) let (_errors, files_info_and_addenda) = parse_name_and_decl ctx to_decl in (* NAMING PHASE 4: for the forward naming table delta, add all new items *) let files_info = Relative_path.Map.map files_info_and_addenda ~f:fst in let naming_table = Naming_table.combine naming_table (Naming_table.create files_info) in (* SYMBOL INDEX PHASE 1: initialize *) let glean_reponame = GleanOptions.reponame tcopt in let namespace_map = ParserOptions.auto_namespace_map tcopt in let sienv = SymbolIndex.initialize ~gleanopt:tcopt ~namespace_map ~provider_name: (if String.is_empty glean_reponame then "LocalIndex" else "CustomIndex") ~quiet:true ~savedstate_file_opt:None ~workers:None in let sienv = { sienv with SearchUtils.sie_quiet_mode = false; SearchUtils.sie_resolve_signatures = true; SearchUtils.sie_resolve_positions = true; SearchUtils.sie_resolve_local_decl = true; } in (* SYMBOL INDEX PHASE 2: update *) let paths_with_addenda = files_info_and_addenda |> Relative_path.Map.elements |> List.map ~f:(fun (path, (_fi, addenda)) -> (path, addenda, SearchUtils.TypeChecker)) in let sienv = SymbolIndexCore.update_from_addenda ~sienv ~paths_with_addenda in handle_mode mode files ctx sienv naming_table let main_hack ({ tcopt; _ } as opts) (root : Path.t) (sharedmem_config : SharedMem.config) : unit = (* TODO: We should have a per file config *) Sys_utils.signal Sys.sigusr1 (Sys.Signal_handle Typing.debug_print_last_pos); EventLogger.init_fake (); let (_handle : SharedMem.handle) = SharedMem.init ~num_workers:0 sharedmem_config in Tempfile.with_tempdir (fun hhi_root -> Hhi.set_hhi_root_for_unit_test hhi_root; Relative_path.set_path_prefix Relative_path.Root root; Relative_path.set_path_prefix Relative_path.Hhi hhi_root; Relative_path.set_path_prefix Relative_path.Tmp (Path.make "tmp"); decl_and_run_mode opts tcopt hhi_root; TypingLogger.flush_buffers ()) (* command line driver *) let () = if !Sys.interactive then () else (* On windows, setting 'binary mode' avoids to output CRLF on stdout. The 'text mode' would not hurt the user in general, but it breaks the testsuite where the output is compared to the expected one (i.e. in given file without CRLF). *) Out_channel.set_binary_mode stdout true; let (options, root, sharedmem_config) = parse_options () in Unix.handle_unix_error main_hack options root sharedmem_config
OCaml
hhvm/hphp/hack/src/hh_single_decl.ml
(* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open Direct_decl_parser let popt ~auto_namespace_map ~enable_xhp_class_modifier ~disable_xhp_element_mangling ~keep_user_attributes ~interpret_soft_types_as_like_types ~everything_sdt = let po = ParserOptions.default in let po = ParserOptions.with_disable_xhp_element_mangling po disable_xhp_element_mangling in let po = ParserOptions.with_keep_user_attributes po keep_user_attributes in let po = ParserOptions.with_auto_namespace_map po auto_namespace_map in let po = ParserOptions.with_enable_xhp_class_modifier po enable_xhp_class_modifier in let po = ParserOptions.with_interpret_soft_types_as_like_types po interpret_soft_types_as_like_types in let po = ParserOptions.with_everything_sdt po everything_sdt in po let init root popt ~rust_provider_backend : Provider_context.t = Relative_path.(set_path_prefix Root root); Relative_path.(set_path_prefix Tmp (Path.make "/tmp")); Relative_path.(set_path_prefix Hhi (Path.make "/tmp/non_existent")); let sharedmem_config = if rust_provider_backend then SharedMem. { default_config with shm_use_sharded_hashtbl = true; shm_cache_size = max SharedMem.default_config.shm_cache_size (2 * 1024 * 1024 * 1024); } else SharedMem.default_config in let (_handle : SharedMem.handle) = SharedMem.init ~num_workers:0 sharedmem_config in let tcopt = { popt with GlobalOptions.tco_higher_kinded_types = true } in if rust_provider_backend then Provider_backend.set_rust_backend popt else Provider_backend.set_shared_memory_backend (); let ctx = Provider_context.empty_for_tool ~popt ~tcopt ~backend:(Provider_backend.get ()) ~deps_mode:(Typing_deps_mode.InMemoryMode None) in (* Push local stacks here so we don't include shared memory in our timing. *) File_provider.local_changes_push_sharedmem_stack (); Decl_provider.local_changes_push_sharedmem_stack (); Shallow_classes_provider.local_changes_push_sharedmem_stack (); ctx let direct_decl_parse ctx fn text = let popt = Provider_context.get_popt ctx in let opts = DeclParserOptions.from_parser_options popt in let parsed_file = parse_decls opts fn text in parsed_file.pf_decls let parse_and_print_decls ctx fn text = let (ctx, _entry) = Provider_context.( add_or_overwrite_entry_contents ~ctx ~path:fn ~contents:text) in let decls = direct_decl_parse ctx fn text in let decls_str = show_decls (List.rev decls) ^ "\n" in Printf.eprintf "%s%!" decls_str; (* This mode doesn't compare anything. Return false so that we don't print "They matched!". *) let matched = false in matched let compare_marshal ctx fn text = let (ctx, _entry) = Provider_context.( add_or_overwrite_entry_contents ~ctx ~path:fn ~contents:text) in let decls = direct_decl_parse ctx fn text in (* Test that Rust produces the same marshaled bytes as OCaml. *) let ocaml_marshaled = Marshal.to_string decls [] in let rust_marshaled = Ocamlrep_marshal_ffi.to_string decls [] in let marshaled_bytes_matched = String.equal ocaml_marshaled rust_marshaled in let () = if not marshaled_bytes_matched then begin Printf.printf "OCaml Marshal output does not match Rust ocamlrep_marshal output:\n%!"; Printf.printf "ocaml:\t%S\n%!" ocaml_marshaled; Printf.printf "rust:\t%S\n%!" rust_marshaled end in (* Test that Rust unmarshaling works as expected. *) let rust_read_back_decls = Ocamlrep_marshal_ffi.from_string rust_marshaled 0 in let rust_read_back_matched = String.equal (show_decls decls) (show_decls rust_read_back_decls) in let () = if not rust_read_back_matched then begin Printf.printf "Rust ocamlrep_marshal from_string decl read-back failed:\n%!"; Printf.printf "ocaml:\n%s%!" (show_decls decls); Printf.printf "rust:\n%s%!" (show_decls rust_read_back_decls) end in marshaled_bytes_matched && rust_read_back_matched let show_name_results ~ctx ~ctx_with_entry (pos, name) ~name_type ~f_name_exists ~f_name_pos ~f_name_canon ~f_decl_exists = let show_pos (pos : FileInfo.pos) : string = match pos with | FileInfo.Full pos -> Printf.sprintf "(FileInfo.Full: %s)" (Pos.to_relative_string pos |> Pos.string) | FileInfo.File (name_type, fn) -> Printf.sprintf "(FileInfo.File: %s %s)" (FileInfo.show_name_type name_type) (Relative_path.show fn) in let name_type_lower = FileInfo.show_name_type name_type |> String.lowercase in let show_winner (winner : Decl_provider.winner) : string = match winner with | Decl_provider.Winner -> "winner" | Decl_provider.Loser_to pos -> Printf.sprintf "Loser_to %s" (Pos.to_relative_string pos |> Pos.string) | Decl_provider.Not_found -> "not_found" in let print_item fmt arg ctx_arg = let (value, value_with_entry) = (ctx_arg ctx, ctx_arg ctx_with_entry) in Printf.eprintf fmt arg value; if not (String.equal value value_with_entry) then begin Printf.eprintf " [hh_server / typing_check_service]\n%!"; Printf.eprintf fmt arg value_with_entry; Printf.eprintf " [Provider_context.entry]" end; Printf.eprintf "\n%!" in Printf.eprintf "name=%s, name_type=%s, pos=%s\n%!" name (FileInfo.show_name_type name_type) (Pos.to_relative_string pos |> Pos.string); print_item " Naming_provider.%s_exists(name): %s" name_type_lower (fun ctx -> f_name_exists ctx name |> string_of_bool); print_item " Naming_provider.get_%s_pos(name): %s" name_type_lower (fun ctx -> f_name_pos ctx name |> Option.value_map ~default:"[none]" ~f:show_pos); print_item " Naming_provider.get_%s_canon_name(name): %s" name_type_lower (fun ctx -> f_name_canon ctx name |> Option.value ~default:"[none]"); print_item " Decl_provider.get_%s(name) |> Option.is_some: %s" name_type_lower (fun ctx -> f_decl_exists ctx name |> Option.is_some |> string_of_bool); print_item " Decl_provider.get_pos_from_decl_of_winner%s(name_type,name): %s" "" (fun ctx -> Decl_provider.get_pos_from_decl_of_winner_FOR_TESTS_ONLY ctx name_type name |> Option.value_map ~default:"[none]" ~f:(fun pos -> Pos.to_relative_string pos |> Pos.string)); print_item " Decl_provider.is_this_def_the_winner%s(name_type,name,pos): %s" "" (fun ctx -> Decl_provider.is_this_def_the_winner ctx name_type (pos, name) |> show_winner); Printf.eprintf "\n%!"; () (** Constructs a list of [name_type * id] pairs for each top-level declaration we find in the AST. *) let ast_to_toplevels (ast : Nast.program) : (FileInfo.name_type * Ast_defs.id) list = List.filter_map ast ~f:(fun def -> match def with | Aast.Fun { Aast_defs.fd_name; _ } -> Some (FileInfo.Fun, fd_name) | Aast.Constant { Aast_defs.cst_name; _ } -> Some (FileInfo.Const, cst_name) | Aast.Typedef { Aast_defs.t_name; _ } -> Some (FileInfo.Typedef, t_name) | Aast.Class { Aast_defs.c_name; _ } -> Some (FileInfo.Class, c_name) | Aast.Module { Aast_defs.md_name; _ } -> Some (FileInfo.Module, md_name) | Aast.( ( Stmt _ | SetModule _ | Namespace _ | NamespaceUse _ | SetNamespaceEnv _ | FileAttributes _ )) -> None) (** Constructs a list of [name_type * id] pairs for each top-level declaration we find from the direct-decl-parser. *) let decls_to_toplevels (decls : Direct_decl_parser.parsed_file_with_hashes) : (FileInfo.name_type * Ast_defs.id) list = List.map decls.pfh_decls ~f:(fun (name, decl, _hash) -> let (name_type, pos) = match decl with | Shallow_decl_defs.Class { Shallow_decl_defs.sc_name = (pos, _id); _ } -> (FileInfo.Class, pos) | Shallow_decl_defs.Fun { Typing_defs.fe_pos; _ } -> (FileInfo.Fun, fe_pos) | Shallow_decl_defs.Typedef { Typing_defs.td_pos; _ } -> (FileInfo.Typedef, td_pos) | Shallow_decl_defs.Const { Typing_defs.cd_pos; _ } -> (FileInfo.Const, cd_pos) | Shallow_decl_defs.Module { Typing_defs.mdt_pos; _ } -> (FileInfo.Module, mdt_pos) in let pos = Pos_or_decl.unsafe_to_raw_pos pos in (name_type, (pos, name))) let compare_toplevels (a_name_type, (a_pos, a_name)) (b_name_type, (b_pos, b_name)) = let c = String.compare (String.lowercase a_name) (String.lowercase b_name) in if c <> 0 then c else let c = String.compare a_name b_name in if c <> 0 then c else let c = FileInfo.compare_name_type a_name_type b_name_type in if c <> 0 then c else Pos.compare a_pos b_pos (** This does "naming_global" on all the files, i.e. parses them, figures out winners, updates the reverse naming table. Then for every toplevel symbol name it encountered, it prints out results from a few Naming_provider and Decl_provider APIs on that symbol name. This function does NOT use Provider_context "entries". To explain: you can set up a Provider_context.t with zero or more entries. Each one provides file content, caches for AST and TAST, and it acts as an "override" reverse-naming-table for all names defined in those entries. If a name isn't found in any entry, then we fall back to the global reverse naming table which was set up by Naming_global.ml. Entries are not used in hh_server's Typing_check_service, and they're not used in this function either. [decl_make_env] causes us to call [Decl.make_env]. Its job is to populate the decl-heap with the content of a file. It's called in some codepaths e.g. hh_single_type_check and when we make edits to a file. It's a terrible function which doesn't respect winners/losers. We call it here to make our behavior similar to that of hh_single_type_check. *) let name_and_then_print_name_results ctx files ~decl_make_env = let popt = Provider_context.get_popt ctx in let names = List.map files ~f:(fun (fn, contents) -> File_provider.provide_file_for_tests fn contents; let (_parse_errors, parsed_file) = Errors.do_with_context fn (fun () -> Full_fidelity_ast.defensive_program popt fn contents) in let ast = let { Parser_return.ast; _ } = parsed_file in if ParserOptions.deregister_php_stdlib popt then Nast.deregister_ignored_attributes ast else ast in Ast_provider.provide_ast_hint fn ast Ast_provider.Full; let decls = Direct_decl_utils.direct_decl_parse ctx fn |> Option.value_exn in let fi = Direct_decl_utils.decls_to_fileinfo fn decls in let _conflict_filenames = Naming_global.ndecl_file_and_get_conflict_files ctx fn fi in if decl_make_env then Decl.make_env ~sh:SharedMem.Uses ctx fn; (* Here we assemble top-level definitions as discovered by AST, and also as discovered by direct-decl-parser. We include them both so as to exercise any differences between the two! *) ast_to_toplevels ast @ decls_to_toplevels decls) |> List.concat |> Caml.List.sort_uniq compare_toplevels in List.iter names ~f:(fun (name_type, id) -> let path = Pos.filename (fst id) in let contents = List.Assoc.find_exn files path ~equal:Relative_path.equal in let (ctx_with_entry, _entry) = Provider_context.add_or_overwrite_entry_contents ~ctx ~path ~contents in match name_type with | FileInfo.Fun -> show_name_results ~ctx ~ctx_with_entry id ~name_type ~f_name_exists:Naming_provider.fun_exists ~f_name_pos:Naming_provider.get_fun_pos ~f_name_canon:Naming_provider.get_fun_canon_name ~f_decl_exists:Decl_provider.get_fun | FileInfo.Class -> show_name_results ~ctx ~ctx_with_entry id ~name_type ~f_name_exists:(fun ctx name -> Naming_provider.get_class_path ctx name |> Option.is_some) ~f_name_pos:Naming_provider.get_type_pos ~f_name_canon:Naming_provider.get_type_canon_name ~f_decl_exists:Decl_provider.get_class | FileInfo.Typedef -> show_name_results ~ctx ~ctx_with_entry id ~name_type ~f_name_exists:(fun ctx name -> Naming_provider.get_typedef_path ctx name |> Option.is_some) ~f_name_pos:Naming_provider.get_type_pos ~f_name_canon:Naming_provider.get_type_canon_name ~f_decl_exists:Decl_provider.get_typedef | FileInfo.Const -> show_name_results ~ctx ~ctx_with_entry id ~name_type ~f_name_exists:Naming_provider.const_exists ~f_name_pos:Naming_provider.get_const_pos ~f_name_canon:(fun _ _ -> Some "[undefined]") ~f_decl_exists:Decl_provider.get_gconst | FileInfo.Module -> show_name_results ~ctx ~ctx_with_entry id ~name_type ~f_name_exists:Naming_provider.module_exists ~f_name_pos:Naming_provider.get_module_pos ~f_name_canon:(fun _ _ -> Some "[undefined]") ~f_decl_exists:Decl_provider.get_module); () type modes = | DirectDeclParse (** Runs the direct decl parser on the given file *) | VerifyOcamlrepMarshal (** Marshals the output of the direct decl parser using Marshal and ocamlrep_marshal and compares their output *) | Winners (** reports what Naming_provider and Decl_provider return for each name *) let iterate_files files ~f : bool option = let num_files = List.length files in let (all_matched, _) = List.fold files ~init:(true, true) ~f:(fun (matched, is_first) (filename, contents) -> (* All output is printed to stderr because that's the output channel Ppxlib_print_diff prints to. *) if not is_first then Printf.eprintf "\n%!"; if num_files > 1 then Printf.eprintf "File %s\n%!" (Relative_path.storage_to_string filename); let matched = f filename contents && matched in (matched, false)) in Some all_matched let () = let usage = Printf.sprintf "Usage: %s [OPTIONS] mode filename\n" Sys.argv.(0) in let usage_and_exit () = prerr_endline usage; exit 1 in let mode = ref None in let set_mode m () = match !mode with | None -> mode := Some m | Some _ -> usage_and_exit () in let file = ref None in let set_file f = match !file with | None -> file := Some f | Some _ -> usage_and_exit () in let skip_if_errors = ref false in let expect_extension = ref ".exp" in let set_expect_extension s = expect_extension := s in let auto_namespace_map = ref [] in let enable_xhp_class_modifier = ref false in let disable_xhp_element_mangling = ref false in let keep_user_attributes = ref false in let disallow_static_memoized = ref false in let interpret_soft_types_as_like_types = ref false in let everything_sdt = ref false in let rust_provider_backend = ref false in let ignored_flag flag = (flag, Arg.Unit (fun _ -> ()), "(ignored)") in let ignored_arg flag = (flag, Arg.String (fun _ -> ()), "(ignored)") in Arg.parse [ ( "--decl-parse", Arg.Unit (set_mode DirectDeclParse), "(mode) Runs the direct decl parser on the given file" ); ( "--verify-ocamlrep-marshal", Arg.Unit (set_mode VerifyOcamlrepMarshal), "(mode) Marshals the output of the direct decl parser using Marshal and ocamlrep_marshal and compares their output" ); ( "--winners", Arg.Unit (set_mode Winners), "(mode) reports what Decl_provider returns for each name" ); ( "--skip-if-errors", Arg.Set skip_if_errors, "Skip comparison if the corresponding .exp file has errors" ); ( "--expect-extension", Arg.String set_expect_extension, "The extension with which the output of the legacy pipeline should be written" ); ( "--auto-namespace-map", Arg.String (fun m -> auto_namespace_map := ServerConfig.convert_auto_namespace_to_map m), "Namespace aliases" ); ( "--enable-xhp-class-modifier", Arg.Set enable_xhp_class_modifier, "Enable the XHP class modifier, xhp class name {} will define an xhp class." ); ( "--disable-xhp-element-mangling", Arg.Set disable_xhp_element_mangling, "." ); ("--keep-user-attributes", Arg.Set keep_user_attributes, "."); ( "--disallow-static-memoized", Arg.Set disallow_static_memoized, " Disallow static memoized methods on non-final methods" ); ( "--interpret-soft-types-as-like-types", Arg.Set interpret_soft_types_as_like_types, "Interpret <<__Soft>> type hints as like types" ); ( "--everything-sdt", Arg.Set everything_sdt, " Treat all classes, functions, and traits as though they are annotated with <<__SupportDynamicType>>, unless they are annotated with <<__NoAutoDynamic>>" ); ( "--rust-provider-backend", Arg.Set rust_provider_backend, " Use the Rust implementation of Provider_backend (including decl-folding)" ); (* The following options do not affect the direct decl parser and can be ignored (they are used by hh_single_type_check, and we run hh_single_decl over all of the typecheck test cases). *) ignored_flag "--enable-global-access-check"; ignored_flag "--abstract-static-props"; ignored_arg "--allowed-decl-fixme-codes"; ignored_arg "--allowed-fixme-codes-strict"; ignored_flag "--allow-toplevel-requires"; ignored_flag "--check-xhp-attribute"; ignored_flag "--complex-coercion"; ignored_flag "--const-attribute"; ignored_flag "--const-static-props"; ignored_arg "--disable-hh-ignore-error"; ignored_flag "--disable-modes"; ignored_flag "--disable-partially-abstract-typeconsts"; ignored_flag "--disable-unset-class-const"; ignored_flag "--disable-xhp-children-declarations"; ignored_flag "--disallow-discarded-nullable-awaitables"; ignored_flag "--disallow-fun-and-cls-meth-pseudo-funcs"; ignored_flag "--disallow-func-ptrs-in-constants"; ignored_flag "--disallow-invalid-arraykey-constraint"; ignored_flag "--disallow-php-lambdas"; ignored_flag "--disallow-silence"; ignored_flag "--enable-class-level-where-clauses"; ignored_flag "--enable-higher-kinded-types"; ignored_flag "--forbid_nullable_cast"; ( "--hh-log-level", Arg.Tuple [Arg.String (fun _ -> ()); Arg.String (fun _ -> ())], "(ignored)" ); ignored_flag "--is-systemlib"; ignored_flag "--like-type-hints"; ignored_flag "--method-call-inference"; ignored_flag "--no-builtins"; ignored_flag "--no-strict-contexts"; ignored_flag "--report-pos-from-reason"; ignored_arg "--timeout"; ignored_flag "--union-intersection-type-hints"; ignored_flag "--enable-strict-string-concat-interp"; ignored_arg "--extra-builtin"; ignored_flag "--disallow-inst-meth"; ignored_flag "--ignore-unsafe-cast"; ignored_flag "--inc-dec-new-code"; ignored_flag "--math-new-code"; ignored_flag "--disallow-partially-abstract-typeconst-definitions"; ignored_flag "--typeconst-concrete-concrete-error"; ignored_arg "--enable-strict-const-semantics"; ignored_arg "--strict-wellformedness"; ignored_arg "--meth-caller-only-public-visibility"; ignored_flag "--require-extends-implements-ancestors"; ignored_flag "--strict-value-equality"; ignored_flag "--enable-sealed-subclasses"; ignored_flag "--enable-sound-dynamic-type"; ignored_arg "--explicit-consistent-constructors"; ignored_arg "--require-types-class-consts"; ignored_flag "--skip-tast-checks"; ignored_flag "--expression-tree-virtualize-functions"; ] set_file usage; let mode = match !mode with | None -> usage_and_exit () | Some mode -> mode in let file = match !file with | None -> usage_and_exit () | Some file -> file in let () = if !skip_if_errors && not @@ String.is_substring ~substring:"No errors" (RealDisk.cat (file ^ ".exp")) then begin print_endline "Skipping because input file has errors"; exit 0 end in EventLogger.init_fake (); let file = Path.make file in let auto_namespace_map = !auto_namespace_map in let enable_xhp_class_modifier = !enable_xhp_class_modifier in let disable_xhp_element_mangling = !disable_xhp_element_mangling in let keep_user_attributes = !keep_user_attributes in let interpret_soft_types_as_like_types = !interpret_soft_types_as_like_types in let everything_sdt = !everything_sdt in let popt = popt ~auto_namespace_map ~enable_xhp_class_modifier ~disable_xhp_element_mangling ~keep_user_attributes ~interpret_soft_types_as_like_types ~everything_sdt in let tco_experimental_features = TypecheckerOptions.experimental_from_flags ~disallow_static_memoized:!disallow_static_memoized in let popt = { popt with GlobalOptions.tco_experimental_features } in let ctx = init (Path.dirname file) popt ~rust_provider_backend:!rust_provider_backend in let file = Relative_path.(create Root (Path.to_string file)) in let files = Multifile.file_to_file_list file in (* Multifile produces Dummy paths, but we want root-relative paths *) let files = List.map files ~f:(fun (fn, content) -> (Relative_path.(create Root (Relative_path.to_absolute fn)), content)) in let all_matched = match mode with | DirectDeclParse -> iterate_files files ~f:(fun filename contents -> Provider_utils.respect_but_quarantine_unsaved_changes ~ctx ~f:(fun () -> parse_and_print_decls ctx filename contents)) | VerifyOcamlrepMarshal -> iterate_files files ~f:(fun filename contents -> Provider_utils.respect_but_quarantine_unsaved_changes ~ctx ~f:(fun () -> compare_marshal ctx filename contents)) | Winners -> name_and_then_print_name_results ctx files ~decl_make_env:true; None in match all_matched with | Some true -> Printf.eprintf "\nThey matched!\n%!" | Some false -> exit 1 | None -> ()
OCaml
hhvm/hphp/hack/src/hh_single_fanout.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 options = { debug: bool } let deps_mode = Typing_deps_mode.InMemoryMode None let tcopt = { GlobalOptions.default with GlobalOptions.tco_enable_modules = true; tco_allow_all_files_for_module_declarations = true; } let popt = { GlobalOptions.default with GlobalOptions.po_disable_xhp_element_mangling = false; } let parse_defs (ctx : Provider_context.t) (files : Relative_path.t list) : FileInfo.t Relative_path.Map.t = let workers = None in let done_ = ref false in Direct_decl_service.go ctx ~trace:false ~cache_decls: (* Not caching here, otherwise oldification done in redo_type_decl will * oldify the new version (and override the real old versions*) false workers ~ide_files:Relative_path.Set.empty ~get_next:(fun () -> if !done_ then Bucket.Done else ( done_ := true; Bucket.Job files )) let redecl_make_new_naming_table (ctx : Provider_context.t) options (old_naming_table : Naming_table.t) (files_with_changes : Relative_path.t list) : Naming_table.t = let defs_per_file_parsed = parse_defs ctx files_with_changes in let new_naming_table = Naming_table.update_many old_naming_table defs_per_file_parsed in if options.debug then Printf.printf "%s\n" (Naming_table.show new_naming_table); new_naming_table let get_old_and_new_defs options (files_with_changes : Relative_path.t list) (old_naming_table : Naming_table.t) (new_naming_table : Naming_table.t) : Naming_table.defs_per_file = let add_file_names naming_table filenames acc = List.fold filenames ~init:acc ~f:(fun acc file -> match Naming_table.get_file_info naming_table file with | None -> acc | Some file_info -> let current_file_names = match Relative_path.Map.find_opt acc file with | None -> FileInfo.empty_names | Some current_file_names -> current_file_names in let file_names = FileInfo.simplify file_info in let new_file_names = FileInfo.merge_names current_file_names file_names in Relative_path.Map.add acc ~key:file ~data:new_file_names) in let defs = Relative_path.Map.empty |> add_file_names old_naming_table files_with_changes |> add_file_names new_naming_table files_with_changes in if options.debug then Printf.printf "The following defs will be diffed for each file:\n%s\n" (Naming_table.show_defs_per_file defs); defs let get_symbols_for_deps (deps : Typing_deps.DepSet.t) (dep_to_symbol_map : _ Typing_deps.Dep.variant Typing_deps.DepMap.t) : SSet.t = Typing_deps.DepSet.fold deps ~init:SSet.empty ~f:(fun dep acc -> let symbol = match Typing_deps.DepMap.find_opt dep dep_to_symbol_map with | None -> Typing_deps.Dep.to_hex_string dep | Some variant -> Typing_deps.Dep.variant_to_string variant in SSet.add symbol acc) let compute_fanout ctx options (old_and_new_defs : Naming_table.defs_per_file) : Typing_deps.DepSet.t = let { Decl_redecl_service.fanout = { Fanout.to_recheck; changed }; _ } = Decl_redecl_service.redo_type_decl ctx ~during_init:false None ~bucket_size:500 (fun _ -> SSet.empty) ~previously_oldified_defs:FileInfo.empty_names ~defs:old_and_new_defs in if options.debug then ( Printf.printf "Hashes of changed:%s\n" (Typing_deps.DepSet.show changed); Printf.printf "Hashes to recheck:%s\n" (Typing_deps.DepSet.show to_recheck) ); to_recheck let update_naming_table_and_compute_fanout (ctx : Provider_context.t) (options : options) files_with_changes old_naming_table (dep_to_symbol_map : _ Typing_deps.Dep.variant Typing_deps.DepMap.t) : SSet.t = let new_naming_table = redecl_make_new_naming_table ctx options old_naming_table files_with_changes in let old_and_new_defs = get_old_and_new_defs options files_with_changes old_naming_table new_naming_table in let to_recheck = compute_fanout ctx options old_and_new_defs in let to_recheck = get_symbols_for_deps to_recheck dep_to_symbol_map in to_recheck module FileSystem = struct let read_test_file_and_provide_before (file_path : string) : Relative_path.t list = File_provider.local_changes_push_sharedmem_stack (); let files = Multifile.States.base_files file_path in Relative_path.Map.iter files ~f:File_provider.provide_file_for_tests; Relative_path.Map.keys files let read_test_file_and_provide_after (file_path : string) : Relative_path.t list = let files = Multifile.States.changed_files file_path in Relative_path.Map.fold files ~init:[] ~f:(fun file_path content changed_files -> let old_content = File_provider.get_contents file_path in let changed = match old_content with | None -> true | Some old_content -> not (String.equal old_content content) in if changed then ( File_provider.provide_file_for_tests file_path content; file_path :: changed_files ) else changed_files) end let print_fanout fanout = SSet.iter (Printf.printf "%s\n") fanout let init_paths (hhi_root : Path.t) : unit = (* dummy path, not actually used *) Relative_path.set_path_prefix Relative_path.Root (Path.make "/"); Hhi.set_hhi_root_for_unit_test hhi_root; Relative_path.set_path_prefix Relative_path.Hhi hhi_root; (* dummy path, not actually used *) Relative_path.set_path_prefix Relative_path.Tmp (Path.make "tmp"); () module DepToSymbolsMap = struct let map : Typing_deps.Dep.dependency Typing_deps.Dep.variant Typing_deps.DepMap.t ref = ref Typing_deps.DepMap.empty let add (dep : _ Typing_deps.Dep.variant) : unit = let hash = Typing_deps.Dep.make dep in map := Typing_deps.DepMap.add hash (Typing_deps.Dep.dependency_of_variant dep) !map let callback (dependent : Typing_deps.Dep.dependent Typing_deps.Dep.variant) (dependency : Typing_deps.Dep.dependency Typing_deps.Dep.variant) : unit = add dependent; add dependency let get () = !map end let make_nast ctx (filename : Relative_path.t) : Nast.program = Ast_provider.get_ast ~full:true ctx filename |> Naming.program ctx let make_dep_to_symbol_map ctx options (files : Relative_path.t list) : _ Typing_deps.Dep.variant Typing_deps.DepMap.t = let dep_to_symbol_map = Typing_deps.DepMap.union (DepToSymbolsMap.get ()) (Dep_hash_to_symbol.from_nasts (List.map files ~f:(make_nast ctx))) in if options.debug then Printf.printf "%s\n" (Typing_deps.DepMap.show Typing_deps.Dep.pp_variant dep_to_symbol_map); dep_to_symbol_map (** Initialize a number of backend structures and global states necessary for the typechecker to function. *) let init (hhi_root : Path.t) : Provider_context.t = EventLogger.init_fake (); let (_ : SharedMem.handle) = SharedMem.init ~num_workers:0 SharedMem.default_config in init_paths hhi_root; let ctx = Provider_context.empty_for_test ~popt ~tcopt ~deps_mode in Typing_deps.add_dependency_callback ~name:"dep_to_symbol" DepToSymbolsMap.callback; ctx let commit_dep_edges () : unit = Typing_deps.flush_ideps_batch deps_mode |> Typing_deps.register_discovered_dep_edges let make_reverse_naming_table ctx (defs_per_file : FileInfo.t Relative_path.Map.t) : unit = Relative_path.Map.iter defs_per_file ~f:(fun file file_info -> Naming_global.ndecl_file_skip_if_already_bound ctx file file_info) (** Build and return the naming table and build the reverse naming table as a side-effect. *) let make_naming_table ctx options (defs_per_file : FileInfo.t Relative_path.Map.t) : Naming_table.t = let naming_table = Naming_table.create defs_per_file in if options.debug then Printf.printf "%s\n" @@ Naming_table.show naming_table; make_reverse_naming_table ctx defs_per_file; naming_table (** Type check given files. Create the dependency graph as a side effect. *) let type_check_make_depgraph ctx options (files : Relative_path.t list) : unit = List.iter files ~f:(fun file -> let full_ast = Ast_provider.get_ast ctx file ~full:true in let (_ : Errors.t * Tast.by_names) = Typing_check_job.calc_errors_and_tast ctx file ~full_ast in ()); if options.debug then Typing_deps.dump_current_edge_buffer_in_memory_mode (); commit_dep_edges (); () (** Build the naming table and typecheck the base file to create the depgraph. Only the naming table is returned. The reverse naming table and depgraph are produced as side effects. *) let process_pre_changes ctx options (files : Relative_path.t list) : Naming_table.t = (* TODO builtins and hhi stuff *) let defs_per_file = parse_defs ctx files in let naming_table = make_naming_table ctx options defs_per_file in type_check_make_depgraph ctx options files; naming_table (** Process changed files by making those files available in the typechecker as a side effect and returning the list of changed files. *) let process_changed_files options (test_file : string) : Relative_path.t list = let files_with_changes = FileSystem.read_test_file_and_provide_after test_file in Ast_provider.clear_local_cache (); Ast_provider.clear_parser_cache (); if options.debug then Printf.printf "Changed files: %s\n" (String.concat ~sep:", " (List.map files_with_changes ~f:Relative_path.show)); files_with_changes (** This takes the path of a file specifying the base and changed versions of files as a multifile, and prints the computed fanout for that change to standard output. To do so, it typechecks the base version to create a depgraph and naming table, then uses those to compute a fanout. *) let go (test_file : string) options = Tempfile.with_tempdir @@ fun hhi_root -> let ctx = init hhi_root in let files = FileSystem.read_test_file_and_provide_before test_file in let naming_table = process_pre_changes ctx options files in let files_with_changes = process_changed_files options test_file in let dep_to_symbol_map = make_dep_to_symbol_map ctx options files_with_changes in let fanout = update_naming_table_and_compute_fanout ctx options files_with_changes naming_table dep_to_symbol_map in print_fanout fanout let die str = let oc = stderr in Out_channel.output_string oc str; Out_channel.close oc; exit 2 let parse_args () : string * options = let usage = Printf.sprintf "Usage: %s filename\n" Sys.argv.(0) in let fn_ref = ref [] in let debug = ref false in let options = [("--debug", Arg.Set debug, "print debug information")] in Arg.parse options (fun fn -> fn_ref := fn :: !fn_ref) usage; let options = { debug = !debug } in let files = !fn_ref in match files with | [file] -> (file, options) | _ -> die usage let () = let (test_file, options) = parse_args () in go test_file options
OCaml
hhvm/hphp/hack/src/hh_single_type_check.ml
(* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the "hack" directory of this source tree. * *) open Hh_prelude open Sys_utils module Cls = Decl_provider.Class (*****************************************************************************) (* Profiling utilities *) (*****************************************************************************) let mean samples = List.fold ~init:0.0 ~f:( +. ) samples /. Float.of_int (List.length samples) let standard_deviation mean samples = let sosq = List.fold ~init:0.0 ~f:(fun acc sample -> let diff = sample -. mean in (diff *. diff) +. acc) samples in let sosqm = sosq /. Float.of_int (List.length samples) in Float.sqrt sosqm (*****************************************************************************) (* Types, constants *) (*****************************************************************************) type mode = | Ifc of string * string | Cst_search | Dump_symbol_info | Glean_index of string | Glean_sym_hash | Dump_inheritance | Errors | Lint | Lint_json | Dump_deps | Dump_dep_hashes | Get_some_file_deps of int | Identify_symbol of int * int | Ide_code_actions of { title_prefix: string; use_snippet_edits: bool; } | Find_local of int * int | Get_member of string | Outline | Dump_nast | Dump_stripped_tast | Dump_tast | Find_refs of int * int | Highlight_refs of int * int | Decl_compare | Shallow_class_diff | Go_to_impl of int * int | Hover of (int * int) option | Apply_quickfixes | Shape_analysis of string | Refactor_sound_dynamic of string * string * string | RemoveDeadUnsafeCasts | CountImpreciseTypes | SDT_analysis of string | Get_type_hierarchy | Map_reduce_mode type options = { files: string list; extra_builtins: string list; mode: mode; error_format: Errors.format; no_builtins: bool; max_errors: int option; tcopt: GlobalOptions.t; batch_mode: bool; out_extension: string; verbosity: int; should_print_position: bool; custom_hhi_path: string option; profile_type_check_multi: int option; memtrace: string option; rust_provider_backend: bool; naming_table_path: string option; packages_config_path: string option; } (** If the user passed --root, then all pathnames have to be canonicalized. The fact of whether they passed --root is kind of stored inside Relative_path global variables: the Relative_path.(path_of_prefix Root) is either "/" if they failed to pass something, or the thing that they passed. *) let use_canonical_filenames () = not (String.equal "/" (Relative_path.path_of_prefix Relative_path.Root)) (* Canonical builtins from our hhi library *) let hhi_builtins = Hhi.get_raw_hhi_contents () (* All of the stuff that hh_single_type_check relies on is sadly not contained * in the hhi library, so we include a very small number of magic builtins *) let magic_builtins = [| ( "hh_single_type_check_magic.hhi", "<?hh\n" ^ "namespace {\n" ^ "<<__NoAutoDynamic, __SupportDynamicType>> function hh_show<T>(<<__AcceptDisposable>> readonly T $val)[]:T {}\n" ^ "<<__NoAutoDynamic, __SupportDynamicType>> function hh_expect<T>(<<__AcceptDisposable>> readonly T $val)[]:T {}\n" ^ "<<__NoAutoDynamic, __SupportDynamicType>> function hh_expect_equivalent<T>(<<__AcceptDisposable>> readonly T $val)[]:T {}\n" ^ "<<__NoAutoDynamic>> function hh_show_env()[]:void {}\n" ^ "<<__NoAutoDynamic>> function hh_log_level(string $key, int $level)[]:void {}\n" ^ "<<__NoAutoDynamic>> function hh_force_solve()[]:void {}" ^ "<<__NoAutoDynamic>> function hh_time(string $command, string $tag = '_'):void {}\n" ^ "}\n" ); |] (*****************************************************************************) (* Helpers *) (*****************************************************************************) let die str = let oc = stderr in Out_channel.output_string oc str; Out_channel.close oc; exit 2 let print_error format ?(oc = stderr) l = let formatter = match format with | Errors.Context -> (fun e -> Contextual_error_formatter.to_string e) | Errors.Raw -> (fun e -> Raw_error_formatter.to_string e) | Errors.Plain -> (fun e -> Errors.to_string e) | Errors.Highlighted -> Highlighted_error_formatter.to_string in let absolute_errors = User_error.to_absolute l in Out_channel.output_string oc (formatter absolute_errors) let write_error_list format errors oc max_errors = let (shown_errors, dropped_errors) = match max_errors with | Some max_errors -> List.split_n errors max_errors | None -> (errors, []) in if not (List.is_empty errors) then ( List.iter ~f:(print_error format ~oc) shown_errors; match Errors.format_summary format ~displayed_count:(List.length errors) ~dropped_count:(Some (List.length dropped_errors)) ~max_errors with | Some summary -> Out_channel.output_string oc summary | None -> () ) else Out_channel.output_string oc "No errors\n"; Out_channel.close oc let print_error_list format errors max_errors = let (shown_errors, dropped_errors) = match max_errors with | Some max_errors -> List.split_n errors max_errors | None -> (errors, []) in if not (List.is_empty errors) then ( List.iter ~f:(print_error format) shown_errors; match Errors.format_summary format ~displayed_count:(List.length errors) ~dropped_count:(Some (List.length dropped_errors)) ~max_errors with | Some summary -> Out_channel.output_string stderr summary | None -> () ) else Printf.printf "No errors\n" let print_errors format (errors : Errors.t) max_errors : unit = print_error_list format (Errors.get_sorted_error_list errors) max_errors let print_errors_if_present (errors : Errors.error list) = if not (List.is_empty errors) then ( let errors_output = Errors.convert_errors_to_string errors in Printf.printf "Errors:\n"; List.iter errors_output ~f:(fun err_output -> Printf.printf " %s\n" err_output) ) let comma_string_to_iset (s : string) : ISet.t = Str.split (Str.regexp ", *") s |> List.map ~f:int_of_string |> ISet.of_list let load_and_parse_custom_error_config path = match Custom_error_config.initialize (`Absolute path) with | Ok cfg -> if not @@ List.is_empty cfg.Custom_error_config.invalid then eprintf "Encountered invalid rules with loading custom error config: \n %s\n" @@ String.concat ~sep:"\n" @@ List.map ~f:(fun Custom_error.{ name; _ } -> name) @@ cfg.Custom_error_config.invalid; Some cfg | Error msg -> eprintf "Encountered and error when loading custom error config: \n %s\n" msg; None let parse_options () = let fn_ref = ref [] in let extra_builtins = ref [] in let usage = Printf.sprintf "Usage: %s filename\n" Sys.argv.(0) in let mode = ref Errors in let no_builtins = ref false in let log_levels = ref SMap.empty in let max_errors = ref None in let batch_mode = ref false in let set_mode x () = match !mode with | Errors -> mode := x | _ -> raise (Arg.Bad "only a single mode should be specified") in let ifc_mode = ref "" in let set_ifc lattice = set_mode (Ifc (!ifc_mode, lattice)) (); batch_mode := true in let config_overrides = ref [] in let error_format = ref Errors.Highlighted in let forbid_nullable_cast = ref false in let deregister_attributes = ref None in let auto_namespace_map = ref None in let log_inference_constraints = ref None in let timeout = ref None in let disallow_byref_dynamic_calls = ref (Some false) in let disallow_byref_calls = ref (Some false) in let set_bool x () = x := Some true in let set_bool_ x () = x := true in let rust_elab = ref false in let rust_provider_backend = ref false in let skip_hierarchy_checks = ref false in let skip_tast_checks = ref false in let skip_check_under_dynamic = ref false in let out_extension = ref ".out" in let like_type_hints = ref false in let union_intersection_type_hints = ref false in let call_coeffects = ref true in let local_coeffects = ref true in let strict_contexts = ref true in let symbolindex_file = ref None in let check_xhp_attribute = ref false in let check_redundant_generics = ref false in let disallow_static_memoized = ref false in let enable_supportdyn_hint = ref false in let enable_class_level_where_clauses = ref false in let disable_legacy_soft_typehints = ref false in let allow_new_attribute_syntax = ref false in let allow_toplevel_requires = ref false in let const_static_props = ref false in let disable_legacy_attribute_syntax = ref false in let const_attribute = ref false in let const_default_func_args = ref false in let const_default_lambda_args = ref false in let disallow_silence = ref false in let abstract_static_props = ref false in let glean_reponame = ref (GleanOptions.reponame GlobalOptions.default) in let disallow_func_ptrs_in_constants = ref false in let error_php_lambdas = ref false in let disallow_discarded_nullable_awaitables = ref false in let disable_xhp_element_mangling = ref false in let keep_user_attributes = ref false in let disable_xhp_children_declarations = ref false in let enable_xhp_class_modifier = ref false in let verbosity = ref 0 in let disable_hh_ignore_error = ref 0 in let is_systemlib = ref false in let enable_higher_kinded_types = ref false in let allowed_fixme_codes_strict = ref None in let allowed_decl_fixme_codes = ref None in let method_call_inference = ref false in let report_pos_from_reason = ref false in let enable_sound_dynamic = ref true in let always_pessimise_return = ref false in let consider_type_const_enforceable = ref false in let interpret_soft_types_as_like_types = ref false in let enable_strict_string_concat_interp = ref false in let ignore_unsafe_cast = ref false in let math_new_code = ref false in let typeconst_concrete_concrete_error = ref false in let enable_strict_const_semantics = ref 0 in let strict_wellformedness = ref 0 in let meth_caller_only_public_visibility = ref true in let require_extends_implements_ancestors = ref false in let strict_value_equality = ref false in let expression_tree_virtualize_functions = ref false in let naming_table = ref None in let root = ref None in let sharedmem_config = ref SharedMem.default_config in let print_position = ref true in let enforce_sealed_subclasses = ref false in let everything_sdt = ref false in let custom_hhi_path = ref None in let explicit_consistent_constructors = ref 0 in let require_types_class_consts = ref 0 in let type_printer_fuel = ref (TypecheckerOptions.type_printer_fuel GlobalOptions.default) in let profile_type_check_multi = ref None in let profile_top_level_definitions = ref (TypecheckerOptions.profile_top_level_definitions GlobalOptions.default) in let memtrace = ref None in let enable_global_access_check = ref false in let packages_config_path = ref None in let custom_error_config_path = ref None in let allow_all_files_for_module_declarations = ref true in let loop_iteration_upper_bound = ref None in let substitution_mutation = ref false in let options = [ ( "--config", Arg.String (fun s -> config_overrides := s :: !config_overrides), "<option=value> Set one hhconfig option; can be used multiple times" ); ( "--no-print-position", Arg.Unit (fun _ -> print_position := false), " Don't print positions while printing TASTs and NASTs" ); ( "--naming-table", Arg.String (fun s -> naming_table := Some s), " Naming table, to look up undefined symbols; needs --root." ^ " (Hint: buck2 run //hphp/hack/src/hh_naming_table_builder)" ); ( "--root", Arg.String (fun s -> root := Some s), " Root for where to look up undefined symbols; needs --naming-table" ); ( "--extra-builtin", Arg.String (fun f -> extra_builtins := f :: !extra_builtins), " HHI file to parse and declare" ); ( "--ifc", Arg.Tuple [Arg.String (fun m -> ifc_mode := m); Arg.String set_ifc], " Run the flow analysis" ); ( "--shape-analysis", Arg.String (fun mode -> batch_mode := true; set_mode (Shape_analysis mode) ()), " Run the shape analysis" ); ( "--refactor-sound-dynamic", (let refactor_analysis_mode = ref "" in let refactor_mode = ref "" in Arg.Tuple [ Arg.String (( := ) refactor_analysis_mode); Arg.String (( := ) refactor_mode); Arg.String (fun x -> batch_mode := true; set_mode (Refactor_sound_dynamic (!refactor_analysis_mode, !refactor_mode, x)) ()); ]), " Run the flow analysis" ); ( "--deregister-attributes", Arg.Unit (set_bool deregister_attributes), " Ignore all functions with attribute '__PHPStdLib'" ); ( "--auto-namespace-map", Arg.String (fun m -> auto_namespace_map := Some (ServerConfig.convert_auto_namespace_to_map m)), " Alias namespaces" ); ( "--no-call-coeffects", Arg.Unit (fun () -> call_coeffects := false), " Turns off call coeffects" ); ( "--no-local-coeffects", Arg.Unit (fun () -> local_coeffects := false), " Turns off local coeffects" ); ( "--no-strict-contexts", Arg.Unit (fun () -> strict_contexts := false), " Do not enforce contexts to be defined within Contexts namespace" ); ( "--cst-search", Arg.Unit (set_mode Cst_search), " Search the concrete syntax tree of the given file using the pattern" ^ " given on stdin." ^ " (The pattern is a JSON object adhering to the search DSL.)" ); ( "--dump-symbol-info", Arg.Unit (set_mode Dump_symbol_info), " Dump all symbol information" ); ( "--glean-index", Arg.String (fun output_dir -> set_mode (Glean_index output_dir) ()), " Run indexer and output json in provided dir" ); ( "--glean-sym-hash", Arg.Unit (set_mode Glean_sym_hash), " Print symbols hashes used by incremental indexer" ); ( "--error-format", Arg.String (fun s -> match s with | "raw" -> error_format := Errors.Raw | "context" -> error_format := Errors.Context | "highlighted" -> error_format := Errors.Highlighted | "plain" -> error_format := Errors.Plain | _ -> print_string "Warning: unrecognized error format.\n"), "<raw|context|highlighted|plain> Error formatting style; (default: highlighted)" ); ("--lint", Arg.Unit (set_mode Lint), " Produce lint errors"); ("--lint-json", Arg.Unit (set_mode Lint_json), " Produce json lint output"); ( "--no-builtins", Arg.Set no_builtins, " Don't use builtins (e.g. ConstSet); implied by --root" ); ( "--out-extension", Arg.String (fun s -> out_extension := s), " output file extension (default .out)" ); ("--dump-deps", Arg.Unit (set_mode Dump_deps), " Print dependencies"); ( "--dump-dep-hashes", Arg.Unit (set_mode Dump_dep_hashes), " Print dependency hashes" ); ( "--dump-inheritance", Arg.Unit (set_mode Dump_inheritance), " Print inheritance" ); ( "--get-some-file-deps", Arg.Int (fun depth -> set_mode (Get_some_file_deps depth) ()), " Print a list of files this file depends on. The provided integer is the depth of the traversal. Requires --root, --naming-table and --depth" ); ( "--ide-code-actions", Arg.String (fun title_prefix -> set_mode (Ide_code_actions { title_prefix; use_snippet_edits = true }) ()), "<title_prefix> Apply a code action with the given title prefix to the given file, where the selection is indicated with markers in comments (see tests)" ); ( "--ide-code-actions-no-experimental-capabilities", Arg.String (fun title_prefix -> set_mode (Ide_code_actions { title_prefix; use_snippet_edits = false }) ()), "<title_prefix> Like --ide-code-actions, but do not use any nonstandard LSP features (experimental capabilities)." ); ( "--identify-symbol", (let line = ref 0 in Arg.Tuple [ Arg.Int (( := ) line); Arg.Int (fun column -> set_mode (Identify_symbol (!line, column)) ()); ]), "<pos> Show info about symbol at given line and column" ); ( "--find-local", (let line = ref 0 in Arg.Tuple [ Arg.Int (( := ) line); Arg.Int (fun column -> set_mode (Find_local (!line, column)) ()); ]), "<pos> Find all usages of local at given line and column" ); ( "--max-errors", Arg.Int (fun num_errors -> max_errors := Some num_errors), " Maximum number of errors to display" ); ("--outline", Arg.Unit (set_mode Outline), " Print file outline"); ("--nast", Arg.Unit (set_mode Dump_nast), " Print out the named AST"); ("--tast", Arg.Unit (set_mode Dump_tast), " Print out the typed AST"); ( "--stripped-tast", Arg.Unit (set_mode Dump_stripped_tast), " Print out the typed AST, stripped of type information." ^ " This can be compared against the named AST to look for holes." ); ( "--find-refs", (let line = ref 0 in Arg.Tuple [ Arg.Int (( := ) line); Arg.Int (fun column -> set_mode (Find_refs (!line, column)) ()); ]), "<pos> Find all usages of a symbol at given line and column" ); ( "--go-to-impl", Arg.Tuple (let line = ref 0 in [ Arg.Int (( := ) line); Arg.Int (fun column -> set_mode (Go_to_impl (!line, column)) ()); ]), "<pos> Find all implementations of a symbol at given line and column" ); ( "--highlight-refs", (let line = ref 0 in Arg.Tuple [ Arg.Int (( := ) line); Arg.Int (fun column -> set_mode (Highlight_refs (!line, column)) ()); ]), "<pos> Highlight all usages of a symbol at given line and column" ); ( "--decl-compare", Arg.Unit (set_mode Decl_compare), " Test comparison functions used in incremental mode on declarations" ^ " in provided file" ); ( "--shallow-class-diff", Arg.Unit (set_mode Shallow_class_diff), " Test shallow class comparison used in incremental mode on shallow class declarations" ); ( "--forbid_nullable_cast", Arg.Set forbid_nullable_cast, " Forbid casting from nullable values." ); ( "--get-member", Arg.String (fun class_and_member_id -> set_mode (Get_member class_and_member_id) ()), " Given ClassName::MemberName, fetch the decl of members with that name and print them." ); ( "--log-inference-constraints", Arg.Unit (set_bool log_inference_constraints), " Log inference constraints to Scuba." ); ( "--timeout", Arg.Int (fun secs -> timeout := Some secs), " Timeout in seconds for checking a function or a class." ); ( "--hh-log-level", (let log_key = ref "" in Arg.Tuple [ Arg.String (( := ) log_key); Arg.Int (fun level -> log_levels := SMap.add !log_key level !log_levels); ]), " Set the log level for a key" ); ( "--batch-files", Arg.Set batch_mode, " Typecheck each file passed in independently" ); ( "--disallow-static-memoized", Arg.Set disallow_static_memoized, " Disallow static memoized methods on non-final methods" ); ( "--check-xhp-attribute", Arg.Set check_xhp_attribute, " Typechecks xhp required attributes" ); ( "--disallow-byref-dynamic-calls", Arg.Unit (set_bool disallow_byref_dynamic_calls), " Disallow passing arguments by reference to dynamically called functions [e.g. $foo(&$bar)]" ); ( "--disallow-byref-calls", Arg.Unit (set_bool disallow_byref_calls), " Disallow passing arguments by reference in any form [e.g. foo(&$bar)]" ); ( "--rust-elab", Arg.Set rust_elab, " Use the Rust implementation of naming elaboration and NAST checks" ); ( "--rust-provider-backend", Arg.Set rust_provider_backend, " Use the Rust implementation of Provider_backend (including decl-folding)" ); ( "--skip-hierarchy-checks", Arg.Set skip_hierarchy_checks, " Do not apply checks on class hierarchy (override, implements, etc)" ); ( "--skip-tast-checks", Arg.Set skip_tast_checks, " Do not apply checks using TAST visitors" ); ( "--skip-check-under-dynamic", Arg.Set skip_check_under_dynamic, " Do not apply second check to functions and methods under dynamic assumptions" ); ( "--union-intersection-type-hints", Arg.Set union_intersection_type_hints, " Allows union and intersection types to be written in type hint positions" ); ( "--like-type-hints", Arg.Set like_type_hints, " Allows like types to be written in type hint positions" ); ( "--naive-implicit-pess", Arg.Unit (fun () -> set_bool_ enable_sound_dynamic (); set_bool_ everything_sdt (); set_bool_ like_type_hints (); set_bool_ always_pessimise_return (); set_bool_ consider_type_const_enforceable (); set_bool_ enable_supportdyn_hint ()), " Enables naive implicit pessimisation" ); ( "--implicit-pess", Arg.Unit (fun () -> set_bool_ enable_sound_dynamic (); set_bool_ everything_sdt (); set_bool_ like_type_hints (); set_bool_ enable_supportdyn_hint ()), " Enables implicit pessimisation" ); ( "--explicit-pess", Arg.String (fun dir -> set_bool_ enable_sound_dynamic (); set_bool_ like_type_hints (); set_bool_ enable_supportdyn_hint (); custom_hhi_path := Some dir), " Enables checking explicitly pessimised files. Requires path to pessimised .hhi files " ); ( "--symbolindex-file", Arg.String (fun str -> symbolindex_file := Some str), " Load the symbol index from this file" ); ( "--enable-supportdyn-hint", Arg.Set enable_supportdyn_hint, " Allow the supportdyn type hint" ); ( "--enable-class-level-where-clauses", Arg.Set enable_class_level_where_clauses, " Enables support for class-level where clauses" ); ( "--disable-legacy-soft-typehints", Arg.Set disable_legacy_soft_typehints, " Disables the legacy @ syntax for soft typehints (use __Soft instead)" ); ( "--allow-new-attribute-syntax", Arg.Set allow_new_attribute_syntax, " Allow the new @ attribute syntax (disables legacy soft typehints)" ); ( "--allow-toplevel-requires", Arg.Set allow_toplevel_requires, " Allow `require()` and similar at the top-level" ); ( "--const-static-props", Arg.Set const_static_props, " Enable static properties to be const" ); ( "--disable-legacy-attribute-syntax", Arg.Set disable_legacy_attribute_syntax, " Disable the legacy <<...>> user attribute syntax" ); ("--const-attribute", Arg.Set const_attribute, " Allow __Const attribute"); ( "--const-default-func-args", Arg.Set const_default_func_args, " Statically check default function arguments are constant initializers" ); ( "--const-default-lambda-args", Arg.Set const_default_lambda_args, " Statically check default lambda args are constant." ^ " Produces a subset of errors of const-default-func-args" ); ( "--disallow-silence", Arg.Set disallow_silence, " Disallow the error suppression operator, @" ); ( "--abstract-static-props", Arg.Set abstract_static_props, " Static properties can be abstract" ); ( "--glean-reponame", Arg.String (fun str -> glean_reponame := str), " glean repo name" ); ( "--disallow-func-ptrs-in-constants", Arg.Set disallow_func_ptrs_in_constants, " Disallow use of HH\\fun and HH\\class_meth in constants and constant initializers" ); ( "--disallow-php-lambdas", Arg.Set error_php_lambdas, " Disallow php style anonymous functions." ); ( "--disallow-discarded-nullable-awaitables", Arg.Set disallow_discarded_nullable_awaitables, " Error on using discarded nullable awaitables" ); ( "--disable-xhp-element-mangling", Arg.Set disable_xhp_element_mangling, " Disable mangling of XHP elements :foo. That is, :foo:bar is now \\foo\\bar, not xhp_foo__bar" ); ( "--keep-user-attributes", Arg.Set keep_user_attributes, " Keep user attributes when parsing decls" ); ( "--disable-xhp-children-declarations", Arg.Set disable_xhp_children_declarations, " Disable XHP children declarations, e.g. children (foo, bar+)" ); ( "--enable-xhp-class-modifier", Arg.Set enable_xhp_class_modifier, " Enable the XHP class modifier, xhp class name {} will define an xhp class." ); ( "--verbose", Arg.Int (fun v -> verbosity := v), " Verbosity as an integer." ); ( "--disable-hh-ignore-error", Arg.Int (( := ) disable_hh_ignore_error), " Forbid HH_IGNORE_ERROR comments as an alternative to HH_FIXME, or treat them as normal comments." ); ( "--is-systemlib", Arg.Set is_systemlib, " Enable systemlib annotations and other internal-only features" ); ( "--enable-higher-kinded-types", Arg.Set enable_higher_kinded_types, " Enable support for higher-kinded types" ); ( "--allowed-fixme-codes-strict", Arg.String (fun s -> allowed_fixme_codes_strict := Some (comma_string_to_iset s)), " List of fixmes that are allowed in strict mode." ); ( "--allowed-decl-fixme-codes", Arg.String (fun s -> allowed_decl_fixme_codes := Some (comma_string_to_iset s)), " List of fixmes that are allowed in declarations." ); ( "--method-call-inference", Arg.Set method_call_inference, " Infer constraints for method calls. NB: incompatible with like types." ); ( "--report-pos-from-reason", Arg.Set report_pos_from_reason, " Flag errors whose position is derived from reason information in types." ); ( "--enable-sound-dynamic-type", Arg.Set enable_sound_dynamic, " Enforce sound dynamic types. Experimental." ); ( "--always-pessimise-return", Arg.Set always_pessimise_return, " Consider all return types unenforceable." ); ( "--consider-type-const-enforceable", Arg.Set consider_type_const_enforceable, " Consider type constants to potentially be enforceable." ); ( "--interpret-soft-types-as-like-types", Arg.Set interpret_soft_types_as_like_types, " Types declared with <<__Soft>> (runtime logs but doesn't throw) become like types." ); ( "--enable-strict-string-concat-interp", Arg.Set enable_strict_string_concat_interp, " Require arguments are arraykey types in string concatenation and interpolation." ); ( "--ignore-unsafe-cast", Arg.Set ignore_unsafe_cast, " Ignore unsafe_cast and retain the original type of the expression" ); ( "--math-new-code", Arg.Set math_new_code, " Use a new error code for math operations: addition, subtraction, division, multiplication, exponentiation" ); ( "--typeconst-concrete-concrete-error", Arg.Set typeconst_concrete_concrete_error, " Raise an error when a concrete type constant is overridden by a concrete type constant in a child class." ); ( "--enable-strict-const-semantics", Arg.Int (fun x -> enable_strict_const_semantics := x), " Raise an error when a concrete constants is overridden or multiply defined" ); ( "--strict-wellformedness", Arg.Int (fun x -> strict_wellformedness := x), " Re-introduce missing well-formedness checks in AST positions" ); ( "--meth-caller-only-public-visibility", Arg.Bool (fun x -> meth_caller_only_public_visibility := x), " Controls whether meth_caller can be used on non-public methods" ); ( "--hover", (let line = ref 0 in Arg.Tuple [ Arg.Int (fun x -> line := x); Arg.Int (fun column -> set_mode (Hover (Some (!line, column))) ()); ]), "<pos> Display hover tooltip" ); ( "--hover-at-caret", Arg.Unit (fun () -> set_mode (Hover None) ()), " Show the hover information indicated by // ^ hover-at-caret" ); ( "--fix", Arg.Unit (fun () -> set_mode Apply_quickfixes ()), " Apply quickfixes for all the errors in the file, and print the resulting code." ); ( "--require-extends-implements-ancestors", Arg.Set require_extends_implements_ancestors, " Consider `require extends` and `require implements` as ancestors when checking a class" ); ( "--strict-value-equality", Arg.Set strict_value_equality, " Emit an error when \"==\" or \"!=\" is used to compare values that are incompatible types." ); ( "--enable-sealed-subclasses", Arg.Set enforce_sealed_subclasses, " Require all __Sealed arguments to be subclasses" ); ( "--everything-sdt", Arg.Set everything_sdt, " Treat all classes, functions, and traits as though they are annotated with <<__SupportDynamicType>>, unless they are annotated with <<__NoAutoDynamic>>" ); ( "--custom-hhi-path", Arg.String (fun s -> custom_hhi_path := Some s), " Use custom hhis" ); ( "--explicit-consistent-constructors", Arg.Int (( := ) explicit_consistent_constructors), " Raise an error for <<__ConsistentConstruct>> without an explicit constructor; 1 for traits, 2 for all " ); ( "--require-types-class-consts", Arg.Int (( := ) require_types_class_consts), " Raise an error for class constants missing types; 1 for abstract constants, 2 for all " ); ( "--profile-type-check-twice", Arg.Unit (fun () -> profile_type_check_multi := Some 1), " Typecheck the file twice" ); ( "--profile-type-check-multi", Arg.Int (fun n -> profile_type_check_multi := Some n), " Typecheck the files n times extra (!)" ); ( "--profile-top-level-definitions", Arg.Set profile_top_level_definitions, " Profile typechecking of top-level definitions" ); ( "--memtrace", Arg.String (fun s -> memtrace := Some s), " Write memtrace to this file (typical extension .ctf)" ); ( "--type-printer-fuel", Arg.Int (( := ) type_printer_fuel), " Sets the amount of fuel that the type printer can use to display an individual type. Default: " ^ string_of_int (TypecheckerOptions.type_printer_fuel GlobalOptions.default) ); ( "--enable-global-access-check", Arg.Set enable_global_access_check, " Run global access checker to check global writes and reads" ); ( "--overwrite-loop-iteration-upper-bound", Arg.Int (fun u -> loop_iteration_upper_bound := Some u), " Sets the maximum number of iterations that will be used to typecheck loops" ); ( "--expression-tree-virtualize-functions", Arg.Set expression_tree_virtualize_functions, " Enables function virtualization in Expression Trees" ); ( "--substitution-mutation", Arg.Set substitution_mutation, " Applies substitution mutation to applicable entities and typechecks them" ); ( "--remove-dead-unsafe-casts", Arg.Unit (fun () -> set_mode RemoveDeadUnsafeCasts ()), " Removes dead unsafe casts from a file" ); ( "--count-imprecise-types", Arg.Unit (fun () -> set_mode CountImpreciseTypes ()), " Counts the number of mixed, dynamic, and nonnull types in a file" ); ( "--sdt-analysis", Arg.String (fun command -> batch_mode := true; set_mode (SDT_analysis command) ()), " Analyses to support Sound Dynamic rollout" ); ( "--packages-config-path", Arg.String (fun s -> packages_config_path := Some s), " Config file for a list of package definitions" ); ( "--custom-error-config-path", Arg.String (fun s -> custom_error_config_path := Some s), " Config file for custom error messages" ); ( "--get-type-hierarchy-at-caret", Arg.Unit (set_mode Get_type_hierarchy), " Produce type hierarchy at caret location" ); ( "--map-reduce", Arg.Unit (set_mode Map_reduce_mode), " Run the map reducers and print the result" ); ] in (* Sanity check that all option descriptions are well-formed. *) List.iter options ~f:(fun (_, _, description) -> if String.is_prefix description ~prefix:" " || String.is_prefix description ~prefix:"<" then () else failwith (Printf.sprintf "Descriptions should start with <foo> or a leading space, got: %S" description)); let options = Arg.align ~limit:25 options in Arg.parse options (fun fn -> fn_ref := fn :: !fn_ref) usage; let fns = match (!fn_ref, !mode) with | ([], Get_member _) -> [] | ([], _) -> die usage | (x, _) -> x in let is_ifc_mode = match !mode with | Ifc _ -> true | _ -> false in (match !mode with | Get_some_file_deps _ -> if Option.is_none !naming_table then raise (Arg.Bad "--get-some-file-deps requires --naming-table"); if Option.is_none !root then raise (Arg.Bad "--get-some-file-deps requires --root") | _ -> ()); if Option.is_some !naming_table && Option.is_none !root then failwith "--naming-table needs --root"; (* --root implies certain things... *) let root = match !root with | None -> Path.make "/" (* if none specified, we use this dummy *) | Some root -> if Option.is_none !naming_table then failwith "--root needs --naming-table"; (* builtins are already provided by project at --root, so we shouldn't provide our own *) no_builtins := true; (* Following will throw an exception if .hhconfig not found *) let (_config_hash, config) = Config_file.parse_hhconfig (Filename.concat root Config_file.file_path_relative_to_repo_root) in (* We will pick up values from .hhconfig, unless they've been overridden at the command-line. *) if Option.is_none !auto_namespace_map then auto_namespace_map := config |> Config_file.Getters.string_opt "auto_namespace_map" |> Option.map ~f:ServerConfig.convert_auto_namespace_to_map; if Option.is_none !allowed_fixme_codes_strict then allowed_fixme_codes_strict := config |> Config_file.Getters.string_opt "allowed_fixme_codes_strict" |> Option.map ~f:comma_string_to_iset; sharedmem_config := ServerConfig.make_sharedmem_config config (ServerArgs.default_options ~root) ServerLocalConfig.default; (* Path.make canonicalizes it, i.e. resolves symlinks *) Path.make root in let tcopt : GlobalOptions.t = GlobalOptions.set ~tco_saved_state:GlobalOptions.default_saved_state ?po_deregister_php_stdlib:!deregister_attributes ?tco_log_inference_constraints:!log_inference_constraints ?tco_timeout:!timeout ?po_auto_namespace_map:!auto_namespace_map ?tco_disallow_byref_dynamic_calls:!disallow_byref_dynamic_calls ?tco_disallow_byref_calls:!disallow_byref_calls ~allowed_fixme_codes_strict: (Option.value !allowed_fixme_codes_strict ~default:ISet.empty) ~tco_check_xhp_attribute:!check_xhp_attribute ~tco_check_redundant_generics:!check_redundant_generics ~tco_skip_hierarchy_checks:!skip_hierarchy_checks ~tco_skip_tast_checks:!skip_tast_checks ~tco_like_type_hints:!like_type_hints ~tco_union_intersection_type_hints:!union_intersection_type_hints ~tco_strict_contexts:!strict_contexts ~tco_coeffects:!call_coeffects ~tco_coeffects_local:!local_coeffects ~tco_like_casts:false ~log_levels:!log_levels ~po_enable_class_level_where_clauses:!enable_class_level_where_clauses ~po_disable_legacy_soft_typehints:!disable_legacy_soft_typehints ~po_allow_new_attribute_syntax:!allow_new_attribute_syntax ~po_disallow_toplevel_requires:(not !allow_toplevel_requires) ~tco_const_static_props:!const_static_props ~po_disable_legacy_attribute_syntax:!disable_legacy_attribute_syntax ~tco_const_attribute:!const_attribute ~po_const_default_func_args:!const_default_func_args ~po_const_default_lambda_args:!const_default_lambda_args ~po_disallow_silence:!disallow_silence ~po_abstract_static_props:!abstract_static_props ~po_disallow_func_ptrs_in_constants:!disallow_func_ptrs_in_constants ~tco_check_attribute_locations:true ~tco_error_php_lambdas:!error_php_lambdas ~tco_disallow_discarded_nullable_awaitables: !disallow_discarded_nullable_awaitables ~glean_reponame:!glean_reponame ~po_disable_xhp_element_mangling:!disable_xhp_element_mangling ~po_disable_xhp_children_declarations:!disable_xhp_children_declarations ~po_enable_xhp_class_modifier:!enable_xhp_class_modifier ~po_keep_user_attributes:!keep_user_attributes ~po_disable_hh_ignore_error:!disable_hh_ignore_error ~tco_is_systemlib:!is_systemlib ~tco_higher_kinded_types:!enable_higher_kinded_types ~po_allowed_decl_fixme_codes: (Option.value !allowed_decl_fixme_codes ~default:ISet.empty) ~po_allow_unstable_features:true ~tco_method_call_inference:!method_call_inference ~tco_report_pos_from_reason:!report_pos_from_reason ~tco_enable_sound_dynamic:!enable_sound_dynamic ~tco_skip_check_under_dynamic:!skip_check_under_dynamic ~tco_ifc_enabled: (if is_ifc_mode then ["/"] else []) ~tco_global_access_check_enabled:!enable_global_access_check ~po_interpret_soft_types_as_like_types:!interpret_soft_types_as_like_types ~tco_enable_strict_string_concat_interp: !enable_strict_string_concat_interp ~tco_ignore_unsafe_cast:!ignore_unsafe_cast ~tco_math_new_code:!math_new_code ~tco_typeconst_concrete_concrete_error:!typeconst_concrete_concrete_error ~tco_enable_strict_const_semantics:!enable_strict_const_semantics ~tco_strict_wellformedness:!strict_wellformedness ~tco_meth_caller_only_public_visibility: !meth_caller_only_public_visibility ~tco_require_extends_implements_ancestors: !require_extends_implements_ancestors ~tco_strict_value_equality:!strict_value_equality ~tco_enforce_sealed_subclasses:!enforce_sealed_subclasses ~tco_everything_sdt:!everything_sdt ~tco_explicit_consistent_constructors:!explicit_consistent_constructors ~tco_require_types_class_consts:!require_types_class_consts ~tco_type_printer_fuel:!type_printer_fuel ~tco_profile_top_level_definitions:!profile_top_level_definitions ~tco_allow_all_files_for_module_declarations: !allow_all_files_for_module_declarations ~tco_loop_iteration_upper_bound:!loop_iteration_upper_bound ~tco_expression_tree_virtualize_functions: !expression_tree_virtualize_functions ~tco_substitution_mutation:!substitution_mutation ~tco_rust_elab:!rust_elab GlobalOptions.default in let tcopt = let config = List.fold (List.rev !config_overrides) ~init:(Config_file_common.empty ()) ~f:(fun config setting -> let c = Config_file_common.parse_contents setting in Config_file_common.apply_overrides ~config ~overrides:c ~log_reason:None) in ServerConfig.load_config config tcopt in Errors.allowed_fixme_codes_strict := GlobalOptions.allowed_fixme_codes_strict tcopt; Errors.report_pos_from_reason := TypecheckerOptions.report_pos_from_reason tcopt; let tco_experimental_features = tcopt.GlobalOptions.tco_experimental_features in let tco_experimental_features = if !forbid_nullable_cast then SSet.add TypecheckerOptions.experimental_forbid_nullable_cast tco_experimental_features else tco_experimental_features in let tco_experimental_features = if is_ifc_mode then SSet.add TypecheckerOptions.experimental_infer_flows tco_experimental_features else tco_experimental_features in let tco_experimental_features = if !disallow_static_memoized then SSet.add TypecheckerOptions.experimental_disallow_static_memoized tco_experimental_features else tco_experimental_features in let tco_experimental_features = if !enable_supportdyn_hint then SSet.add TypecheckerOptions.experimental_supportdynamic_type_hint tco_experimental_features else tco_experimental_features in let tco_experimental_features = if !always_pessimise_return then SSet.add TypecheckerOptions.experimental_always_pessimise_return tco_experimental_features else tco_experimental_features in let tco_experimental_features = if !consider_type_const_enforceable then SSet.add TypecheckerOptions.experimental_consider_type_const_enforceable tco_experimental_features else tco_experimental_features in let tcopt = { tcopt with GlobalOptions.tco_experimental_features } in let tco_custom_error_config = Option.value ~default:Custom_error_config.empty @@ Option.bind ~f:load_and_parse_custom_error_config !custom_error_config_path in let tcopt = GlobalOptions.{ tcopt with tco_custom_error_config } in ( { files = fns; extra_builtins = !extra_builtins; mode = !mode; no_builtins = !no_builtins; max_errors = !max_errors; error_format = !error_format; tcopt; batch_mode = !batch_mode; out_extension = !out_extension; verbosity = !verbosity; should_print_position = !print_position; custom_hhi_path = !custom_hhi_path; profile_type_check_multi = !profile_type_check_multi; memtrace = !memtrace; rust_provider_backend = !rust_provider_backend; naming_table_path = !naming_table; packages_config_path = !packages_config_path; }, root, if !rust_provider_backend then SharedMem. { !sharedmem_config with shm_use_sharded_hashtbl = true; shm_cache_size = max !sharedmem_config.shm_cache_size (2 * 1024 * 1024 * 1024); } else !sharedmem_config ) let print_elapsed fn desc ~start_time = let elapsed_ms = Float.(Unix.gettimeofday () - start_time) *. 1000. in Printf.printf "%s: %s - %0.2fms\n" (Relative_path.to_absolute fn |> Filename.basename) desc elapsed_ms let check_file ctx errors files_info ~profile_type_check_multi ~memtrace = let profiling = Option.is_some profile_type_check_multi in if profiling then Relative_path.Map.iter files_info ~f:(fun fn (_fileinfo : FileInfo.t) -> let full_ast = Ast_provider.get_ast ctx fn ~full:true in let start_time = Unix.gettimeofday () in let _ = Typing_check_job.calc_errors_and_tast ctx fn ~full_ast in print_elapsed fn "first typecheck+decl" ~start_time); let tracer = Option.map memtrace ~f:(fun filename -> Memtrace.start_tracing ~context:None ~sampling_rate:Memtrace.default_sampling_rate ~filename) in let add_timing fn timings closure = let start_cpu = Sys.time () in let result = Lazy.force closure in let elapsed_cpu_time = Sys.time () -. start_cpu in let add_sample = function | Some samples -> Some (elapsed_cpu_time :: samples) | None -> Some [elapsed_cpu_time] in let timings = Relative_path.Map.update fn add_sample timings in (result, timings) in let rec go n timings = let (errors, timings) = Relative_path.Map.fold files_info ~f:(fun fn _fileinfo (errors, timings) -> let full_ast = Ast_provider.get_ast ctx fn ~full:true in let ((new_errors, _tast), timings) = add_timing fn timings @@ lazy (Typing_check_job.calc_errors_and_tast ctx fn ~full_ast) in (errors @ Errors.get_sorted_error_list new_errors, timings)) ~init:(errors, timings) in if n > 1 then go (n - 1) timings else (errors, timings) in let n_of_times_to_typecheck = max 1 (Option.value ~default:1 profile_type_check_multi) in let timings = Relative_path.Map.empty in let (errors, timings) = go n_of_times_to_typecheck timings in let print_elapsed_cpu_time fn samples = let mean = mean samples in Printf.printf "%s: %d typechecks - %f ± %f (s)\n" (Relative_path.to_absolute fn |> Filename.basename) n_of_times_to_typecheck mean (standard_deviation mean samples) in if profiling then Relative_path.Map.iter timings ~f:print_elapsed_cpu_time; Option.iter tracer ~f:Memtrace.stop_tracing; errors let create_nasts ctx files_info = let build_nast fn _ = let (syntax_errors, ast) = Ast_provider.get_ast_with_error ~full:true ctx fn in let error_list = Errors.get_sorted_error_list syntax_errors in List.iter error_list ~f:Errors.add_error; Naming.program ctx ast in Relative_path.Map.mapi ~f:build_nast files_info (** This is an almost-pure function which returns what we get out of parsing. The only side-effect it has is on the global errors list. *) let parse_and_name ctx files_contents = Relative_path.Map.mapi files_contents ~f:(fun fn contents -> (* Get parse errors. *) let () = Errors.run_in_context fn (fun () -> let popt = Provider_context.get_tcopt ctx in let parsed_file = Full_fidelity_ast.defensive_program popt fn contents in let ast = let { Parser_return.ast; _ } = parsed_file in if ParserOptions.deregister_php_stdlib popt then Nast.deregister_ignored_attributes ast else ast in Ast_provider.provide_ast_hint fn ast Ast_provider.Full; ()) in match Direct_decl_utils.direct_decl_parse ctx fn with | None -> failwith "no file contents" | Some decls -> Direct_decl_utils.decls_to_fileinfo fn decls) (** This function is used for gathering naming and parsing errors, and the side-effect of updating the global reverse naming table (and picking up duplicate-name errors along the way), and for the side effect of updating the decl heap (and picking up decling errors along the way). *) let parse_name_and_decl ctx files_contents = Errors.do_ (fun () -> let files_info = parse_and_name ctx files_contents in Relative_path.Map.iter files_info ~f:(fun fn fileinfo -> let _failed_naming_fns = Naming_global.ndecl_file_and_get_conflict_files ctx fn fileinfo in ()); Relative_path.Map.iter files_info ~f:(fun fn _ -> Decl.make_env ~sh:SharedMem.Uses ctx fn); files_info) (** This function is used solely for its side-effect of putting decls into shared-mem *) let add_decls_to_heap ctx files_contents = Errors.ignore_ (fun () -> let files_info = parse_and_name ctx files_contents in Relative_path.Map.iter files_info ~f:(fun fn _ -> Decl.make_env ~sh:SharedMem.Uses ctx fn)); () (** This function doesn't have side-effects. Its sole job is to return shallow decls. *) let get_shallow_decls ctx filename file_contents : Shallow_decl_defs.shallow_class SMap.t = let popt = Provider_context.get_popt ctx in let opts = DeclParserOptions.from_parser_options popt in (Direct_decl_parser.parse_decls opts filename file_contents) .Direct_decl_parser.pf_decls |> List.fold ~init:SMap.empty ~f:(fun acc (name, decl) -> match decl with | Shallow_decl_defs.Class c -> SMap.add name c acc | _ -> acc) let test_shallow_class_diff ctx filename = let filename_after = Relative_path.to_absolute filename ^ ".after" in let contents1 = Sys_utils.cat (Relative_path.to_absolute filename) in let contents2 = Sys_utils.cat filename_after in let decls1 = get_shallow_decls ctx filename contents1 in let decls2 = get_shallow_decls ctx filename contents2 in let decls = SMap.merge (fun _ a b -> Some (a, b)) decls1 decls2 |> SMap.bindings in let diffs = List.map decls ~f:(fun (cid, old_and_new) -> ( Utils.strip_ns cid, match old_and_new with | (Some c1, Some c2) -> Shallow_class_diff.diff_class (Provider_context.get_package_info ctx) c1 c2 | (None, None) -> ClassDiff.(Major_change MajorChange.Unknown) | (None, Some _) -> ClassDiff.(Major_change MajorChange.Added) | (Some _, None) -> ClassDiff.(Major_change MajorChange.Removed) )) in List.iter diffs ~f:(fun (cid, diff) -> Format.printf "%s: %a@." cid ClassDiff.pp diff) let add_newline contents = (* this is used for incremental mode to change all the positions, so we basically want a prepend; there's a few cases we need to handle: - empty file - header line: apppend after header - shebang and header: append after header - shebang only, no header (e.g. .hack file): append after shebang - no header or shebang (e.g. .hack file): prepend *) let after_shebang = if String.is_prefix contents ~prefix:"#!" then String.index_exn contents '\n' + 1 else 0 in let after_header = if String.length contents > after_shebang + 2 && String.equal (String.sub contents ~pos:after_shebang ~len:2) "<?" then String.index_from_exn contents after_shebang '\n' + 1 else after_shebang in String.sub contents ~pos:0 ~len:after_header ^ "\n" ^ String.sub contents ~pos:after_header ~len:(String.length contents - after_header) (* Might raise because of Option.value_exn *) let get_decls defs = ( SSet.fold (fun x acc -> Option.value_exn ~message:"Decl not found" (Decl_heap.Typedefs.get x) :: acc) defs.FileInfo.n_types [], SSet.fold (fun x acc -> Option.value_exn ~message:"Decl not found" (Decl_heap.Funs.get x) :: acc) defs.FileInfo.n_funs [], SSet.fold (fun x acc -> Option.value_exn ~message:"Decl not found" (Decl_heap.Classes.get x) :: acc) defs.FileInfo.n_classes [] ) let fail_comparison s = raise (Failure (Printf.sprintf "Comparing %s failed!\n" s ^ "It's likely that you added new positions to decl types " ^ "without updating Decl_pos_utils.NormalizeSig\n")) let compare_typedefs t1 t2 = let t1 = Decl_pos_utils.NormalizeSig.typedef t1 in let t2 = Decl_pos_utils.NormalizeSig.typedef t2 in if Poly.(t1 <> t2) then fail_comparison "typedefs" let compare_funs f1 f2 = let f1 = Decl_pos_utils.NormalizeSig.fun_elt f1 in let f2 = Decl_pos_utils.NormalizeSig.fun_elt f2 in if Poly.(f1 <> f2) then fail_comparison "funs" let compare_classes mode c1 c2 = if Decl_compare.class_big_diff c1 c2 then fail_comparison "class_big_diff"; let c1 = Decl_pos_utils.NormalizeSig.class_type c1 in let c2 = Decl_pos_utils.NormalizeSig.class_type c2 in let (_, is_unchanged) = Decl_compare.ClassDiff.compare mode c1.Decl_defs.dc_name c1 c2 in if not is_unchanged then fail_comparison "ClassDiff"; let (_, is_unchanged) = Decl_compare.ClassEltDiff.compare mode c1 c2 in match is_unchanged with | `Changed -> fail_comparison "ClassEltDiff" | _ -> () let test_decl_compare ctx filenames builtins files_contents files_info = (* skip some edge cases that we don't handle now... ugly! *) if String.equal (Relative_path.suffix filenames) "capitalization3.php" then () else if String.equal (Relative_path.suffix filenames) "capitalization4.php" then () else (* do not analyze builtins over and over *) let files_info = Relative_path.Map.fold builtins ~f: begin (fun k _ acc -> Relative_path.Map.remove acc k) end ~init:files_info in let files = Relative_path.Map.fold files_info ~f:(fun k _ acc -> Relative_path.Set.add acc k) ~init:Relative_path.Set.empty in let defs = Relative_path.Map.fold files_info ~f: begin fun _ names1 names2 -> FileInfo.(merge_names (simplify names1) names2) end ~init:FileInfo.empty_names in let (typedefs1, funs1, classes1) = get_decls defs in (* For the purpose of this test, we can ignore other heaps *) Ast_provider.remove_batch files; let get_classes path = match Relative_path.Map.find_opt files_info path with | None -> SSet.empty | Some info -> SSet.of_list @@ List.map info.FileInfo.classes ~f:(fun (_, x, _) -> x) in (* We need to oldify, not remove, for ClassEltDiff to work *) Decl_redecl_service.oldify_type_decl ctx None get_classes ~bucket_size:1 ~defs ~collect_garbage:false; let files_contents = Relative_path.Map.map files_contents ~f:add_newline in add_decls_to_heap ctx files_contents; let (typedefs2, funs2, classes2) = get_decls defs in let deps_mode = Provider_context.get_deps_mode ctx in List.iter2_exn typedefs1 typedefs2 ~f:compare_typedefs; List.iter2_exn funs1 funs2 ~f:compare_funs; List.iter2_exn classes1 classes2 ~f:(compare_classes deps_mode); () let compute_nasts ctx files_info interesting_files = let nasts = create_nasts ctx files_info in (* Interesting files are usually the non hhi ones. *) let filter_non_interesting nasts = Relative_path.Map.merge nasts interesting_files ~f:(fun _k nast x -> match (nast, x) with | (Some nast, Some _) -> Some nast | _ -> None) in filter_non_interesting nasts (* Returns a list of Tast defs, along with associated type environments. *) let compute_tasts ?(drop_fixmed = true) ctx files_info interesting_files : Errors.t * Tast.program Relative_path.Map.t = let _f _k nast x = match (nast, x) with | (Some nast, Some _) -> Some nast | _ -> None in Errors.do_ ~drop_fixmed (fun () -> let nasts = compute_nasts ctx files_info interesting_files in let tasts = Relative_path.Map.map nasts ~f:(fun nast -> let tast = Typing_toplevel.nast_to_tast ~do_tast_checks:true ctx nast in if TypecheckerOptions.enable_sound_dynamic (Provider_context.get_tcopt ctx) then List.concat (Tast_with_dynamic.all tast) else tast.Tast_with_dynamic.under_normal_assumptions) in tasts) let compute_tasts_by_name ?(drop_fixmed = true) ctx files_info interesting_files : Errors.t * Tast.by_names Relative_path.Map.t = let (nast_errors, nasts) = Errors.do_ ~drop_fixmed (fun () -> compute_nasts ctx files_info interesting_files) in let errors_and_tasts = Relative_path.Map.mapi nasts ~f:(fun fn full_ast -> Typing_check_job.calc_errors_and_tast ctx ~drop_fixmed fn ~full_ast) in let tasts = Relative_path.Map.map ~f:snd errors_and_tasts in let tast_errors = Relative_path.Map.values errors_and_tasts |> List.map ~f:fst in ( List.fold (nast_errors :: tast_errors) ~init:Errors.empty ~f:Errors.merge, tasts ) (* Given source code containing a caret marker (e.g. "^ hover-at-caret"), return the line and column of the position indicated. *) let caret_pos (src : string) (marker : string) : int * int = let lines = String.split_lines src in match List.findi lines ~f:(fun _ line -> String.is_substring line ~substring:marker) with | Some (line_num, line_src) -> let col_num = String.lfindi line_src ~f:(fun _ c -> match c with | '^' -> true | _ -> false) in (line_num, Option.value_exn col_num + 1) | None -> failwith (Printf.sprintf "Could not find any occurrence of '%s' in source code" marker) (* Given source code containing the patterns [start_marker] and [end_marker], calculate the range between the markers *) let find_ide_range src : Ide_api_types.range = let start_marker = "/*range-start*/" in let end_marker = "/*range-end*/" in let lines = String.split_lines src in let find_line marker = List.findi lines ~f:(fun _ line -> String.is_substring line ~substring:marker) in let find_marker marker after_or_before = let (line_zero_indexed, start_line_src) = find_line marker |> Option.value_exn ~message:(Format.sprintf "couldn't find marker %s" marker) in let line = line_zero_indexed + 1 in let column = let marker_start = Str.search_forward (Str.regexp_string marker) start_line_src 0 in let column_adjustment = match after_or_before with | `After -> String.length marker + 1 | `Before -> 1 in marker_start + column_adjustment in Ide_api_types.{ line; column } in let st = find_marker start_marker `After in let ed = find_marker end_marker `Before in Ide_api_types.{ st; ed } (** * Compute TASTs for some files, then expand all type variables. *) let compute_tasts_expand_types ctx files_info interesting_files = let (errors, tasts) = compute_tasts ctx files_info interesting_files in let tasts = Relative_path.Map.map tasts ~f:(Tast_expand.expand_program ctx) in (errors, tasts) let decl_parse_typecheck_and_then ctx files_contents f = let (parse_errors, files_info) = parse_name_and_decl ctx files_contents in let parse_errors = Errors.get_sorted_error_list parse_errors in let (errors, _tasts) = compute_tasts_expand_types ctx files_info files_contents in let errors = parse_errors @ Errors.get_sorted_error_list errors in if List.is_empty errors then f files_info else print_errors_if_present errors let print_nasts ~should_print_position nasts filenames = List.iter filenames ~f:(fun filename -> match Relative_path.Map.find_opt nasts filename with | None -> Printf.eprintf "Could not find nast for file %s\n" (Relative_path.show filename); Printf.eprintf "Available nasts:\n"; Relative_path.Map.iter nasts ~f:(fun path _ -> Printf.eprintf " %s\n" (Relative_path.show path)) | Some nast -> if should_print_position then Naming_ast_print.print_nast nast else Naming_ast_print.print_nast_without_position nast) let print_tasts ~should_print_position tasts ctx = Relative_path.Map.iter tasts ~f:(fun _k (tast : Tast.program) -> if should_print_position then Typing_ast_print.print_tast ctx tast else Typing_ast_print.print_tast_without_position ctx tast) let pp_debug_deps fmt entries = Format.fprintf fmt "@[<v>"; ignore @@ List.fold_left entries ~init:false ~f:(fun sep (obj, roots) -> if sep then Format.fprintf fmt "@;"; Format.fprintf fmt "%s -> " obj; Format.fprintf fmt "@[<hv>"; ignore @@ List.fold_left roots ~init:false ~f:(fun sep root -> if sep then Format.fprintf fmt ",@ "; Format.pp_print_string fmt root; true); Format.fprintf fmt "@]"; true); Format.fprintf fmt "@]" let show_debug_deps = Format.asprintf "%a" pp_debug_deps let sort_debug_deps deps = Hashtbl.fold deps ~init:[] ~f:(fun ~key:obj ~data:set acc -> (obj, set) :: acc) |> List.sort ~compare:(fun (a, _) (b, _) -> String.compare a b) |> List.map ~f:(fun (obj, roots) -> let roots = HashSet.fold roots ~init:[] ~f:List.cons |> List.sort ~compare:String.compare in (obj, roots)) (* Note: this prints dependency graph edges in the same direction as the mapping which is actually stored in the shared memory table. The line "X -> Y" can be read, "X is used by Y", or "X is a dependency of Y", or "when X changes, Y must be rechecked". *) let dump_debug_deps dbg_deps = dbg_deps |> sort_debug_deps |> show_debug_deps |> Printf.printf "%s\n" let handle_constraint_mode ~do_ name opts ctx error_format ~iter_over_files ~profile_type_check_multi ~memtrace = (* Process a single typechecked file *) let process_file path info = match info.FileInfo.file_mode with | Some FileInfo.Mstrict -> let (ctx, entry) = Provider_context.add_entry_if_missing ~ctx ~path in let { Tast_provider.Compute_tast.tast; _ } = Tast_provider.compute_tast_unquarantined ~ctx ~entry in let tast = List.concat (Tast_with_dynamic.all tast) in do_ opts ctx tast | _ -> (* We are not interested in partial files and there is nothing in HHI files to analyse *) () in let print_errors = List.iter ~f:(print_error ~oc:stdout error_format) in (* Process a multifile that is not typechecked *) let process_multifile filename = Printf.printf "=== %s analysis results for %s\n%!" name (Relative_path.to_absolute filename); let files_contents = Multifile.file_to_files filename in let (parse_errors, file_info) = parse_name_and_decl ctx files_contents in let error_list = Errors.get_sorted_error_list parse_errors in let check_errors = check_file ctx error_list file_info ~profile_type_check_multi ~memtrace in if not (List.is_empty check_errors) then print_errors check_errors else Relative_path.Map.iter file_info ~f:process_file in let process_multifile filename = Provider_utils.respect_but_quarantine_unsaved_changes ~ctx ~f:(fun () -> process_multifile filename) in iter_over_files process_multifile let scrape_class_names (ast : Nast.program) : SSet.t = let names = ref SSet.empty in let visitor = object (* It would look less clumsy to use Aast.reduce, but would use set union which has higher complexity. *) inherit [_] Aast.iter method! on_class_name _ (_p, id) = names := SSet.add id !names end in visitor#on_program () ast; !names (** Scrape names in file and return the files where those names are defined. *) let get_some_file_dependencies ctx (file : Relative_path.t) : Relative_path.Set.t = let open Hh_prelude in let nast = Ast_provider.get_ast ctx ~full:true file in let names = Errors.ignore_ (fun () -> Naming.program ctx nast) |> scrape_class_names (* TODO: scape other defs too *) in SSet.fold (fun class_name files -> match Naming_provider.get_class_path ctx class_name with | None -> files | Some file -> Relative_path.Set.add files file) names Relative_path.Set.empty (** Recursively scrape names in files and return the files where those names are defined. *) let traverse_file_dependencies ctx (files : Relative_path.t list) ~(depth : int) : Relative_path.Set.t = let rec traverse (files : Relative_path.Set.t) depth (visited : Relative_path.Set.t) (results : Relative_path.Set.t) = if Int.( <= ) depth 0 then Relative_path.Set.union files results else let (next_files, visited, results) = Relative_path.Set.fold files ~init:(Relative_path.Set.empty, visited, results) ~f:(fun file (next_files, visited, results) -> if Relative_path.Set.mem visited file then (next_files, visited, results) else let visited = Relative_path.Set.add visited file in let dependencies = get_some_file_dependencies ctx file in let next_files = Relative_path.Set.union dependencies next_files in let results = Relative_path.Set.add results file in (next_files, visited, results)) in traverse next_files (depth - 1) visited results in traverse (Relative_path.Set.of_list files) depth Relative_path.Set.empty Relative_path.Set.empty (** Used for testing code that generates patches. *) let codemod ~files_info ~files_contents ctx (get_patches : files_info:FileInfo.t Relative_path.Map.t -> ServerRenameTypes.patch list) = let decl_parse_typecheck_and_then = decl_parse_typecheck_and_then ctx in let backend = Provider_context.get_backend ctx in (* Because we repeatedly apply the codemod, positions change. So we need to re-parse, decl, and typecheck the file to generated accurate patches as well as amend the patched test files in memory. This involves invalidating a number of shared heaps and providing in memory replacements after patching files. *) let invalidate_heaps_and_update_files files_info files_contents = let paths_to_purge = Relative_path.Map.keys files_contents |> Relative_path.Set.of_list in (* Purge the file, then provide its replacement, otherwise the replacement is dropped on the floor. *) File_provider.remove_batch paths_to_purge; Relative_path.Map.iter ~f:File_provider.provide_file_for_tests files_contents; Ast_provider.remove_batch paths_to_purge; Relative_path.Map.iter ~f:(fun path file_info -> (* Don't invalidate builtins, otherwise, we can't find them. *) if not (Relative_path.prefix path |> Relative_path.is_hhi) then Naming_global.remove_decls_using_file_info backend file_info) files_info in let rec go files_info files_contents = invalidate_heaps_and_update_files files_info files_contents; decl_parse_typecheck_and_then files_contents @@ fun files_info -> let patches = get_patches ~files_info in let files_contents = ServerRenameTypes.apply_patches_to_file_contents files_contents patches in if List.is_empty patches then Multifile.print_files_as_multifile files_contents else go files_info files_contents in go files_info files_contents; (* Typecheck after the codemod is fully applied to confirm that what we produce is not garbage. *) Printf.printf "\nTypechecking after the codemod... (no output after this is good news)\n"; invalidate_heaps_and_update_files files_info files_contents; decl_parse_typecheck_and_then files_contents ignore let handle_mode mode filenames ctx builtins files_contents files_info parse_errors max_errors error_format batch_mode out_extension dbg_deps ~should_print_position ~profile_type_check_multi ~memtrace ~verbosity = let expect_single_file () : Relative_path.t = match filenames with | [x] -> x | _ -> die "Only single file expected" in let iter_over_files f : unit = List.iter filenames ~f in match mode with | Refactor_sound_dynamic (analysis_mode, refactor_mode, element_name) -> let opts = match ( Refactor_sd_options.parse_analysis_mode analysis_mode, Refactor_sd_options.parse_refactor_mode refactor_mode ) with | (Some analysis_mode, Some refactor_mode) -> Refactor_sd_options.mk ~analysis_mode ~refactor_mode | (None, _) -> die "invalid refactor_sd analysis mode" | (_, None) -> die "invalid refactor_sd refactor mode" in handle_constraint_mode ~do_:(Refactor_sd.do_ element_name) "Sound Dynamic" opts ctx error_format ~iter_over_files ~profile_type_check_multi ~memtrace | SDT_analysis command -> handle_constraint_mode ~do_:(Sdt_analysis.do_ ~command ~on_bad_command:die ~verbosity) "SDT" () ctx error_format ~iter_over_files ~profile_type_check_multi ~memtrace | Shape_analysis mode -> let opts = match Shape_analysis_options.parse_mode mode with | Some (command, mode) -> Shape_analysis_options.mk ~command ~mode ~verbosity | None -> die "invalid shape analysis mode" in handle_constraint_mode ~do_:Shape_analysis.do_ "Shape" opts ctx error_format ~iter_over_files ~profile_type_check_multi ~memtrace | Ifc (mode, lattice) -> (* Timing mode is same as check except we print out the time it takes to analyse the file. *) let (mode, should_time) = if String.equal mode "time" then ("check", true) else (mode, false) in let ifc_opts = match Ifc_options.parse ~mode ~lattice with | Ok opts -> opts | Error e -> die ("could not parse IFC options: " ^ e) in let time f = let start_time = Unix.gettimeofday () in let result = Lazy.force f in let elapsed_time = Unix.gettimeofday () -. start_time in if should_time then Printf.printf "Duration: %f\n" elapsed_time; result in let print_errors = List.iter ~f:(print_error ~oc:stdout error_format) in let process_file filename = Printf.printf "=== IFC analysis results for %s\n%!" (Relative_path.to_absolute filename); let files_contents = Multifile.file_to_files filename in let (parse_errors, file_info) = parse_name_and_decl ctx files_contents in let check_errors = let error_list = Errors.get_sorted_error_list parse_errors in check_file ctx error_list file_info ~profile_type_check_multi ~memtrace in if not (List.is_empty check_errors) then print_errors check_errors else try let ifc_errors = time @@ lazy (Ifc_main.do_ ifc_opts file_info ctx) in if not (List.is_empty ifc_errors) then print_errors ifc_errors with | exn -> let e = Exception.wrap exn in Stdlib.Printexc.register_printer (function | Ifc_types.IFCError err -> Some (Printf.sprintf "IFCError(%s)" @@ Ifc_types.show_ifc_error_ty err) | _ -> None); Printf.printf "Uncaught exception: %s" (Exception.to_string e) in iter_over_files (fun filename -> Provider_utils.respect_but_quarantine_unsaved_changes ~ctx ~f:(fun () -> process_file filename)) | Cst_search -> let path = expect_single_file () in let (ctx, entry) = Provider_context.add_entry_if_missing ~ctx ~path in let result = let open Result.Monad_infix in Sys_utils.read_stdin_to_string () |> Hh_json.json_of_string |> CstSearchService.compile_pattern ctx >>| CstSearchService.search ctx entry >>| CstSearchService.result_to_json ~sort_results:true >>| Hh_json.json_to_string ~pretty:true in begin match result with | Ok result -> Printf.printf "%s\n" result | Error message -> Printf.printf "%s\n" message; exit 1 end | Dump_symbol_info -> iter_over_files (fun filename -> match Relative_path.Map.find_opt files_info filename with | Some _fileinfo -> let raw_result = SymbolInfoServiceUtils.helper ctx [] [filename] in let result = SymbolInfoServiceUtils.format_result raw_result in let result_json = ServerCommandTypes.Symbol_info_service.to_json result in print_endline (Hh_json.json_to_multiline result_json) | None -> ()) | Glean_index out_dir -> if (not (Disk.is_directory out_dir)) || Array.length (Sys.readdir out_dir) > 0 then ( Printf.printf "%s should be an empty dir\n" out_dir; exit 1 ) else Symbol_entrypoint.index_files ctx ~out_dir ~files:filenames | Glean_sym_hash -> List.iter (Symbol_entrypoint.sym_hashes ctx ~files:filenames) ~f:(fun (path, hash) -> Printf.printf "%s %s\n" path (Md5.to_hex hash)) | Lint -> let lint_errors = Relative_path.Map.fold files_contents ~init:[] ~f:(fun fn content lint_errors -> lint_errors @ fst (Lints_core.do_ (fun () -> Linting_main.lint ctx fn content))) in if not (List.is_empty lint_errors) then ( let lint_errors = List.sort ~compare: begin fun x y -> Pos.compare (Lints_core.get_pos x) (Lints_core.get_pos y) end lint_errors in let lint_errors = List.map ~f:Lints_core.to_absolute lint_errors in ServerLintTypes.output_text stdout lint_errors error_format; exit 2 ) else Printf.printf "No lint errors\n" | Lint_json -> let json_errors = Relative_path.Map.fold files_contents ~init:[] ~f:(fun fn content json_errors -> json_errors @ fst (Lints_core.do_ (fun () -> Linting_main.lint ctx fn content))) in let json_errors = List.sort ~compare: begin fun x y -> Pos.compare (Lints_core.get_pos x) (Lints_core.get_pos y) end json_errors in let json_errors = List.map ~f:Lints_core.to_absolute json_errors in ServerLintTypes.output_json ~pretty:true stdout json_errors; exit 2 | Dump_deps -> Relative_path.Map.iter files_info ~f:(fun fn _fileinfo -> let full_ast = Ast_provider.get_ast ctx fn ~full:true in ignore @@ Typing_check_job.calc_errors_and_tast ctx fn ~full_ast); if Hashtbl.length dbg_deps > 0 then dump_debug_deps dbg_deps | Dump_dep_hashes -> iter_over_files (fun _ -> let nasts = create_nasts ctx files_info in Relative_path.Map.iter nasts ~f:(fun _ nast -> Dep_hash_to_symbol.dump nast)) | Get_some_file_deps depth -> let file_deps = traverse_file_dependencies ctx filenames ~depth in Relative_path.Set.iter file_deps ~f:(fun file -> Printf.printf "%s\n" (Relative_path.to_absolute file)) | Dump_inheritance -> let open ServerCommandTypes.Method_jumps in let naming_table = Naming_table.create files_info in Naming_table.iter naming_table ~f:(fun fn fileinfo -> if Relative_path.Map.mem builtins fn then () else ( List.iter fileinfo.FileInfo.classes ~f:(fun (_p, class_, _) -> Printf.printf "Ancestors of %s and their overridden methods:\n" class_; let ancestors = (* Might raise {!Naming_table.File_info_not_found} *) MethodJumps.get_inheritance ctx class_ ~filter:No_filter ~find_children:false naming_table None in ServerCommandTypes.Method_jumps.print_readable ancestors ~find_children:false; Printf.printf "\n"); Printf.printf "\n"; List.iter fileinfo.FileInfo.classes ~f:(fun (_p, class_, _) -> Printf.printf "Children of %s and the methods they override:\n" class_; let children = (* Might raise {!Naming_table.File_info_not_found} *) MethodJumps.get_inheritance ctx class_ ~filter:No_filter ~find_children:true naming_table None in ServerCommandTypes.Method_jumps.print_readable children ~find_children:true; Printf.printf "\n") )) | Identify_symbol (line, column) -> let path = expect_single_file () in let (ctx, entry) = Provider_context.add_entry_if_missing ~ctx ~path in (* TODO(ljw): surely this doesn't need quarantine? *) let result = Provider_utils.respect_but_quarantine_unsaved_changes ~ctx ~f:(fun () -> ServerIdentifyFunction.go_quarantined_absolute ~ctx ~entry ~line ~column) in begin match result with | [] -> print_endline "None" | result -> ClientGetDefinition.print_readable ~short_pos:true result end | Ide_code_actions { title_prefix; use_snippet_edits } -> let path = expect_single_file () in let (ctx, entry) = Provider_context.add_entry_if_missing ~ctx ~path in let src = Provider_context.read_file_contents_exn entry in let range = find_ide_range src in Code_actions_cli_lib.run ctx entry range ~title_prefix ~use_snippet_edits | Find_local (line, char) -> let filename = expect_single_file () in let (ctx, entry) = Provider_context.add_entry_if_missing ~ctx ~path:filename in let result = ServerFindLocals.go ~ctx ~entry ~line ~char in let print pos = Printf.printf "%s\n" (Pos.string_no_file pos) in List.iter result ~f:print | Outline -> iter_over_files (fun filename -> let file = cat (Relative_path.to_absolute filename) in let results = FileOutline.outline (Provider_context.get_popt ctx) file in FileOutline.print ~short_pos:true results) | Dump_nast -> let (errors, nasts) = Errors.do_ (fun () -> create_nasts ctx files_info) in print_errors_if_present (Errors.get_sorted_error_list errors); print_nasts ~should_print_position nasts (Relative_path.Map.keys files_contents) | Dump_tast -> let (errors, tasts) = compute_tasts_expand_types ctx files_info files_contents in print_errors_if_present (parse_errors @ Errors.get_sorted_error_list errors); print_tasts ~should_print_position tasts ctx | Dump_stripped_tast -> iter_over_files (fun filename -> let files_contents = Relative_path.Map.filter files_contents ~f:(fun k _v -> Relative_path.equal k filename) in let (_, tasts) = compute_tasts ctx files_info files_contents in let tast = Relative_path.Map.find tasts filename in let nast = Tast.to_nast tast in Printf.printf "%s\n" (Nast.show_program nast)) | RemoveDeadUnsafeCasts -> let ctx = Provider_context.map_tcopt ctx ~f:(fun tcopt -> GlobalOptions.{ tcopt with tco_populate_dead_unsafe_cast_heap = true }) in let get_patches ~files_info = Remove_dead_unsafe_casts.get_patches ~is_test:true ~files_info ~fold:Relative_path.Map.fold in codemod ~files_info ~files_contents ctx get_patches | Find_refs (line, column) -> let path = expect_single_file () in let naming_table = Naming_table.create files_info in let genv = ServerEnvBuild.default_genv in let init_id = Random_id.short_string () in let env = { (ServerEnvBuild.make_env ~init_id ~deps_mode:(Typing_deps_mode.InMemoryMode None) genv.ServerEnv.config) with ServerEnv.naming_table; ServerEnv.tcopt = Provider_context.get_tcopt ctx; } in let include_defs = true in let (ctx, entry) = Provider_context.add_entry_if_missing ~ctx:(Provider_utils.ctx_from_server_env env) ~path in let open ServerCommandTypes.Done_or_retry in Provider_utils.respect_but_quarantine_unsaved_changes ~ctx ~f:(fun () -> match ServerFindRefs.go_from_file_ctx ~ctx ~entry ~line ~column with | None -> () | Some (name, action) -> let results = match ServerFindRefs.go ctx action include_defs ~stream_file:None ~hints:[] genv env with | (_env, Done r) -> ServerFindRefs.to_absolute r | (_env, Retry) -> failwith "didn't expect retry" in Printf.printf "%s\n" name; FindRefsWireFormat.CliHumanReadable.print_results (List.rev results)) | Go_to_impl (line, column) -> let filename = expect_single_file () in let naming_table = Naming_table.create files_info in let genv = ServerEnvBuild.default_genv in let init_id = Random_id.short_string () in let env = { (ServerEnvBuild.make_env ~init_id ~deps_mode:(Typing_deps_mode.InMemoryMode None) genv.ServerEnv.config) with ServerEnv.naming_table; ServerEnv.tcopt = Provider_context.get_tcopt ctx; } in let filename = Relative_path.to_absolute filename in let contents = cat filename in let (ctx, entry) = Provider_context.add_or_overwrite_entry_contents ~ctx:(Provider_utils.ctx_from_server_env env) ~path:(Relative_path.create_detect_prefix filename) ~contents in let open ServerCommandTypes.Done_or_retry in begin match ServerFindRefs.go_from_file_ctx ~ctx ~entry ~line ~column with | None -> () | Some (name, action) -> let results = match ServerGoToImpl.go ~action ~genv ~env with | (_env, Done r) -> ServerFindRefs.to_absolute r | (_env, Retry) -> failwith "didn't expect retry" in Printf.printf "%s\n" name; FindRefsWireFormat.CliHumanReadable.print_results (List.rev results) end | Highlight_refs (line, column) -> let path = expect_single_file () in let (ctx, entry) = Provider_context.add_entry_if_missing ~ctx ~path in let results = ServerHighlightRefs.go_quarantined ~ctx ~entry ~line ~column in ClientHighlightRefs.go results ~output_json:false | Errors when batch_mode -> (* For each file in our batch, run typechecking serially. Reset the heaps every time in between. *) iter_over_files (fun filename -> let oc = Out_channel.create (Relative_path.to_absolute filename ^ out_extension) in (* This means builtins had errors, so lets just print those if we see them *) if not (List.is_empty parse_errors) then (* This closes the out channel *) write_error_list error_format parse_errors oc max_errors else ( Typing_log.out_channel := oc; Provider_utils.respect_but_quarantine_unsaved_changes ~ctx ~f:(fun () -> let files_contents = Multifile.file_to_files filename in Relative_path.Map.iter files_contents ~f:(fun filename contents -> File_provider.(provide_file_for_tests filename contents)); let (parse_errors, individual_file_info) = parse_name_and_decl ctx files_contents in let errors = check_file ctx (Errors.get_sorted_error_list parse_errors) individual_file_info ~profile_type_check_multi ~memtrace in write_error_list error_format errors oc max_errors) )) | Decl_compare when batch_mode -> (* For each file in our batch, run typechecking serially. Reset the heaps every time in between. *) iter_over_files (fun filename -> let oc = Out_channel.create (Relative_path.to_absolute filename ^ ".decl_out") in Provider_utils.respect_but_quarantine_unsaved_changes ~ctx ~f:(fun () -> let files_contents = Relative_path.Map.filter files_contents ~f:(fun k _v -> Relative_path.equal k filename) in let (_, individual_file_info) = parse_name_and_decl ctx files_contents in try test_decl_compare ctx filename builtins files_contents individual_file_info; Out_channel.output_string oc "" with | e -> let msg = Exn.to_string e in Out_channel.output_string oc msg); Out_channel.close oc) | Errors -> (* Don't typecheck builtins *) let errors = check_file ctx parse_errors files_info ~profile_type_check_multi ~memtrace in print_error_list error_format errors max_errors; if not (List.is_empty errors) then exit 2 | Decl_compare -> let filename = expect_single_file () in (* Might raise because of Option.value_exn *) test_decl_compare ctx filename builtins files_contents files_info | Shallow_class_diff -> print_errors_if_present parse_errors; let filename = expect_single_file () in test_shallow_class_diff ctx filename | Get_member class_and_member_id -> let (cid, mid) = match Str.split (Str.regexp "::") class_and_member_id with | [cid; mid] -> (cid, mid) | _ -> failwith (Printf.sprintf "Invalid --get-member ID: %S" class_and_member_id) in let cid = Utils.add_ns cid in (match Decl_provider.get_class ctx cid with | None -> Printf.printf "No class named %s\n" cid | Some cls -> let ty_to_string ty = let env = Typing_env_types.empty ctx Relative_path.default ~droot:None in Typing_print.full_strip_ns_decl env ty in let print_class_element member_type get mid = match get cls mid with | None -> () | Some ce -> let abstract = if Typing_defs.get_ce_abstract ce then "abstract " else "" in let origin = ce.Typing_defs.ce_origin in let from = if String.equal origin cid then "" else Printf.sprintf " from %s" (Utils.strip_ns origin) in Printf.printf " %s%s%s: %s\n" abstract member_type from (ty_to_string (Lazy.force ce.Typing_defs.ce_type)) in Printf.printf "%s::%s\n" cid mid; print_class_element "method" Cls.get_method mid; print_class_element "static method" Cls.get_smethod mid; print_class_element "property" Cls.get_prop mid; print_class_element "static property" Cls.get_sprop mid; print_class_element "static property" Cls.get_sprop ("$" ^ mid); (match Cls.get_const cls mid with | None -> () | Some cc -> let abstract = Typing_defs.( match cc.cc_abstract with | CCAbstract _ -> "abstract " | CCConcrete -> "") in let origin = cc.Typing_defs.cc_origin in let from = if String.equal origin cid then "" else Printf.sprintf " from %s" (Utils.strip_ns origin) in let ty = ty_to_string cc.Typing_defs.cc_type in Printf.printf " %sconst%s: %s\n" abstract from ty); (match Cls.get_typeconst cls mid with | None -> () | Some ttc -> let origin = ttc.Typing_defs.ttc_origin in let from = if String.equal origin cid then "" else Printf.sprintf " from %s" (Utils.strip_ns origin) in let ty = let open Typing_defs in match ttc.ttc_kind with | TCConcrete { tc_type = ty } -> "= " ^ ty_to_string ty | TCAbstract { atc_as_constraint = as_cstr; atc_super_constraint = _; atc_default = default; } -> String.concat ~sep:" " (List.filter_map [ Option.map as_cstr ~f:(fun ty -> "as " ^ ty_to_string ty); Option.map default ~f:(fun ty -> "= " ^ ty_to_string ty); ] ~f:(fun x -> x)) in let abstract = Typing_defs.( match ttc.ttc_kind with | TCConcrete _ -> "" | TCAbstract _ -> "abstract ") in Printf.printf " %stypeconst%s: %s %s\n" abstract from mid ty); ()) | Hover pos_given -> let filename = expect_single_file () in let (ctx, entry) = Provider_context.add_entry_if_missing ~ctx ~path:filename in let (line, column) = match pos_given with | Some (line, column) -> (line, column) | None -> let src = Provider_context.read_file_contents_exn entry in caret_pos src "^ hover-at-caret" in let results = ServerHover.go_quarantined ~ctx ~entry ~line ~column in let formatted_results = List.map ~f:(fun r -> let open HoverService in String.concat ~sep:"\n" (r.snippet :: r.addendum)) results in Printf.printf "%s\n" (String.concat ~sep:"\n-------------\n" formatted_results) | Apply_quickfixes -> let path = expect_single_file () in let (ctx, entry) = Provider_context.add_entry_if_missing ~ctx ~path in let (errors, _) = compute_tasts ~drop_fixmed:false ctx files_info files_contents in let src = Relative_path.Map.find files_contents path in let quickfixes = Errors.get_error_list ~drop_fixmed:false errors |> List.map ~f:(fun e -> (* If an error has multiple possible quickfixes, take the first. *) List.hd (User_error.quickfixes e)) |> List.filter_opt in let cst = Ast_provider.compute_cst ~ctx ~entry in let tree = Provider_context.PositionedSyntaxTree.root cst in let classish_starts = match entry.Provider_context.source_text with | Some source_text -> Quickfix_ffp.classish_starts tree source_text entry.Provider_context.path | None -> SMap.empty in (* Print the title of each quickfix, so we can see text changes in tests. *) List.iter quickfixes ~f:(fun qf -> Printf.printf "%s\n" (Quickfix.get_title qf)); (* Print the source code after applying all these quickfixes. *) Printf.printf "\n%s" (Quickfix.apply_all src classish_starts quickfixes) | CountImpreciseTypes -> let (errors, tasts) = compute_tasts_expand_types ctx files_info files_contents in if not @@ Errors.is_empty errors then ( print_errors error_format errors max_errors; Printf.printf "Did not count imprecise types because there are typing errors."; exit 2 ) else let tasts = Relative_path.Map.values tasts in let results = List.map ~f:(Count_imprecise_types.count ctx) tasts |> List.fold ~f:(SMap.union ~combine:(fun id _ -> failwith ("Clash at " ^ id))) ~init:SMap.empty in let json = Count_imprecise_types.json_of_results results in Printf.printf "%s" (Hh_json.json_to_string json) | Get_type_hierarchy -> let path = expect_single_file () in let (ctx, entry) = Provider_context.add_entry_if_missing ~ctx ~path in let src = Provider_context.read_file_contents_exn entry in let (line, column) = caret_pos src "^ type-hierarchy-at-caret" in let results = ServerTypeHierarchy.go_quarantined ~ctx ~entry ~line ~column in let json = ServerTypeHierarchy.json_of_results ~results in Printf.printf "%s" (Hh_json.json_to_string ~pretty:true json) | Map_reduce_mode -> let (errors, tasts) = compute_tasts_by_name ctx files_info files_contents in print_errors_if_present (parse_errors @ Errors.get_sorted_error_list errors); let mapped = Relative_path.Map.elements tasts |> List.map ~f:(fun (fn, tasts) -> Map_reduce.map ctx fn tasts) in let reduced = List.fold mapped ~init:Map_reduce.empty ~f:Map_reduce.reduce in let json = Map_reduce_ffi.yojson_of_t (Map_reduce.to_ffi reduced) in Yojson.Safe.pretty_to_channel Caml.stdout json (*****************************************************************************) (* Main entry point *) (*****************************************************************************) let decl_and_run_mode { files; extra_builtins; mode; error_format; no_builtins; tcopt; max_errors; batch_mode; out_extension; verbosity; should_print_position; custom_hhi_path; profile_type_check_multi; memtrace; rust_provider_backend; naming_table_path; packages_config_path; } (hhi_root : Path.t) : unit = Ident.track_names := true; let builtins = if no_builtins then Relative_path.Map.empty else let extra_builtins = let add_file_content map filename = Relative_path.create Relative_path.Dummy filename |> Multifile.file_to_file_list |> List.map ~f:(fun (path, contents) -> (Filename.basename (Relative_path.suffix path), contents)) |> List.unordered_append map in extra_builtins |> List.fold ~f:add_file_content ~init:[] |> Array.of_list in let magic_builtins = Array.append magic_builtins extra_builtins in let hhi_builtins = match custom_hhi_path with | None -> hhi_builtins | Some path -> Array.of_list (Hhi_get.get_hhis_in_dir path) in (* Check that magic_builtin filenames are unique *) let () = let n_of_builtins = Array.length magic_builtins in let n_of_unique_builtins = Array.to_list magic_builtins |> List.map ~f:fst |> SSet.of_list |> SSet.cardinal in if n_of_builtins <> n_of_unique_builtins then die "Multiple magic builtins share the same base name.\n" in Array.iter magic_builtins ~f:(fun (file_name, file_contents) -> let file_path = Path.concat hhi_root file_name in let file = Path.to_string file_path in Sys_utils.try_touch (Sys_utils.Touch_existing { follow_symlinks = true }) file; Sys_utils.write_file ~file file_contents); (* Take the builtins (file, contents) array and create relative paths *) Array.fold (Array.append magic_builtins hhi_builtins) ~init:Relative_path.Map.empty ~f:(fun acc (f, src) -> let f = Path.concat hhi_root f |> Path.to_string in Relative_path.Map.add acc ~key:(Relative_path.create Relative_path.Hhi f) ~data:src) in let files = if use_canonical_filenames () then let canonicalize_path path = match Sys_utils.realpath path with | Some path -> Relative_path.create_detect_prefix path | None -> failwith ("Couldn't resolve realpath of " ^ path) in files |> List.map ~f:canonicalize_path else files |> List.map ~f:(Relative_path.create Relative_path.Dummy) in let files_contents = List.fold files ~f:(fun acc filename -> let files_contents = Multifile.file_to_files filename in Relative_path.Map.union acc files_contents) ~init:Relative_path.Map.empty in (* Merge in builtins *) let files_contents_with_builtins = Relative_path.Map.fold builtins ~f: begin (fun k src acc -> Relative_path.Map.add acc ~key:k ~data:src) end ~init:files_contents in Relative_path.Map.iter files_contents ~f:(fun filename contents -> File_provider.(provide_file_for_tests filename contents)); (* Don't declare all the filenames in batch_errors mode *) let to_decl = if batch_mode then builtins else files_contents_with_builtins in let dbg_deps = Hashtbl.Poly.create () in (match mode with | Dump_deps -> (* In addition to actually recording the dependencies in shared memory, we build a non-hashed respresentation of the dependency graph for printing. *) let get_debug_trace root obj = let root = Typing_deps.Dep.variant_to_string root in let obj = Typing_deps.Dep.variant_to_string obj in match Hashtbl.find dbg_deps obj with | Some set -> HashSet.add set root | None -> let set = HashSet.create () in HashSet.add set root; Hashtbl.set dbg_deps ~key:obj ~data:set in Typing_deps.add_dependency_callback ~name:"get_debug_trace" get_debug_trace | _ -> ()); let package_info = match packages_config_path with | None -> PackageInfo.empty | Some _ -> let (_errors, info) = PackageConfig.load_and_parse ~pkgs_config_abs_path:packages_config_path () in info in let tcopt = { tcopt with GlobalOptions.tco_package_info = package_info } in let ctx = if rust_provider_backend then ( Provider_backend.set_rust_backend tcopt; Provider_context.empty_for_tool ~popt:tcopt ~tcopt ~backend:(Provider_backend.get ()) ~deps_mode:(Typing_deps_mode.InMemoryMode None) ) else Provider_context.empty_for_test ~popt:tcopt ~tcopt ~deps_mode:(Typing_deps_mode.InMemoryMode None) in (* We make the following call for the side-effect of updating ctx's "naming-table fallback" so it will look in the sqlite database for names it doesn't know. This function returns the forward naming table. *) let naming_table_for_root : Naming_table.t option = Option.map naming_table_path ~f:(fun path -> Naming_table.load_from_sqlite ctx path) in (* If run in naming-table mode, we first have to remove any old names from the files we're about to redeclare -- otherwise when we declare them it'd count as a duplicate definition! *) Option.iter naming_table_for_root ~f:(fun naming_table_for_root -> Relative_path.Map.iter files_contents ~f:(fun file _content -> let file_info = Naming_table.get_file_info naming_table_for_root file in Option.iter file_info ~f:(fun file_info -> let ids_to_strings ids = List.map ids ~f:(fun (_, name, _) -> name) in Naming_global.remove_decls ~backend:(Provider_context.get_backend ctx) ~funs:(ids_to_strings file_info.FileInfo.funs) ~classes:(ids_to_strings file_info.FileInfo.classes) ~typedefs:(ids_to_strings file_info.FileInfo.typedefs) ~consts:(ids_to_strings file_info.FileInfo.consts) ~modules:(ids_to_strings file_info.FileInfo.modules)))); let (errors, files_info) = parse_name_and_decl ctx to_decl in handle_mode mode files ctx builtins files_contents files_info (Errors.get_sorted_error_list errors) max_errors error_format batch_mode out_extension dbg_deps ~should_print_position ~profile_type_check_multi ~memtrace ~verbosity let main_hack opts (root : Path.t) (sharedmem_config : SharedMem.config) : unit = (* TODO: We should have a per file config *) Sys_utils.signal Sys.sigusr1 (Sys.Signal_handle Typing.debug_print_last_pos); EventLogger.init_fake (); ServerProgress.disable (); Measure.push_global (); let (_handle : SharedMem.handle) = SharedMem.init ~num_workers:0 sharedmem_config in let process custom hhi_root = if custom then let hhi_root_s = Path.to_string hhi_root in if Disk.file_exists hhi_root_s && Disk.is_directory hhi_root_s then Hhi.set_custom_hhi_root hhi_root else die ("Custom hhi directory " ^ hhi_root_s ^ " not found") else Hhi.set_hhi_root_for_unit_test hhi_root; Relative_path.set_path_prefix Relative_path.Root root; Relative_path.set_path_prefix Relative_path.Hhi hhi_root; Relative_path.set_path_prefix Relative_path.Tmp (Path.make "tmp"); decl_and_run_mode opts hhi_root; TypingLogger.flush_buffers () in match opts.custom_hhi_path with | Some hhi_root -> process true (Path.make hhi_root) | None -> Tempfile.with_tempdir (fun hhi_root -> process false hhi_root) (* command line driver *) let () = if !Sys.interactive then () else (* On windows, setting 'binary mode' avoids to output CRLF on stdout. The 'text mode' would not hurt the user in general, but it breaks the testsuite where the output is compared to the expected one (i.e. in given file without CRLF). *) Out_channel.set_binary_mode stdout true; let (options, root, sharedmem_config) = parse_options () in Unix.handle_unix_error main_hack options root sharedmem_config
OCaml
hhvm/hphp/hack/src/lwt_unix.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. * *) (** This file exists only to ensure that we don't accidentally link hh_server against Lwt_unix. Something about the Lwt_unix module initialization messes with signals in such a way that many of our raw Unix.XXX IO calls fail with EINTR, so adding this fake module causes us to have a build failure if we ever link against Lwt_unix from inside hh_server. EINTR is technically retryable, and we could fix it by finding every single existing raw IO call and wrapping them, but we'd have to make sure that no raw IO ever got checked in again without being guarded. Given that, we felt it was more future-proof to just forbid Lwt_unix. For more context, view T37072141. *)
Shell Script
hhvm/hphp/hack/src/oxidized_regen.sh
#!/bin/bash set -u # terminate upon read of uninitalized variable set -o pipefail # in a pipe, the whole pipe runs, but its exit code is that of the first failure CYAN="" WHITE="" BOLD="" RESET="" # If these fail that's just fine. if [ -t 1 ]; then CYAN=$(tput setaf 6) WHITE=$(tput setaf 7) BOLD=$(tput bold) RESET=$(tput sgr0) fi set -e # terminate upon non-zero-exit-codes (in case of pipe, only checks at end of pipe) trap 'echo "exit code $? at line $LINENO" >&2' ERR function summary { echo -e "\n$BOLD$CYAN==>$WHITE ${1}$RESET" } # Try to get the path of this script relative to fbcode/. #set -x # echo every statement in the script FBCODE_ROOT="$(dirname "${BASH_SOURCE[0]}")/../../.." REGEN_COMMAND="$(realpath --relative-to="${FBCODE_ROOT}" "${BASH_SOURCE[0]}")" cd "$FBCODE_ROOT" # rustfmt is committed at fbsource/tools/third-party/rustfmt/rustfmt RUSTFMT_PATH="${RUSTFMT_PATH:-"$(realpath ../tools/third-party/rustfmt/rustfmt)"}" BUILD_AND_RUN="hphp/hack/scripts/build_and_run.sh" summary "Write oxidized/gen/" "${BUILD_AND_RUN}" src/hh_oxidize hh_oxidize \ --out-dir hphp/hack/src/oxidized/gen \ --regen-command "$REGEN_COMMAND" \ --rustfmt-path "$RUSTFMT_PATH" \ --copy-types-file hphp/hack/src/oxidized/copy_types.txt \ hphp/hack/src/annotated_ast/aast_defs.ml \ hphp/hack/src/annotated_ast/namespace_env.ml \ hphp/hack/src/ast/ast_defs.ml \ hphp/hack/src/custom_error/custom_error.ml \ hphp/hack/src/custom_error/custom_error_config.ml \ hphp/hack/src/custom_error/error_message.ml \ hphp/hack/src/custom_error/patt_binding_ty.ml \ hphp/hack/src/custom_error/patt_error.ml \ hphp/hack/src/custom_error/patt_locl_ty.ml \ hphp/hack/src/custom_error/patt_name.ml \ hphp/hack/src/custom_error/patt_string.ml \ hphp/hack/src/custom_error/patt_var.ml \ hphp/hack/src/custom_error/validation_err.ml \ hphp/hack/src/decl/decl_defs.ml \ hphp/hack/src/decl/pos/pos_or_decl.ml \ hphp/hack/src/decl/shallow_decl_defs.ml \ hphp/hack/src/errors/user_error.ml \ hphp/hack/src/errors/errors.ml \ hphp/hack/src/errors/error_codes.ml \ hphp/hack/src/errors/message.ml \ hphp/hack/src/naming/name_context.ml \ hphp/hack/src/naming/naming_error.ml \ hphp/hack/src/typing/nast_check/nast_check_error.ml \ hphp/hack/src/parser/parsing_error.ml \ hphp/hack/src/errors/quickfix.ml \ hphp/hack/src/naming/naming_phase_error.ml \ hphp/hack/src/options/declParserOptions.ml \ hphp/hack/src/options/globalOptions.ml \ hphp/hack/src/options/parserOptions.ml \ hphp/hack/src/options/saved_state_rollouts.ml \ hphp/hack/src/options/typecheckerOptions.ml \ hphp/hack/src/package/package.ml \ hphp/hack/src/package/packageInfo.ml \ hphp/hack/src/parser/full_fidelity_parser_env.ml \ hphp/hack/src/search/utils/searchTypes.ml \ hphp/hack/src/typing/service/tast_hashes.ml \ hphp/hack/src/typing/service/type_counter.ml \ hphp/hack/src/typing/service/map_reduce_ffi.ml \ hphp/hack/src/typing/tast.ml \ hphp/hack/src/typing/tast_with_dynamic.ml \ hphp/hack/src/typing/type_parameter_env.ml \ hphp/hack/src/typing/typing_defs_core.ml \ hphp/hack/src/typing/typing_defs.ml \ hphp/hack/src/typing/typing_inference_env.ml \ hphp/hack/src/typing/typing_kinding_defs.ml \ hphp/hack/src/typing/typing_reason.ml \ hphp/hack/src/typing/typing_tyvar_occurrences.ml \ hphp/hack/src/typing/xhp_attribute.ml \ hphp/hack/src/utils/decl_reference.ml \ hphp/hack/src/parser/scoured_comments.ml \ # Add exports in oxidized/lib.rs from oxidized/gen/mod.rs. # BSD sed doesn't have -i sed "/^pub use gen::/d" hphp/hack/src/oxidized/lib.rs > hphp/hack/src/oxidized/lib.rs.tmp mv hphp/hack/src/oxidized/lib.rs.tmp hphp/hack/src/oxidized/lib.rs grep "^pub mod " hphp/hack/src/oxidized/gen/mod.rs | sed 's/^pub mod /pub use gen::/' >> hphp/hack/src/oxidized/lib.rs summary "Write individually-converted oxidized files" "${BUILD_AND_RUN}" src/hh_oxidize hh_oxidize --regen-command "$REGEN_COMMAND" --rustfmt-path "$RUSTFMT_PATH" hphp/hack/src/deps/fileInfo.ml > hphp/hack/src/deps/rust/file_info.rs "${BUILD_AND_RUN}" src/hh_oxidize hh_oxidize --regen-command "$REGEN_COMMAND" --rustfmt-path "$RUSTFMT_PATH" hphp/hack/src/utils/core/prim_defs.ml > hphp/hack/src/deps/rust/prim_defs.rs "${BUILD_AND_RUN}" src/hh_oxidize hh_oxidize --regen-command "$REGEN_COMMAND" --rustfmt-path "$RUSTFMT_PATH" hphp/hack/src/naming/naming_types.ml > hphp/hack/src/naming/rust/naming_types.rs "${BUILD_AND_RUN}" src/hh_oxidize hh_oxidize --regen-command "$REGEN_COMMAND" --rustfmt-path "$RUSTFMT_PATH" hphp/hack/src/lints/lints_core.ml > hphp/hack/src/utils/lint/lint.rs "${BUILD_AND_RUN}" src/hh_oxidize hh_oxidize --regen-command "$REGEN_COMMAND" --rustfmt-path "$RUSTFMT_PATH" hphp/hack/src/typing/hh_distc_types.ml > hphp/hack/src/typing/hh_distc_types/hh_distc_types.rs summary "Write oxidized/impl_gen/" "${BUILD_AND_RUN}" src/hh_codegen hh_codegen \ --regen-cmd "$REGEN_COMMAND" \ --rustfmt "$RUSTFMT_PATH" \ enum-helpers \ --input "hphp/hack/src/oxidized/gen/aast_defs.rs|crate::aast_defs::*|crate::ast_defs|crate::LocalIdMap" \ --input "hphp/hack/src/oxidized/gen/ast_defs.rs|crate::ast_defs::*" \ --output "hphp/hack/src/oxidized/impl_gen/" \ summary "Write oxidized/aast_visitor/" "${BUILD_AND_RUN}" src/hh_codegen hh_codegen \ --regen-cmd "$REGEN_COMMAND" \ --rustfmt "$RUSTFMT_PATH" \ visitor \ --input "hphp/hack/src/oxidized/gen/aast_defs.rs" \ --input "hphp/hack/src/oxidized/gen/ast_defs.rs" \ --output "hphp/hack/src/oxidized/aast_visitor/" \ --root "Program" \ summary "Write oxidized/asts" "${BUILD_AND_RUN}" src/hh_codegen hh_codegen \ --regen-cmd "$REGEN_COMMAND" \ --rustfmt "$RUSTFMT_PATH" \ asts \ --input "hphp/hack/src/oxidized/gen/aast_defs.rs" \ --input "hphp/hack/src/oxidized/gen/ast_defs.rs" \ --output "hphp/hack/src/oxidized/asts/" \ --root "Program" \ summary "Write elab/transform/" "${BUILD_AND_RUN}" src/hh_codegen hh_codegen \ --regen-cmd "$REGEN_COMMAND" \ --rustfmt "$RUSTFMT_PATH" \ elab-transform \ --input "hphp/hack/src/oxidized/gen/aast_defs.rs" \ --input "hphp/hack/src/oxidized/gen/ast_defs.rs" \ --output "hphp/hack/src/elab/" \ --root "Program" \ summary "Write oxidized_by_ref/gen/" "${BUILD_AND_RUN}" src/hh_oxidize hh_oxidize \ --out-dir hphp/hack/src/oxidized_by_ref/gen \ --regen-command "$REGEN_COMMAND" \ --rustfmt-path "$RUSTFMT_PATH" \ --extern-types-file hphp/hack/src/oxidized_by_ref/extern_types.txt \ --owned-types-file hphp/hack/src/oxidized_by_ref/owned_types.txt \ --copy-types-file hphp/hack/src/oxidized_by_ref/copy_types.txt \ --by-ref \ hphp/hack/src/annotated_ast/aast_defs.ml \ hphp/hack/src/annotated_ast/namespace_env.ml \ hphp/hack/src/ast/ast_defs.ml \ hphp/hack/src/custom_error/custom_error.ml \ hphp/hack/src/custom_error/custom_error_config.ml \ hphp/hack/src/custom_error/error_message.ml \ hphp/hack/src/custom_error/patt_binding_ty.ml \ hphp/hack/src/custom_error/patt_error.ml \ hphp/hack/src/custom_error/patt_locl_ty.ml \ hphp/hack/src/custom_error/patt_name.ml \ hphp/hack/src/custom_error/patt_string.ml \ hphp/hack/src/custom_error/patt_var.ml \ hphp/hack/src/custom_error/validation_err.ml \ hphp/hack/src/decl/decl_defs.ml \ hphp/hack/src/decl/pos/pos_or_decl.ml \ hphp/hack/src/decl/shallow_decl_defs.ml \ hphp/hack/src/deps/fileInfo.ml \ hphp/hack/src/naming/naming_types.ml \ hphp/hack/src/naming/nast.ml \ hphp/hack/src/options/saved_state_rollouts.ml \ hphp/hack/src/package/package.ml \ hphp/hack/src/package/packageInfo.ml \ hphp/hack/src/parser/scoured_comments.ml \ hphp/hack/src/typing/typing_defs_core.ml \ hphp/hack/src/typing/typing_defs.ml \ hphp/hack/src/typing/typing_reason.ml \ hphp/hack/src/typing/xhp_attribute.ml \ hphp/hack/src/utils/decl_reference.ml \ hphp/hack/src/utils/core/prim_defs.ml \ # Add exports in oxidized_by_ref/lib.rs from oxidized_by_ref/gen/mod.rs. # BSD sed doesn't have -i sed "/^pub use gen::/d" hphp/hack/src/oxidized_by_ref/lib.rs > hphp/hack/src/oxidized_by_ref/lib.rs.tmp mv hphp/hack/src/oxidized_by_ref/lib.rs.tmp hphp/hack/src/oxidized_by_ref/lib.rs grep "^pub mod " hphp/hack/src/oxidized_by_ref/gen/mod.rs | sed 's/^pub mod /pub use gen::/' >> hphp/hack/src/oxidized_by_ref/lib.rs summary "Write oxidized_by_ref/decl_visitor/" "${BUILD_AND_RUN}" src/hh_codegen hh_codegen \ --regen-cmd "$REGEN_COMMAND" \ --rustfmt "$RUSTFMT_PATH" \ by-ref-decl-visitor \ --input "hphp/hack/src/oxidized_by_ref/gen/ast_defs.rs" \ --input "hphp/hack/src/oxidized_by_ref/gen/shallow_decl_defs.rs" \ --input "hphp/hack/src/oxidized_by_ref/gen/typing_defs_core.rs" \ --input "hphp/hack/src/oxidized_by_ref/gen/typing_defs.rs" \ --input "hphp/hack/src/oxidized_by_ref/gen/typing_reason.rs" \ --input "hphp/hack/src/oxidized_by_ref/gen/xhp_attribute.rs" \ --input "hphp/hack/src/oxidized_by_ref/manual/direct_decl_parser.rs" \ --input "hphp/hack/src/oxidized_by_ref/manual/t_shape_map.rs" \ --extern-input "hphp/hack/src/oxidized/gen/ast_defs.rs" \ --extern-input "hphp/hack/src/oxidized/gen/typing_defs.rs" \ --extern-input "hphp/hack/src/oxidized/gen/typing_defs_core.rs" \ --extern-input "hphp/hack/src/oxidized/gen/typing_reason.rs" \ --extern-input "hphp/hack/src/oxidized/gen/xhp_attribute.rs" \ --output "hphp/hack/src/oxidized_by_ref/decl_visitor/" \ --root "Decls" \
Markdown
hhvm/hphp/hack/src/style_guide.md
Style Guide =========== As far as indentation rules go, ocp-indent should be used as the final word. However, here are some examples. Let Expressions --------------- Try to fit a `let ... in` onto one line: let foo = bar x y z in ... If the expression is too long, first try let foo = some_long_expression_bar x y z in ... If the second line is still too long, fall back to let foo = some_long_expression_bar long_arg_1 long_arg_2 long_arg_3 in Match Clauses ------------- Don't indent the clauses of a standalone match expression match foo with | Some x -> ... | None -> ... However, if the match expression is the RHS of a let expression, do indent them: let bar = match foo with | Some x -> ... | None -> ... in ... Alternatively, if `foo` is too long, move the `match` to the next line: let foo = match some_long_expression arg1 arg2 with | Some x -> ... | None -> ... in ... If the expression between `match ... with` is too long to fit into one line, split it out as in separate `let` expression. That is, instead of let foo = match some_long_expression arg1 arg2 with | Some x -> ... | None -> ... in ... Prefer let bar = some_long_expression arg1 arg2 in let foo = match bar with | Some x -> ... | None -> ... in ... Note that the `in` should be on its own line. I.e. avoid let bar = match foo with | Some x -> ... | None -> ... in ... Functions --------- Function expressions that span multiple lines should be wrapped in a `begin ... end`: List.iter foo begin fun x -> ... end However, expressions on a single line should use parentheses: List.map foo (fun x -> x + 1) In general, function bodies should be indented. However, we make an exception if `fun` comes right after an operator (typically one of `>>=`, `@@`, or `>>|`): some_monadic_x >>= fun x -> some_monadic_y >>= fun y -> return x + y Modules ------- Top-level modules (those created by individual files) should be named using Underscore_separated_words. Modules within files should be CamelCase. Top-level module opens should be reserved only for very commonly used modules, like `Utils`. Aside from those, prefer module LMN = Long_module_name or use local opens: let open Long_module_name in ... Modules should have the name of their containing directory as a prefix. E.g. modules under typing/ should be named as `Typing_foo`. Parentheses ----------- Generally, there are only two cases where parentheses / `begin ... end` are necessary: for nesting `with` clauses and for inserting multiple semicolon-separated expressions into the `then` clause of an `if`-expression. match foo with | Some x -> begin match bar with | Some y -> ... | None -> ... end | None -> ... if foo then begin do_something (); do_another_thing (); end If the test expression is too long, the following is also acceptable: if long_expression arg1 arg2 then begin do_something (); do_another_thing (); end Variants -------- Variants should be named using `Capitalized_underscore_separated_words`. This includes polymorphic variants; i.e. we want `\`Foo` and not `\`foo`. In fact, the OCaml manual suggests that lowercase polymorphic variants may be deprecated in future versions. Miscellany ---------- Boolean function parameters should always be labeled. Consider labeling integer parameters as well. Try to use exhaustive matching whenever possible. That is, avoid the wildcard `_` match.
hhvm/hphp/hack/src/_tags
true: package(unix),package(str),package(bigarray),package(ppx_deriving.std) <**/*.ml*>: ocaml, warn_A, warn(-3-4-6-29-35-44-48-50-52) <*.ml*>: warn(-27) <hhi/hhi.ml>: ppx(ppx/ppx_gen_hhi hhi) <client/*.ml*>: warn(-27) <deps/*.ml*>: warn(-27) <dfind/*.ml*>: warn(-27) <format/*.ml*>: warn(-27) <heap/*.ml*>: warn(-27-34) <naming/*.ml*>: warn(-27-45) <parsing/*.ml*>: warn(-27) <ppx/*.ml*>: package(ocaml-migrate-parsetree) <ppx>: -traverse <procs/*.ml*>: warn(-27) <server/serverInit.ml>: warn(-41-45) <third-party/avl/*.ml*>: warn(-27) <third-party/core/*.ml*>: warn(-32-41) <utils/*.ml*>: warn(-27) not <{dfind,find,heap,injection,socket,third-party,fsnotify,stubs}/**/*>: package(core_kernel), package(visitors.ppx), package(visitors.runtime), package(pcre), package(lwt), package(lwt.unix), package(lwt_ppx), package(lwt_log) <{utils,watchman,search,procs,globals}/**/*>: -package(pcre)
hhvm/hphp/hack/src/ai/dune
(* -*- tuareg -*- *) let library_entry name suffix = Printf.sprintf "(library (name %s) (wrapped false) (modules) (libraries %s_%s))" name name suffix let executable_entry is_fb name = if is_fb then Printf.sprintf "(executable (name %s) (modules %s) (modes exe byte_complete) (link_flags (:standard (:include ../dune_config/ld-opts.sexp))) (libraries default_injector_config %s_fb))" name name name else Printf.sprintf "(executable (name %s) (modules %s) (modes exe byte_complete) (libraries))" name name let fb_entry name = library_entry name "fb" let stubs_entry name = library_entry name "stubs" let entry is_fb name = if is_fb then fb_entry name else stubs_entry name let () = (* test presence of fb subfolder *) let current_dir = Sys.getcwd () in (* we are in src/ai, locate src/facebook *) let src_dir = Filename.dirname current_dir in let fb_dir = Filename.concat src_dir "facebook" in (* locate src/facebook/dune *) let fb_dune = Filename.concat fb_dir "dune" in let is_fb = Sys.file_exists fb_dune in let ai = entry is_fb "ai" in let ai_options = entry is_fb "ai_options" in let zoncolan = executable_entry is_fb "zoncolan" in String.concat "\n" [ai_options; ai; zoncolan] |> Jbuild_plugin.V1.send
OCaml
hhvm/hphp/hack/src/ai/zoncolan.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. * *) (* Intentionally left blank *)